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 flow: initialization now includes an automatic dependency tidy step after module setup.
  • Bug Fixes

    • Errors during initialization or dependency tidy are now surfaced immediately to prevent silent failures during project creation.

✏️ Tip: You can customize this high-level summary in your review settings.

@welcome
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

@coderabbitai
Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

The createBasic function in cmd/new.go now runs go mod init and, on success, runs go mod tidy inside the new project directory, returning errors immediately from either command.

Changes

Cohort / File(s) Summary
Project creation command
cmd/new.go
Added explicit error handling for go mod init and added execution of go mod tidy (executed in the new project directory) with error propagation in createBasic.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant User
    participant createBasic
    participant ShellCmd

    User->>createBasic: invoke createBasic(modName, dir)
    createBasic->>ShellCmd: runCmd(execCommand "go" "mod" "init" modName) [cwd=dir]
    alt init error
        ShellCmd-->>createBasic: error
        createBasic-->>User: return error
    else init ok
        createBasic->>ShellCmd: runCmd(execCommand "go" "mod" "tidy") [cwd=dir]
        alt tidy error
            ShellCmd-->>createBasic: error
            createBasic-->>User: return error
        else tidy ok
            createBasic-->>User: return success
        end
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🐇
I hopped in code with nimble feet,
Init then tidy — tidy and neat.
If either slips, I sound the bell,
Returning errors true and well.
A carrot nod for builds complete.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: executing go mod tidy after basic project creation, which matches the implementation in cmd/new.go.
Description check ✅ Passed The description follows the template structure, references the related issue (#122), explains the problem, and details the solution using go mod tidy for automatic module installation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🧹 Recent nitpick comments
cmd/new.go (1)

100-100: Redundant return statement.

With the suggested simplification above (returning runCmd(installModules) directly), this line becomes unnecessary.

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66f65f0 and 941a87d.

📒 Files selected for processing (1)
  • cmd/new.go
🧰 Additional context used
🪛 GitHub Actions: golangci-lint
cmd/new.go

[error] 92-92: File is not properly formatted (gci)

🪛 GitHub Check: lint
cmd/new.go

[failure] 96-96:
if-return: redundant if ...; err != nil check, just return error instead. (revive)


[failure] 93-93:
commentFormatting: put a space between // and comment text (gocritic)


[failure] 92-92:
File is not properly formatted (gci)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
🔇 Additional comments (1)
cmd/new.go (1)

89-91: LGTM!

The go mod init execution and error handling are correctly implemented.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

@valentimarco valentimarco changed the title ✨ Execute go mod tidy after basic creation 🚸 Execute go mod tidy after basic creation Dec 5, 2024
@gaby gaby requested a review from a team as a code owner February 1, 2026 17:12
@gaby gaby requested review from efectn, gaby and sixcolors and removed request for a team February 1, 2026 17:12
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

🤖 Fix all issues with AI agents
In `@cmd/new.go`:
- Around line 89-100: The function uses bare returns but doesn't have named
return values; change the three bare "return" statements to return the error
from the failing call (e.g., after "if err := runCmd(...); err != nil { return
err }" and similarly for the "if err := runCmd(installModules); err != nil {
return err }"), and make the final successful exit return nil instead of a bare
return so the function returns an error type consistently; look for runCmd,
execCommand and the surrounding createBasic function to update the returns.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

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

📒 Files selected for processing (1)
  • cmd/new.go

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@gaby
Copy link
Member

gaby commented Feb 1, 2026

@copilot fix the issues in this PR

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds an automatic go mod tidy step to the fiber new basic template flow so newly generated projects have a complete, runnable go.mod/go.sum out of the box (fixes #122).

Changes:

  • Replaces the single go mod init call with explicit error handling.
  • Executes go mod tidy after initializing the module during basic project creation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +89 to +95
if err := runCmd(execCommand("go", "mod", "init", modName)); err != nil {
return err
}

//Execute go mod tidy in the project directory
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
Copy link

Copilot AI Feb 1, 2026

Choose a reason for hiding this comment

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

createBasic runs go mod init without setting Cmd.Dir, but sets Cmd.Dir for go mod tidy. Since the function already receives projectPath, it would be more robust/consistent to set Dir for both commands (and avoid relying on a prior os.Chdir). This also prevents go.mod being created in the wrong directory if createBasic is ever called without createProject.

Suggested change
if err := runCmd(execCommand("go", "mod", "init", modName)); err != nil {
return err
}
//Execute go mod tidy in the project directory
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
modInit := execCommand("go", "mod", "init", modName)
modInit.Dir = projectPath
if err := runCmd(modInit); err != nil {
return err
}
// Execute go mod tidy in the project directory
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = projectPath

Copilot uses AI. Check for mistakes.
Comment on lines +94 to +98
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
if err := runCmd(installModules); err != nil {
return err
}
Copy link

Copilot AI Feb 1, 2026

Choose a reason for hiding this comment

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

go mod tidy can be affected by an enclosing go.work (workspace) file. Elsewhere the repo explicitly forces GOWORK=off when running go mod ... commands (see cmd/internal/go_mod.go:33-55). Consider applying the same environment filtering here for both go mod init and go mod tidy so project generation is isolated from the caller’s workspace.

Copilot uses AI. Check for mistakes.
Comment on lines +94 to +96
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
if err := runCmd(installModules); err != nil {
Copy link

Copilot AI Feb 1, 2026

Choose a reason for hiding this comment

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

installModules.Dir is set via fmt.Sprintf("%s%c", projectPath, os.PathSeparator), which adds a trailing separator and is inconsistent with other usages (cmd.Dir = dir in cmd/internal/go_mod.go). Prefer setting Dir to projectPath (optionally cleaned with filepath.Clean) to avoid odd paths like .../project// and keep path handling consistent.

Copilot uses AI. Check for mistakes.
Comment on lines +94 to +98
installModules := execCommand("go", "mod", "tidy")
installModules.Dir = fmt.Sprintf("%s%c", projectPath, os.PathSeparator)
if err := runCmd(installModules); err != nil {
return err
}
Copy link

Copilot AI Feb 1, 2026

Choose a reason for hiding this comment

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

This change adds a new externally-visible step (go mod tidy) during fiber new, but current tests don’t assert that tidy is invoked. Consider adding a unit test that captures execCommand invocations and verifies go mod tidy runs after go mod init.

Copilot uses AI. Check for mistakes.
@gaby
Copy link
Member

gaby commented Feb 1, 2026

@copilot open a new pull request to apply changes based on the comments in this thread

1 similar comment
@gaby
Copy link
Member

gaby commented Feb 1, 2026

@copilot open a new pull request to apply changes based on the comments in this thread

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.

4 participants