-
Notifications
You must be signed in to change notification settings - Fork 16
fix: handle cross-file middleware context keys #196
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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 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 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 (2)
WalkthroughImplements 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
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
Estimated code review effortπ― 4 (Complex) | β±οΈ ~60 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.
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
-
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.
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.
There was a problem hiding this 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.replFmtChange 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 togo/parserinstead 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
pkgexists 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 capturingalias="."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{[^}]*}plusremoveConfigFieldpasses 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=="."becomesalias=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.
π 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 downstreamokchecks detected; manual review still recommendedAutomated 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 remainingFromContextcalls.Next steps:
- If any
okbindings remain solely to satisfy short-declarations, consider removing them.- Otherwise, verify that no business logic conditionally depends on a false
okafter migration.
Summary
LocalsTesting
GOFLAGS=-mod=mod make lintGOFLAGS=-mod=mod make testhttps://chatgpt.com/codex/tasks/task_e_68ab3d9110ec83268f4faa65ff8d1d06
Summary by CodeRabbit
New Features
Tests