Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Remove shelljs from appsmithctl #37401

Merged
merged 6 commits into from
Nov 15, 2024
Merged

chore: Remove shelljs from appsmithctl #37401

merged 6 commits into from
Nov 15, 2024

Conversation

sharat87
Copy link
Member

@sharat87 sharat87 commented Nov 15, 2024

Remove shelljs dependency from appsmithctl, instead using our own much smaller utility functions to run external commands.

Now esbuild should be able to build appsmithctl project nicely! For a future PR.

Automation

/test sanity

🔍 Cypress test results

Warning

Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/11857542672
Commit: a2d5a61
Cypress dashboard.
Tags: @tag.Sanity
Spec:
It seems like no tests ran 😔. We are not able to recognize it, please check workflow here.


Fri, 15 Nov 2024 13:58:27 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Introduced an asynchronous database import process for improved control flow and error handling.
    • Added a new function to execute commands and return their output as a promise.
  • Bug Fixes

    • Enhanced error handling to ensure the supervisor is running before proceeding with database operations.
  • Tests

    • Added a new test suite for the command execution function, validating various output scenarios.
  • Chores

    • Removed unnecessary dependencies from the project configuration.

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces significant modifications to the import_db.js, index.js, utils.js, and related test files. Key changes include the transformation of the import_database function into an asynchronous importDatabase, alongside renaming and enhancing the run function. A new utility function, execCommandReturningOutput, is added to improve command execution handling. The package.json file sees the removal of the shelljs dependency, streamlining the project. Tests are added to validate the new command execution functionality.

Changes

File Path Change Summary
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js Renamed import_database to importDatabase, converted to async; renamed main to run, also async; enhanced error handling and command execution logic.
deploy/docker/fs/opt/appsmith/utils/bin/index.js Renamed method import_db.runImportDatabase to import_db.run to reflect changes in import_db.js.
deploy/docker/fs/opt/appsmith/utils/bin/utils.js Added execCommandReturningOutput function to execute commands and return output as a promise.
deploy/docker/fs/opt/appsmith/utils/bin/utils.test.js Added tests for execCommandReturningOutput to validate output from various command executions.
deploy/docker/fs/opt/appsmith/utils/package.json Removed dependency on shelljs, kept readline-sync unchanged.

Possibly related PRs

Suggested reviewers

  • trishaanand
  • pratapaprasanna
  • mohanarpit
  • nidhi-nair

🎉 In the code's embrace, functions dance and play,
Async now, they lead the way!
With commands that return their might,
Errors caught, all feels just right.
Goodbye to shelljs, we bid adieu,
In the world of code, we start anew! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Nov 15, 2024
@sharat87 sharat87 added the ok-to-test Required label for CI label Nov 15, 2024
@sharat87 sharat87 marked this pull request as ready for review November 15, 2024 09:01
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
deploy/docker/fs/opt/appsmith/utils/bin/utils.test.js (1)

7-10: Consider adding edge cases for the echo command test.

While the basic test is good, consider adding cases for empty input and special characters.

+  test("Output of echo with empty input", async () => {
+    const result = await utils.execCommandReturningOutput(["echo", ""]);
+    expect(result).toBe("");
+  });
+
+  test("Output of echo with special characters", async () => {
+    const result = await utils.execCommandReturningOutput(["echo", "hello$world\n"]);
+    expect(result).toBe("hello$world\\n");
+  });
deploy/docker/fs/opt/appsmith/utils/bin/index.js (1)

Line range hint 14-18: Consider consolidating duplicate environment variable handling logic

The APPSMITH_DB_URL fallback logic is duplicated before and after loading the .env file. While this might be intentional, consider consolidating this into a single function for better maintainability.

+function ensureDbUrl() {
+  if (!process.env.APPSMITH_DB_URL) {
+    process.env.APPSMITH_DB_URL = process.env.APPSMITH_MONGODB_URI;
+    delete process.env.APPSMITH_MONGODB_URI;
+  }
+}

-// Check if APPSMITH_DB_URL is set, if not set, fall back to APPSMITH_MONGODB_URI
-if (!process.env.APPSMITH_DB_URL) {
-  process.env.APPSMITH_DB_URL = process.env.APPSMITH_MONGODB_URI;
-  delete process.env.APPSMITH_MONGODB_URI;
-}
+ensureDbUrl();

// Loading latest application configuration
require("dotenv").config({ path: APPLICATION_CONFIG_PATH });

-// AGAIN: Check if APPSMITH_DB_URL is set, if not set, fall back to APPSMITH_MONGODB_URI
-if (!process.env.APPSMITH_DB_URL) {
-  process.env.APPSMITH_DB_URL = process.env.APPSMITH_MONGODB_URI;
-  delete process.env.APPSMITH_MONGODB_URI;
-}
+ensureDbUrl();

Also applies to: 21-25

🧰 Tools
🪛 Biome

[error] 43-43: Illegal return statement outside of a function

(parse)

deploy/docker/fs/opt/appsmith/utils/bin/utils.js (1)

94-121: LGTM! Well-structured command execution implementation.

The implementation properly handles command execution, output collection, and error cases. A few suggestions to make it more robust:

Consider these improvements:

 function execCommandReturningOutput(cmd, options) {
   return new Promise((resolve, reject) => {
     const p = childProcess.spawn(cmd[0], cmd.slice(1), options);
-
-    p.stdin.end()
+    // Handle spawn errors
+    p.on("error", (err) => {
+      reject(`Failed to start command: ${err.message}`);
+    });
+
+    if (p.stdin) {
+      p.stdin.end();
+    }

     const outChunks = [], errChunks = [];
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (1)

6-14: Standardize logging messages

Consider updating the log statements for consistency and clarity.

Apply this diff:

-  console.log('import_database  ....')
+  console.log('Starting database import...')
...
-  console.log('import_database done')
+  console.log('Database import completed.')
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6fc6327 and 2e85d1b.

⛔ Files ignored due to path filters (1)
  • deploy/docker/fs/opt/appsmith/utils/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/index.js (1 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/utils.js (2 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/utils.test.js (1 hunks)
  • deploy/docker/fs/opt/appsmith/utils/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • deploy/docker/fs/opt/appsmith/utils/package.json
🔇 Additional comments (8)
deploy/docker/fs/opt/appsmith/utils/bin/utils.test.js (4)

5-6: LGTM! Clear test suite structure.


12-15: LGTM! Clear stdout verification.


17-20: LGTM! Clear stderr verification.


22-30: Verify output ordering assumptions across environments.

The tests assume stdout always appears before stderr in the output string, regardless of the actual order of operations. This might not be consistent across different Node.js versions or operating systems.

deploy/docker/fs/opt/appsmith/utils/bin/index.js (1)

41-41: LGTM! Method rename looks good.

The change from runImportDatabase to run aligns with the PR objective and maintains consistent parameter passing.

deploy/docker/fs/opt/appsmith/utils/bin/utils.js (2)

228-228: LGTM! Export added correctly.

The new function is properly exported in the module exports.


94-121: Verify complete removal of shelljs dependency.

Since this function is part of the shelljs removal effort, let's verify there are no remaining shelljs usages.

deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (1)

62-62: 🛠️ Refactor suggestion

Avoid using process.exit() in asynchronous code

Calling process.exit() can interrupt pending asynchronous operations. Consider allowing the process to exit naturally or handle termination more gracefully.

Apply this diff:

-    process.exit(errorCode)

Likely invalid or redundant comment.

deploy/docker/fs/opt/appsmith/utils/bin/index.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2)

27-38: Improve robustness of command output parsing

While error handling is good, the command output parsing could be more robust.

-    const shellCmdResult = await utils.execCommandReturningOutput([
+    const { stdout } = await utils.execCommandReturningOutput([
       "mongo",
       process.env.APPSMITH_DB_URL,
       "--quiet",
       "--eval",
       "db.getCollectionNames().length",
     ]);
   } catch (error) {
     console.error("Failed to execute mongo command:", error);
     throw error;
   }
-    const collectionsLen = parseInt(shellCmdResult.stdout.toString().trimEnd())
+    const output = stdout.toString().trimEnd();
+    const collectionsLen = Number.isInteger(parseInt(output)) ? parseInt(output) : 0;

Line range hint 42-58: Reduce code duplication in import logic

The importDatabase call is repeated in multiple places. Consider consolidating the logic.

+    async function performImport() {
+      await importDatabase();
+      return;
+    }
+
     if (collectionsLen > 0) {
       if (forceOption) {
-        await importDatabase()
+        await performImport();
         return
       }
       console.log()
       console.log('**************************** WARNING ****************************')
       console.log(`Your target database is not empty, it has data in ${collectionsLen} collections.`)
       const input = readlineSync.question('Importing this DB will erase this data. Are you sure you want to proceed?[Yes/No] ')
       const answer = input && input.toLocaleUpperCase()
       if (answer === 'Y' || answer === 'YES') {
-        await importDatabase()
+        await performImport();
         return
       } else if (answer === 'N' || answer === 'NO') {
         return
       }
       console.log(`Your input is invalid. Please try to run import command again.`)
     } else {
-      await importDatabase()
+      await performImport();
     }
🧰 Tools
🪛 Biome

[error] 49-49: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2e85d1b and 86c7684.

📒 Files selected for processing (2)
  • deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/index.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • deploy/docker/fs/opt/appsmith/utils/bin/index.js
🔇 Additional comments (2)
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2)

19-22: LGTM! Good initialization with supervisor check

The supervisor check before proceeding with operations is a good practice.


60-71: LGTM! Good error handling and cleanup

The cleanup in the finally block ensures services are restarted regardless of import success or failure.

deploy/docker/fs/opt/appsmith/utils/bin/import_db.js Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2)

Line range hint 29-64: Simplify nested conditionals and error handling

The current implementation has deep nesting which affects readability. Consider extracting the database check into a separate function.

+async function checkDatabaseCollections() {
+  try {
+    const shellCmdResult = await utils.execCommandReturningOutput([
+      "mongo",
+      process.env.APPSMITH_DB_URL,
+      "--quiet",
+      "--eval",
+      "db.getCollectionNames().length",
+    ]);
+    return parseInt(shellCmdResult.stdout.toString().trimEnd());
+  } catch (error) {
+    console.error("Failed to execute mongo command:", error);
+    throw error;
+  }
+}

 async function run(forceOption) {
   // ... supervisor check ...
   try {
     await utils.stop(["backend", "rts"]);
-    try {
-      const shellCmdResult = // ... current implementation
-    } catch (error) {
-      console.error("Failed to execute mongo command:", error);
-      throw error;
-    }
-    const collectionsLen = parseInt(shellCmdResult.stdout.toString().trimEnd())
+    const collectionsLen = await checkDatabaseCollections();
     if (collectionsLen > 0 && !forceOption) {
       // ... rest of the code ...
     }

65-72: Enhance error logging for better debugging

Consider adding more context to error logs to help with troubleshooting.

   } catch (err) {
-    console.log(err)
+    console.error('Database import failed with error:', err.message);
+    console.error('Stack trace:', err.stack);
     errorCode = 1
   }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 86c7684 and d25bb8d.

📒 Files selected for processing (1)
  • deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2 hunks)
🔇 Additional comments (2)
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2)

6-20: LGTM! Clean async implementation with proper error handling.


74-77: LGTM! Clean exports following the function rename.

sharat87 and others added 2 commits November 15, 2024 19:26
Co-authored-by: Arpit Mohan <mohanarpit@users.noreply.github.com>
Co-authored-by: Arpit Mohan <mohanarpit@users.noreply.github.com>
@sharat87 sharat87 requested a review from mohanarpit November 15, 2024 13:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants