Skip to content

Conversation

valentimarco
Copy link

@valentimarco valentimarco commented Dec 5, 2024

Please provide enough information so that others can review your pull request:

Fix to #122

Explain the details for making this change. What existing problem does the pull request solve?

The expected use case for fiber new <name_project> is a working and ready to go setup. With this PR i propose to automatically install the required modules using go mod tidy

Summary by CodeRabbit

  • New Features

    • Improved project generation: better error handling during Go module initialization and automatic dependency tidy-up after project creation.
  • Bug Fixes

    • Prevents unnoticed failures during project setup by returning errors from module initialization and dependency management steps.

Copy link

welcome bot commented Dec 5, 2024

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

The createBasic function in cmd/new.go now checks and returns errors from go mod init and additionally runs go mod tidy inside the new project directory with error handling, ensuring failures are propagated immediately.

Changes

Cohort / File(s) Change Summary
Project creation command
cmd/new.go
Added explicit error handling for runCmd(execCommand("go", "mod", "init", modName)) and added execution of go mod tidy (installModules) with error checks in createBasic.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant User
    participant createBasic as Creator
    participant Shell as ShellCmd

    User->>Creator: invoke createBasic()
    Creator->>Shell: runCmd(execCommand "go mod init" modName)
    alt init error
        Shell-->>Creator: error
        Creator-->>User: return error
    else init ok
        Creator->>Shell: runCmd(execCommand "go mod tidy") [in project dir]
        alt tidy error
            Shell-->>Creator: error
            Creator-->>User: return error
        else tidy ok
            Creator-->>User: success
        end
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🐰
A tiny hop, a careful try,
Init and tidy, errors spy.
Modules neat and checks in place,
The project starts with steadier grace. 🥕


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a3f82fb and 3f60284.

📒 Files selected for processing (1)
  • cmd/new.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/new.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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 or @coderabbitai title 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

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 (1)
cmd/new.go (1)

81-91: Consider enhancing command execution robustness

A few suggestions to improve the implementation:

  1. Add timeouts to prevent hanging on slow network connections
  2. Provide more descriptive error messages
  3. Update the success message to mention module installation

Example implementation with timeout:

 func createBasic(projectPath, modName string) (err error) {
     // create main.go
     if err = createFile(fmt.Sprintf("%s%cmain.go", projectPath, os.PathSeparator), newBasicTemplate); err != nil {
         return
     }
 
-    if err = runCmd(execCommand("go", "mod", "init", modName)); err != nil{
+    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+    defer cancel()
+    
+    initCmd := execCommand("go", "mod", "init", modName)
+    initCmd.WaitDelay = ctx.Done()
+    if err = runCmd(initCmd); err != nil {
+        return fmt.Errorf("failed to initialize module: %w", err)
     }
 
-    installModules := execCommand("go", "mod", "tidy")
+    installModules := execCommand("go", "mod", "tidy")
+    installModules.WaitDelay = ctx.Done()
     installModules.Dir = projectPath
-    if err = runCmd(installModules); err != nil{
+    if err = runCmd(installModules); err != nil {
+        return fmt.Errorf("failed to install dependencies: %w", err)
     }
 
     return
 }

Also consider updating the success message template to mention module installation:

 newSuccessTemplate = `
 Scaffolding project in %s (module %s)
+  ✓ Created project structure
+  ✓ Initialized Go module
+  ✓ Installed dependencies
 
   Done. Now run:
 
   cd %s
   fiber dev
 
 ✨  Done in %s.
 `
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f345bf8 and a3f82fb.

📒 Files selected for processing (1)
  • cmd/new.go (1 hunks)
🔇 Additional comments (2)
cmd/new.go (2)

81-83: LGTM: Proper error handling for module initialization

The error handling for go mod init is well-implemented and follows Go's idiomatic patterns.


81-91: Verify error handling and cleanup

Let's verify that errors are properly propagated and the project directory is cleaned up on failure.

✅ Verification successful

Let me gather more information about the error handling in the parent function.


Error handling and cleanup are properly implemented

The code has robust error handling and cleanup mechanisms:

  • The parent function has a deferred cleanup that removes the project directory on any error
  • runCmd properly handles command execution with stderr/stdout pipes and proper cleanup
  • All critical operations (mkdir, chdir, go mod commands) have error checks
  • The project directory is cleaned up if any step in the initialization fails
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and cleanup implementation

# Check if the defer cleanup is triggered on errors
rg -A 5 "defer func\(\)" cmd/

# Check if the parent function handles errors from module commands
rg "if err = create\w+\(" cmd/

Length of output: 4780


Script:

#!/bin/bash
# Check the parent function implementation and error handling
rg -B 5 -A 10 "createProject\(" cmd/

# Check the runCmd implementation
rg -B 5 -A 10 "func runCmd\(" cmd/

Length of output: 1575

Comment on lines +85 to +90
//Execute go mod tidy in the project directory
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
if err = runCmd(installModules); err != nil{
return
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix directory path construction

The directory path construction adds an extra separator character. The projectPath already contains the full path to the project.

Simplify the directory path assignment:

- installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
+ installModules.Dir = projectPath
📝 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
//Execute go mod tidy in the project directory
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
if err = runCmd(installModules); err != nil{
return
}
//Execute go mod tidy in the project directory
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = projectPath
if err = runCmd(installModules); err != nil{
return
}

@valentimarco valentimarco changed the title ✨ Execute go mod tidy after basic creation 🚸 Execute go mod tidy after basic creation Dec 5, 2024
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.

3 participants