Skip to content

feat: fix for create-dojo cli #312

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

Merged
merged 3 commits into from
Nov 4, 2024

Conversation

okhaimie-dev
Copy link
Contributor

@okhaimie-dev okhaimie-dev commented Nov 3, 2024

Closes #

Introduced changes

This PR fixes the issues where one gets an error

Error: package.json: ENOENT: no such file or directory, open 'package.json'

when trying to use the

npx create-test-d-ok@latest start

command

Checklist

  • Linked relevant issue
  • Updated relevant documentation
  • Added relevant tests
  • Add a dedicated CI job for new examples
  • Performed self-review of the code

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for package information retrieval.
    • Introduced a fallback mechanism for reading package.json.
  • Bug Fixes

    • Improved path resolution for package.json to reference the current working directory.
  • Refactor

    • Updated the control flow in the main function to proceed without awaiting package information.

Copy link

coderabbitai bot commented Nov 3, 2024

Walkthrough

The pull request introduces modifications to the main function in packages/create-dojo/src/index.ts by changing the invocation of getPackageInfo from an asynchronous to a synchronous call. Additionally, the getPackageInfo function in packages/create-dojo/src/utils/get-package-info.ts has been updated to include error handling, ensuring that if an error occurs while reading the package JSON file, a default object is returned instead of throwing an error. These changes impact the control flow of the application.

Changes

File Path Change Summary
packages/create-dojo/src/index.ts Modified main function to call getPackageInfo synchronously without awaiting.
packages/create-dojo/src/utils/get-package-info.ts Added error handling to getPackageInfo, returning a default object with a version of "1.0.0" on error.

Possibly related PRs

  • fix: create-dojo #297: The changes in packages/create-dojo/src/index.ts regarding the main function and its control flow are related to the modifications made in the same file in this PR, which also involves changes to the index.ts file.
  • fix: create dojo issue, syscalls #308: This PR addresses issues related to the "create dojo" functionality, which may connect to the changes in the getPackageInfo function's error handling in the main PR, as both involve improving the robustness of the dojo functionality.

🐇 In the code, a change we see,
Synchronous calls now set us free!
Errors caught with a gentle grace,
A default version finds its place.
Hopping forward, we embrace the flow,
In our dojo, watch us grow! 🌱


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a3f45f9 and d66dce4.

📒 Files selected for processing (1)
  • packages/create-dojo/src/utils/get-package-info.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/create-dojo/src/utils/get-package-info.ts

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@okhaimie-dev okhaimie-dev marked this pull request as ready for review November 4, 2024 05:08
Copy link

@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)
packages/create-dojo/src/index.ts (2)

Line range hint 11-24: Consider enhancing error handling in the main CLI function.

The main function could benefit from a top-level error handler to provide better user feedback for CLI operations.

Consider wrapping the main logic in a try-catch block:

 async function main() {
+    try {
         const packageInfo = await getPackageInfo();
 
         const program = new Command()
             .name("@dojoengine")
             .description("install a dojo client")
             .version(
                 packageInfo.version || "1.0.0",
                 "-v, --version",
                 "display the version number"
             );
 
         program.addCommand(start);
 
         program.parse();
+    } catch (error) {
+        console.error('Failed to initialize CLI:', error.message);
+        process.exit(1);
+    }
 }

Line range hint 7-8: Consider adding error handlers for process signals.

While the current signal handlers gracefully exit, they might leave resources in an inconsistent state.

Consider adding cleanup logic:

-process.on("SIGINT", () => process.exit(0));
-process.on("SIGTERM", () => process.exit(0));
+process.on("SIGINT", () => {
+    // Perform cleanup if necessary
+    process.exit(0);
+});
+process.on("SIGTERM", () => {
+    // Perform cleanup if necessary
+    process.exit(0);
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3049291 and a3f45f9.

📒 Files selected for processing (2)
  • packages/create-dojo/src/index.ts (1 hunks)
  • packages/create-dojo/src/utils/get-package-info.ts (1 hunks)
🔇 Additional comments (2)
packages/create-dojo/src/utils/get-package-info.ts (1)

7-13: Verify the impact of silent failures.

The function now silently continues with a default version when package.json is missing or invalid. Let's verify if this behavior is expected in all CLI contexts.

✅ Verification successful

Let me gather more specific information about how getPackageInfo is used.


Based on the gathered information, I can now provide the final response:

Silent failure handling in getPackageInfo is acceptable

The getPackageInfo function is only used in two scenarios:

  1. To display the CLI version number through Commander's .version() call
  2. As a fallback version when package.json is missing

The default version "1.0.0" is appropriate because:

  • For CLI version display: It's a non-critical feature that doesn't affect functionality
  • The actual package versions for project dependencies are fetched directly from npm registry via getLatestVersion() function, not relying on the local package.json
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any CLI commands or features that critically depend on accurate package.json information

# Look for imports/usage of getPackageInfo
rg -l "getPackageInfo" --type ts

# Look for version-dependent logic
rg -i "version|semver" --type ts

Length of output: 2833


Script:

#!/bin/bash
# Check the specific usage of getPackageInfo in index.ts
rg -A 5 "getPackageInfo" packages/create-dojo/src/index.ts

# Check the implementation and usage of start command since it seems to be version-dependent
cat packages/create-dojo/src/commands/start.ts

Length of output: 7010

packages/create-dojo/src/index.ts (1)

12-12: ⚠️ Potential issue

Maintain async/await pattern for consistency and error handling.

The synchronous call to getPackageInfo() within an async function creates inconsistency in the control flow. While the function may handle errors internally, synchronous file operations can block the event loop and impact performance.

Apply this diff to maintain the async pattern:

-    const packageInfo = getPackageInfo();
+    const packageInfo = await getPackageInfo();

Let's verify if getPackageInfo is used asynchronously elsewhere in the codebase:

Comment on lines 7 to 13
try {
return fs.readJSONSync(packageJsonPath) as PackageJson;
} catch (error) {
return {
version: "1.0.0",
} as PackageJson;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error logging and consider project root path.

While the error handling is a good addition, there are a few concerns:

  1. Silently falling back to a default version could mask real issues
  2. The hardcoded path might fail when running from different directories

Consider this improved implementation:

 export function getPackageInfo() {
-    const packageJsonPath = path.join("package.json");
+    const packageJsonPath = path.join(process.cwd(), "package.json");
     try {
         return fs.readJSONSync(packageJsonPath) as PackageJson;
     } catch (error) {
+        console.warn(`Failed to read package.json: ${error.message}`);
+        console.warn('Falling back to default version "1.0.0"');
         return {
             version: "1.0.0",
         } as PackageJson;
     }
 }

The changes:

  1. Use process.cwd() to ensure we look for package.json in the project root
  2. Add warning logs to help diagnose issues
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
return fs.readJSONSync(packageJsonPath) as PackageJson;
} catch (error) {
return {
version: "1.0.0",
} as PackageJson;
}
try {
const packageJsonPath = path.join(process.cwd(), "package.json");
return fs.readJSONSync(packageJsonPath) as PackageJson;
} catch (error) {
console.warn(`Failed to read package.json: ${error.message}`);
console.warn('Falling back to default version "1.0.0"');
return {
version: "1.0.0",
} as PackageJson;
}

@okhaimie-dev okhaimie-dev changed the title feat: fix for cli feat: fix for create-dojo cli Nov 4, 2024
@okhaimie-dev okhaimie-dev changed the title feat: fix for create-dojo cli feat: fix for create-dojo cli Nov 4, 2024
@ponderingdemocritus ponderingdemocritus merged commit 557afb5 into dojoengine:main Nov 4, 2024
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants