Skip to content

feat: allow migrating fiber using commit hash#175

Merged
ReneWerner87 merged 3 commits into
masterfrom
codex/2025-08-23-17-36-43
Aug 23, 2025
Merged

feat: allow migrating fiber using commit hash#175
ReneWerner87 merged 3 commits into
masterfrom
codex/2025-08-23-17-36-43

Conversation

@ReneWerner87
Copy link
Copy Markdown
Member

@ReneWerner87 ReneWerner87 commented Aug 23, 2025

Summary

  • add --hash flag to migrate command to support commit-based fiber versions
  • generate Go pseudo versions from commit hashes via GitHub API
  • test migrations with commit hashes

Testing

  • make lint (fails: interrupted)
  • make test (fails: inconsistent vendoring)
  • GOFLAGS=-mod=mod go test ./cmd -run Test_Migrate_WithHash -count=1
  • GOFLAGS=-mod=mod go test ./cmd/internal/migrations -run MigrateGoPkgs_WithHash -count=1

https://chatgpt.com/codex/tasks/task_e_68a9f947588083269f22ef2a93cb3f15

Summary by CodeRabbit

  • New Features

    • The migrate command now supports a --hash flag to target a specific commit. It derives a pseudo-version from the commit and applies it during migration, including in command output.
  • Tests

    • Added tests validating hash-based migration flow and pseudo-version handling.
    • Centralized test module setup for consistency across migration tests.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 23, 2025

Note

Other AI code review bot(s) detected

CodeRabbit 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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between cfe9a0d and 4c1bd8a.

📒 Files selected for processing (1)
  • cmd/migrate.go (5 hunks)

Walkthrough

Adds 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

Cohort / File(s) Summary
Hash-based migration support in migrate command
cmd/migrate.go
Introduces TargetHash in MigrateOptions, flag handling, and control flow to derive and validate pseudo-versions from a commit hash using GitHub API; adds helper pseudoVersionFromHash and required imports.
Migrate command tests
cmd/migrate_test.go
Centralizes v2 go.mod fixture; updates existing tests to use it; adds Test_Migrate_WithHash using mocked GitHub commit date to verify v3 pseudo-version migration.
Go package migration tests
cmd/internal/migrations/common_test.go
Adds Test_MigrateGoPkgs_WithHash to verify fiber/v3 requirement updated to a pseudo-version when migrating with hash.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

✏️ Feature

Poem

I thump my paw on versioned ground,
A hash-hop later, a tag is found.
From dates and commits I stitch a thread,
A pseudo-path where code is led.
“v3 awaits!” my whiskers cheer—
Hop, migrate, and nibble near. 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-08-23-17-36-43

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 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
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

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 --hash flag for migration: The migrate command now supports a new --hash flag, 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.mod migration with commit hashes: The migration logic has been extended to correctly update go.mod files 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

  1. 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.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

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.

Comment thread cmd/migrate.go Outdated
Comment on lines +141 to +142
defer res.Body.Close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

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)
	}

Comment thread cmd/migrate.go Outdated
Comment thread cmd/migrate.go Outdated
Copy link
Copy Markdown

@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: 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 assertion

Test 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 coverage

This 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 URL

For 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 message

The 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 45d11bb and cfe9a0d.

📒 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 v2

Defining goModV2 once reduces duplication and keeps tests consistent as inputs evolve.


31-37: Refactor to use goModV2 improves clarity

Replacing inline strings with the shared constant makes intent clearer and avoids drift across tests.


122-122: LGTM: reuse goModV2 in default-target test

This 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-safe

Parsing base version first, then replacing TargetVersionS with the computed pseudo-version and re-parsing ensures comparisons are accurate and messages reflect the effective target.

@ReneWerner87 ReneWerner87 merged commit 50867ce into master Aug 23, 2025
13 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-08-23-17-36-43 branch August 23, 2025 18:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant