Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Aug 24, 2025

Summary

  • ensure middleware locals migration uses context keys gathered from all files before replacing Locals
  • add test for context key defined in different file

Testing

  • GOFLAGS=-mod=mod make lint
  • GOFLAGS=-mod=mod make test

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

Summary by CodeRabbit

  • New Features

    • Migration tool now updates middleware locals across the entire project, including cases where context keys are defined in separate files.
    • Automatically cleans up obsolete middleware configuration options during migration.
    • Two-pass process improves accuracy and consistency of code updates.
    • Clearer error messages when gathering and applying migrations.
  • Tests

    • Added cross-file test to verify migration correctly handles context keys defined outside the handler file.

@coderabbitai
Copy link

coderabbitai bot commented Aug 24, 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 6 minutes and 1 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 35f2b9f and 1f01680.

πŸ“’ Files selected for processing (2)
  • cmd/internal/migrations/v3/middleware_locals.go (2 hunks)
  • cmd/internal/migrations/v3/middleware_locals_test.go (2 hunks)

Walkthrough

Implements a two-pass migration in middleware_locals: pass one scans project files to collect middleware context key mappings; pass two applies replacements for Locals lookups, adjusts assignments, removes obsolete Config fields, and centralizes import/regex handling. Adds a cross-file test verifying config-in-one-file and usage-in-another scenario.

Changes

Cohort / File(s) Summary
Migration logic (two-pass, shared regex/import map)
cmd/internal/migrations/v3/middleware_locals.go
Adds two-pass processing: gather ctxMap by analyzing middleware imports/Config fields; then apply replacements (Locals -> FromContext), remove type assertions, convert short assignments to include boolean, strip deprecated Config fields. Centralizes reImport, ctxMap, and extractors; adds explicit error handling.
Tests (cross-file custom ContextKey)
cmd/internal/migrations/v3/middleware_locals_test.go
Adds Test_MigrateMiddlewareLocals_CustomContextKeyAcrossFiles validating migration when ContextKey is defined in a separate file; ensures handler uses FromContext and config drops ContextKey; includes filepath usage.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer
  participant CLI as CLI Command
  participant Mig as MigrateMiddlewareLocals
  participant FS as Filesystem

  Dev->>CLI: run migrate v3 middleware_locals
  CLI->>Mig: MigrateMiddlewareLocals(cwd)
  rect rgba(200,230,255,0.3)
    note over Mig: Pass 1 β€” Gather context mappings
    Mig->>FS: Scan all *.go files
    Mig->>Mig: Detect middleware imports/config (ContextKey/Username/Password)
    Mig->>Mig: Build ctxMap & import map
  end
  rect rgba(200,255,200,0.3)
    note over Mig: Pass 2 β€” Apply replacements
    Mig->>FS: For each file, read contents
    Mig->>Mig: Replace c.Locals(...) with FromContext helpers
    Mig->>Mig: Remove type assertions, adjust := to include boolean
    Mig->>Mig: Remove deprecated Config fields
    Mig->>FS: Write updated files
  end
  Mig-->>CLI: success or error
  CLI-->>Dev: report result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

☒️ Bug

Poem

Thump-thump, my paws review each file with care,
Two hops: map, then mendβ€”no key left bare.
Strings to helpers, configs trimmed tight,
Regex whiskers twitching in the night.
With a nibble of tests and a carrot of proofβ€”
The code now scampers, agile and aloof. πŸ₯•πŸ‡

✨ 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-24-16-54-37

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.

@github-actions github-actions bot added the ☒️ Bug Something isn't working label Aug 24, 2025
Copy link
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 addresses a bug in the middleware locals migration tool, specifically when context keys are defined across multiple files. Previously, the migration might not correctly identify and replace c.Locals("key") calls if the corresponding ContextKey definition was in a different file. The fix introduces a two-pass migration strategy to ensure all context key definitions are gathered before performing replacements, improving the robustness of the migration process.

Highlights

  • Refactored Migration Logic: The MigrateMiddlewareLocals function has been refactored to implement a two-pass approach for handling middleware context keys.
  • Comprehensive Context Key Collection: The first pass now scans all files within the current working directory to collect a comprehensive map of all context key definitions.
  • Accurate Replacement Pass: The second pass then utilizes this complete map to accurately replace c.Locals("key") calls with their respective middleware.FromContext(c) equivalents, ensuring correct migration even for cross-file definitions.
  • New Cross-File Test Case: A new test case has been added to validate the correct migration of context keys defined in separate files, ensuring the fix works as intended for cross-file scenarios.
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
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 effectively addresses the issue of handling middleware context keys defined across different files during migration. The introduction of a two-pass approach, where the first pass gathers all custom context key configurations and the second pass applies the replacements, is a solid and correct solution. The new test case for cross-file context keys is also a great addition that ensures this scenario is covered.

My main feedback is a suggestion to refactor a small piece of duplicated code to improve maintainability. Overall, this is a good improvement.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
cmd/internal/migrations/v3/middleware_locals.go (2)

38-67: First pass should accumulate candidates instead of overwriting to resolve key collisions.

Currently, the latest match wins:

ctxMap[m[1]] = e.replFmt

Change it to append a candidate with its package, so the second pass can choose by local imports.

-		for alias, pkg := range imports {
+		for alias, pkg := range imports {
 			for _, e := range extractors {
 				if e.pkg != pkg {
 					continue
 				}
-				re := regexp.MustCompile(alias + `\.Config{[^}]*` + e.field + `:\s*"([^"]+)"`)
+				re := regexp.MustCompile(alias + `\.Config{[^}]*` + e.field + `:\s*"([^"]+)"`)
 				matches := re.FindAllStringSubmatch(content, -1)
 				for _, m := range matches {
-					ctxMap[m[1]] = e.replFmt
+					key := m[1]
+					ctxMap[key] = append(ctxMap[key], ctxRepl{pkg: e.pkg, replFn: e.replFmt})
 				}
 			}
 		}

Note: The [^}] class can prematurely stop on nested braces inside composite literals. If this becomes a problem in-the-wild, we should switch this pass to go/parser instead of regex.


81-90: Select the replacement by packages actually imported in the current file; avoid guessing.

Use the candidates gathered in the first pass and pick the one whose pkg exists among this file’s imports. If multiple exist, pick deterministically (first), otherwise leave the call unchanged to avoid a wrong rewrite.

-		reLocals := regexp.MustCompile(`(\w+)\.Locals\("([^"]+)"\)`)
+		reLocals := regexp.MustCompile(`(\w+)\.Locals\("([^"]+)"\)`)
 		content = reLocals.ReplaceAllStringFunc(content, func(s string) string {
 			sub := reLocals.FindStringSubmatch(s)
 			ctx := sub[1]
 			key := sub[2]
-			if fmtStr, ok := ctxMap[key]; ok {
-				return fmt.Sprintf(fmtStr, ctx)
-			}
+			if cands, ok := ctxMap[key]; ok && len(cands) > 0 {
+				// Build a set of imported fiber middleware package names in this file (e.g., "csrf", "keyauth").
+				importSet := make(map[string]struct{}, len(imports))
+				for _, pkg := range imports {
+					importSet[pkg] = struct{}{}
+				}
+				// Prefer a candidate whose package is imported in this file.
+				for _, cand := range cands {
+					if _, present := importSet[cand.pkg]; present {
+						return fmt.Sprintf(cand.replFn, ctx)
+					}
+				}
+				// Fallback: if only one candidate exists, use it; otherwise, keep original to avoid wrong rewrite.
+				if len(cands) == 1 {
+					return fmt.Sprintf(cands[0].replFn, ctx)
+				}
+			}
 			return s
 		})

This makes the migration deterministic and avoids cross-project order dependence.

🧹 Nitpick comments (5)
cmd/internal/migrations/v3/middleware_locals_test.go (1)

186-219: Solid cross-file regression test; consider adding alias/ambiguity variants.

This test effectively proves the two-pass scan picks up ContextKey from a different file and migrates the handler accordingly. Two optional enhancements:

  • Add a variant where the middleware import in the handler uses an alias (e.g., ka "…/keyauth"), to ensure replacements still work when the handler doesn't import the defining package directly.
  • Add an ambiguity test where both csrf and keyauth set the same ContextKey (e.g., "token") in different files, and the handler imports only one of themβ€”this catches wrong mapping selection.

If you want, I can draft these additional tests.

cmd/internal/migrations/v3/middleware_locals.go (4)

36-36: Import regex largely covers single and block imports; dot-imports remain a corner case.

Your pattern finds both aliased and non-aliased imports in and outside import blocks. Two small improvements:

  • Normalize dot imports (import . "…/csrf") to avoid capturing alias="." and breaking downstream logic.
  • Consider tolerating trailing comments.

You can normalize the alias immediately after matching:

-	reImport := regexp.MustCompile(`(?m)^\s*(?:import\s+)?(?:([\w\.]+)\s+)?"github\.com/gofiber/fiber/(?:v2|v3)/middleware/([\w]+)"`)
+	reImport := regexp.MustCompile(`(?m)^\s*(?:import\s+)?(?:([\w\.]+)\s+)?"github\.com/gofiber/fiber/(?:v2|v3)/middleware/([\w]+)"(?:\s*//.*)?$`)

and in both import-collection loops (shown further below):

-			if alias == "" {
+			if alias == "" || alias == "." {
 				alias = pkg
 			}

Dot-imports still won’t enable scanning Config{…} without a qualifier; if that’s in scope, it likely needs AST parsing. Marking as optional.


69-79: DRY: factor import harvesting into a small helper.

You repeat the alias→pkg extraction logic in both passes. Extract to a local helper to avoid drift and to apply the dot-import normalization in one place.

Example (no diff needed here, just a suggestion):

func collectFiberMiddlewareImports(re *regexp.Regexp, content string) map[string]string { … }

98-106: Config field cleanup works; be mindful of nested composites.

The removal via alias\.Config{[^}]*} plus removeConfigField passes the current tests (including comment stripping). If configs ever embed slices/maps with } inside, the [^}] class might stop early. Optional: move cleanup to AST in a follow-up if you encounter real-world false negatives.


41-48: Normalize dot-import alias during import harvesting.

Apply the same tweak in both passes so alias=="." becomes alias=pkg, avoiding malformed patterns downstream.

-			if alias == "" {
+			if alias == "" || alias == "." {
 				alias = pkg
 			}

Also applies to: 72-79

πŸ“œ 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 23d8879 and 35f2b9f.

πŸ“’ Files selected for processing (2)
  • cmd/internal/migrations/v3/middleware_locals.go (2 hunks)
  • cmd/internal/migrations/v3/middleware_locals_test.go (2 hunks)
🧰 Additional context used
🧠 Learnings (3)
πŸ“š Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Applied to files:

  • cmd/internal/migrations/v3/middleware_locals_test.go
πŸ“š Learning: 2024-12-13T08:14:22.851Z
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.

Applied to files:

  • cmd/internal/migrations/v3/middleware_locals_test.go
πŸ“š Learning: 2024-10-02T23:03:31.727Z
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.

Applied to files:

  • cmd/internal/migrations/v3/middleware_locals_test.go
🧬 Code graph analysis (2)
cmd/internal/migrations/v3/middleware_locals_test.go (1)
cmd/internal/migrations/v3/middleware_locals.go (1)
  • MigrateMiddlewareLocals (13-119)
cmd/internal/migrations/v3/middleware_locals.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (38-79)
⏰ 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, macos-13)
  • GitHub Check: Build (1.25.x, windows-latest)
πŸ”‡ Additional comments (3)
cmd/internal/migrations/v3/middleware_locals_test.go (1)

6-6: Import of filepath is appropriate for cross-file setup.

Needed for joining the temp dir with the config filename.

cmd/internal/migrations/v3/middleware_locals.go (2)

24-34: Extractor list looks good; keep it the single source of truth.

No change requested. This table-driven approach makes it easy to extend.


92-97: No downstream ok checks detected; manual review still recommended

Automated search for patterns like

x, ok := XxxFromContext(c), true
if !ok { … }

yielded no results, suggesting no code paths rely on a failing assert post-migration.

β€’ Search performed with:

rg -nP -C2 '\b\w+\s*,\s*ok\s*:=\s*[\w\.]+FromContext\([^)]*\),\s*true\b' \
  | rg -nP -C5 '\bif\s+!\s*ok\b|\bok\s*&&|\b&&\s*ok\b'

– no matches found.
β€’ Absence of hits isn’t proof of absence; please manually audit any remaining FromContext calls.

Next steps:

  • If any ok bindings remain solely to satisfy short-declarations, consider removing them.
  • Otherwise, verify that no business logic conditionally depends on a false ok after migration.

@ReneWerner87 ReneWerner87 merged commit 9c07a47 into master Aug 24, 2025
13 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-08-24-16-54-37 branch August 24, 2025 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

☒️ Bug Something isn't working codex

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants