feat: allow migrating fiber using commit hash#175
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Warning Rate limit exceeded@ReneWerner87 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 4 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
WalkthroughAdds hash-derived pseudo-version support to the migrate command via a new --hash option and supporting helper. Updates MigrateOptions to include TargetHash, adjusts control flow to compute/validate pseudo-versions, and extends tests to cover hash-based migration for both the command and Go package migration paths. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User
participant CLI as migrate cmd
participant PV as pseudoVersionFromHash
participant GH as GitHub API
participant MOD as go.mod updater
U->>CLI: migrate -t=3.0.0 --hash=<commit>
CLI->>CLI: Parse base target semver
alt hash provided
CLI->>PV: Build pseudo-version from base + hash
PV->>GH: GET /repos/.../commits/<hash>
GH-->>PV: committer.date, sha
PV-->>CLI: v3.0.1-0.YYYYMMDDhhmmss-<sha12>
CLI->>CLI: Validate pseudo-version
else no hash
CLI->>CLI: Use standard semver target
end
CLI->>CLI: Compare with current version
CLI->>MOD: Apply migration to target version
MOD-->>CLI: go.mod updated
CLI-->>U: "Migrating Go packages" + final target
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @ReneWerner87, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a significant enhancement to the migrate command, allowing users to specify a target Fiber version using a Git commit hash. Previously, only semantic versions were supported. The change enables the CLI to dynamically generate Go pseudo-versions by querying the GitHub API for commit metadata, ensuring that go.mod files can accurately reference specific development or untagged versions of Fiber. This provides greater flexibility for users who need to migrate to a precise state of the Fiber framework not yet released as a formal version.
Highlights
- New
--hashflag for migration: Themigratecommand now supports a new--hashflag, enabling users to specify a target Fiber version using a Git commit hash instead of a traditional semantic version. - Automated Go pseudo-version generation: The CLI can now generate valid Go pseudo-versions (e.g.,
vX.Y.Z-0.YYYYMMDDHHMMSS-abcdef123456) from a given commit hash. This involves making an HTTP request to the GitHub API to retrieve the commit date, which is a crucial component of a pseudo-version. - Enhanced
go.modmigration with commit hashes: The migration logic has been extended to correctly updatego.modfiles to reference Fiber using these newly generated commit-hash-based pseudo-versions. - Comprehensive test coverage for new feature: New unit and integration tests have been added to ensure the robustness and correctness of the commit-hash-based migration functionality, including mocking external API calls.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request introduces a new --hash flag to the migrate command, enabling migrations to Fiber versions specified by a commit hash. This is achieved by fetching commit details from the GitHub API to construct a Go pseudo-version. The changes are well-tested. My review includes suggestions to improve the new API interaction logic for better robustness and maintainability.
| defer res.Body.Close() | ||
|
|
There was a problem hiding this comment.
The HTTP response status code is not checked. If the GitHub API returns a non-200 status (e.g., 404 for an invalid commit hash), the JSON decoding will likely fail with a generic error, or worse, it might succeed with an empty data structure, leading to incorrect pseudo-version generation. You should check for http.StatusOK and return a descriptive error for other statuses.
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("github api returned non-200 status for commit %s: %s", hash, res.Status)
}There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
cmd/migrate.go (1)
129-162: Handle non-200 responses, set headers, and fix Close errcheck to satisfy lint and robustness
- Missing HTTP status check leads to opaque JSON decode errors and makes invalid hashes hard to diagnose. Also previously flagged by another reviewer.
- Add a GitHub-compatible User-Agent and Accept header; optionally honor GITHUB_TOKEN to reduce rate-limit issues.
- Fix golangci-lint errcheck on res.Body.Close.
Apply this diff within pseudoVersionFromHash:
func pseudoVersionFromHash(base *semver.Version, hash string) (string, error) { - url := "https://api.github.com/repos/gofiber/fiber/commits/" + hash + url := "https://api.github.com/repos/gofiber/fiber/commits/" + hash ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return "", fmt.Errorf("create http request: %w", err) } - client := http.Client{} + // GitHub API best practices + req.Header.Set("User-Agent", "gofiber-cli-migrate") + req.Header.Set("Accept", "application/vnd.github+json") + if tok := os.Getenv("GITHUB_TOKEN"); tok != "" { + req.Header.Set("Authorization", "Bearer "+tok) + } + + client := http.Client{} res, err := client.Do(req) if err != nil { return "", fmt.Errorf("http request failed: %w", err) } - defer func() { _ = res.Body.Close() }() + defer func() { _ = res.Body.Close() }() //nolint:errcheck + + if res.StatusCode != http.StatusOK { + // Keep error readable; body may be JSON {"message": ...} or HTML. + b, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10)) + return "", fmt.Errorf("github api %s: %s (%d)", req.URL.Path, strings.TrimSpace(string(b)), res.StatusCode) + } var data struct { Commit struct { Committer struct { Date time.Time `json:"date"` } `json:"committer"` } `json:"commit"` } if err := json.NewDecoder(res.Body).Decode(&data); err != nil { return "", fmt.Errorf("decode response: %w", err) } short := hash if len(short) > 12 { short = short[:12] } pv := module.PseudoVersion("v"+strconv.FormatUint(base.Major(), 10), "v"+base.String(), data.Commit.Committer.Date, short) return strings.TrimPrefix(pv, "v"), nil }Additionally, declare the URL format as a constant for maintainability (optional but recommended):
// at file scope const githubCommitAPIURLFmt = "https://api.github.com/repos/gofiber/fiber/commits/%s"and then:
- url := "https://api.github.com/repos/gofiber/fiber/commits/" + hash + url := fmt.Sprintf(githubCommitAPIURLFmt, hash)Finally, add the missing import:
import "io"
🧹 Nitpick comments (4)
cmd/internal/migrations/common_test.go (1)
53-76: Solid coverage for hash-based go.mod migration; consider one extra assertionTest verifies the pseudo-version replacement and user-facing message. As a tiny enhancement, also assert that the old v2 requirement no longer appears in go.mod to guard against partial replacements.
Apply this diff:
mod := readFile(t, filepath.Join(dir, "go.mod")) assert.Contains(t, mod, "github.com/gofiber/fiber/v3 v3.0.1-0.20200102030405-abcdef123456") +assert.NotContains(t, mod, "github.com/gofiber/fiber/v2 ") assert.Contains(t, buf.String(), "Migrating Go packages")cmd/migrate_test.go (1)
302-330: Hash-path test is strong; add negative-path coverageThis validates the happy path. Please add a failure test for non-200 responses (e.g., 404) to lock in error handling for invalid hashes. Optionally also assert the CLI summary includes the pseudo-version to ensure consistent UX.
Apply this additional test (appending to the file):
func Test_Migrate_WithHash_Non200(t *testing.T) { dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "go.mod"), []byte(goModV2), 0o600)) require.NoError(t, os.WriteFile(filepath.Join(dir, "main.go"), []byte("package main"), 0o600)) cwd, _ := os.Getwd() require.NoError(t, os.Chdir(dir)) defer func() { _ = os.Chdir(cwd) }() hash := "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef" httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder(http.MethodGet, "https://api.github.com/repos/gofiber/fiber/commits/"+hash, httpmock.NewStringResponder(404, `{"message":"Not Found"}`), ) cmd := newMigrateCmd() setupCmd() defer teardownCmd() _, err := runCobraCmd(cmd, "-t=3.0.0", "--hash="+hash) require.Error(t, err) }cmd/migrate.go (2)
129-162: Consider testability: allow injecting http.Client or base URLFor easier unit testing and to avoid reliance on default transports, take an optional http.Client (or a function var) and the base API URL as parameters or package-level vars. Your tests already work with httpmock, but explicit injection reduces hidden coupling.
Example minimal change:
// package-level var httpDo = (&http.Client{}).Do var githubAPIBase = "https://api.github.com" // then in code: res, err := httpDo(req) url := fmt.Sprintf("%s/repos/gofiber/fiber/commits/%s", githubAPIBase, hash)
117-126: Small UX improvement: include 'v' in the final messageThe CLI prints “Migration from Fiber X to Y” with unprefixed versions. Consider prefixing with v for consistency with Go tags and go.mod lines, especially when Y is a pseudo-version.
Apply this diff:
- msg := fmt.Sprintf("Migration from Fiber %s to %s", migrateFromS, opts.TargetVersionS) + msg := fmt.Sprintf("Migration from Fiber v%s to v%s", migrateFromS, opts.TargetVersionS)
📜 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.
📒 Files selected for processing (3)
cmd/internal/migrations/common_test.go(1 hunks)cmd/migrate.go(5 hunks)cmd/migrate_test.go(3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-11-15T07:56:21.623Z
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Applied to files:
cmd/migrate_test.go
🧬 Code graph analysis (1)
cmd/internal/migrations/common_test.go (1)
cmd/internal/migrations/common.go (1)
MigrateGoPkgs(21-58)
🪛 GitHub Check: lint
cmd/migrate.go
[failure] 143-143:
Error return value of res.Body.Close is not checked (errcheck)
🪛 GitHub Actions: golangci-lint
cmd/migrate.go
[error] 143-143: Error return value of res.Body.Close is not checked (errcheck)
⏰ 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). (1)
- GitHub Check: Build (1.25.x, windows-latest)
🔇 Additional comments (5)
cmd/migrate_test.go (3)
24-30: Good move: centralized module fixture for v2Defining goModV2 once reduces duplication and keeps tests consistent as inputs evolve.
31-37: Refactor to use goModV2 improves clarityReplacing inline strings with the shared constant makes intent clearer and avoids drift across tests.
122-122: LGTM: reuse goModV2 in default-target testThis keeps the setup uniform and easier to maintain.
cmd/migrate.go (2)
23-24: CLI flag and options plumbed cleanly--hash flag addition, wiring into MigrateOptions, and help text are coherent and self-explanatory.
Also applies to: 37-38, 43-44, 58-59
79-96: Pseudo-version integration is correct and keeps comparisons semver-safeParsing base version first, then replacing TargetVersionS with the computed pseudo-version and re-parsing ensures comparisons are accurate and messages reflect the effective target.
Summary
--hashflag to migrate command to support commit-based fiber versionsTesting
make lint(fails: interrupted)make test(fails: inconsistent vendoring)GOFLAGS=-mod=mod go test ./cmd -run Test_Migrate_WithHash -count=1GOFLAGS=-mod=mod go test ./cmd/internal/migrations -run MigrateGoPkgs_WithHash -count=1https://chatgpt.com/codex/tasks/task_e_68a9f947588083269f22ef2a93cb3f15
Summary by CodeRabbit
New Features
Tests