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

Skip to content

Conversation

@ReneWerner87
Copy link
Member

@ReneWerner87 ReneWerner87 commented Nov 30, 2025

Summary by CodeRabbit

  • Refactor
    • Introduced centralized helpers for identifier resolution, comment/value extraction, field formatting, extractor chaining, and config-block iteration to simplify migration logic.
  • Bug Fixes
    • Preserved existing parsing and trailing-comment behavior while reducing duplicated parsing logic.
  • Chores
    • No changes to public interfaces; migration outputs and behavior remain unchanged.

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

This commit eliminates code duplication across v3 migration files by
introducing reusable helper functions in common.go:

**New helper functions:**
- GetBaseIdent(): Recursively resolves AST expressions to base identifiers
  (eliminates 28 lines of duplicated code in context_methods.go and redirect_methods.go)

- ExtractCommentAndValue(): Separates values from trailing comments
  (used across multiple extractor files)

- FormatFieldWithComment(): Formats field assignments with consistent spacing
  (eliminates ~150+ lines of repetitive comment handling in 6 files)

- IterateConfigBlocks(): Generic function for processing config blocks
  (eliminates ~80 lines of duplicated iteration logic in 2 files)

**Files refactored:**
- context_methods.go: Uses GetBaseIdent() instead of local function
- redirect_methods.go: Uses GetBaseIdent() instead of local function
- jwt_extractor.go: Uses FormatFieldWithComment() for cleaner comment handling
- paseto_extractor.go: Uses FormatFieldWithComment() for cleaner comment handling
- key_auth_config.go: Uses FormatFieldWithComment() for cleaner comment handling
- session_extractor.go: Uses both IterateConfigBlocks() and FormatFieldWithComment()
- csrfconfig.go: Uses both IterateConfigBlocks() and FormatFieldWithComment()

**Impact:**
- Reduced code duplication by ~200-250 lines
- Improved maintainability through centralized logic
- Made code more consistent across migration files
- No functional changes - all behavior preserved
…ig processing

This commit continues the refactoring effort by adding more reusable
utilities and applying them across migration files:

**New helper functions in common.go:**
- BuildExtractorChain(): Builds extractor expressions from slices
  (eliminates ~40 lines of duplicated chain-building logic across 3 files)

- ExtractorMapping & StandardExtractorMappings(): Provides standardized
  extractor mappings for future use

**Refactored files:**
- cache_config.go: Uses ExtractCommentAndValue() instead of inline logic
  (eliminates 8 lines of duplicate comment extraction)

- jwt_extractor.go: Uses BuildExtractorChain() instead of switch statement
  (reduces 7 lines to 1)

- key_auth_config.go: Uses BuildExtractorChain() instead of if/else chain
  (reduces 8 lines to 1)

- session_extractor.go: Uses BuildExtractorChain() instead of if/else chain
  (reduces 7 lines to 1)

- encryptcookie_config.go: Uses IterateConfigBlocks() helper
  (reduces 26 lines to 6 lines - 77% reduction)

- session_config.go: Uses IterateConfigBlocks() helper
  (reduces 24 lines to 4 lines - 83% reduction)

**Impact:**
- Reduced code duplication by additional ~90-100 lines
- Simplified config processing with IterateConfigBlocks() usage
- More consistent extractor chain building
- Improved readability and maintainability
- No functional changes - all behavior preserved

**Total cumulative reduction: ~300+ lines of duplicated code eliminated**
@ReneWerner87 ReneWerner87 requested a review from a team as a code owner November 30, 2025 12:55
@ReneWerner87 ReneWerner87 requested review from efectn, gaby and sixcolors and removed request for a team November 30, 2025 12:55
@gemini-code-assist
Copy link
Contributor

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 undertakes a significant refactoring effort to streamline the v3 migration utilities. The primary goal is to eliminate code duplication and improve the structural integrity of the codebase by introducing a set of generic helper functions and types. These new utilities centralize common patterns, such as processing configuration blocks, handling comments, and constructing extractor logic, making the migration process more robust and easier to manage.

Highlights

  • Centralized Utility Functions: Common logic for parsing configuration blocks, extracting comments, formatting output, and building extractor chains has been moved into new, reusable helper functions in cmd/internal/migrations/v3/common.go.
  • Reduced Duplication: Repeated code for tasks like comment extraction, AST base identifier resolution, and iterating over config blocks has been replaced with calls to the new centralized helpers, significantly reducing boilerplate across multiple migration files.
  • Improved Code Structure: The refactoring enhances the overall maintainability and readability of the migration utilities by promoting consistency and separating concerns.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 refactors the migration scripts to reduce code duplication by centralizing common logic into helper functions in cmd/internal/migrations/v3/common.go. The introduction of functions like IterateConfigBlocks, BuildExtractorChain, and GetBaseIdent is a great improvement. However, I've found a critical issue in csrfconfig.go where a refactoring introduces a bug that will lead to malformed code. I've also noted some newly added but unused code in common.go that should be addressed. Overall, a good refactoring effort that just needs a couple of adjustments.

@coderabbitai
Copy link

coderabbitai bot commented Nov 30, 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.

Walkthrough

Adds shared migration helpers (AST base-ident resolution, comment/value extraction, config-block iteration, field formatting, extractor-chain builder) and refactors multiple v3 migration files to use them, replacing duplicated parsing/formatting logic while preserving existing migration behavior.

Changes

Cohort / File(s) Summary
New utility helpers
cmd/internal/migrations/v3/common.go
Adds GetBaseIdent, ExtractCommentAndValue, FormatFieldWithComment, IterateConfigBlocks, BuildExtractorChain and supporting regex/text utilities for AST resolution, comment/value splitting, config-block iteration, and extractor-chain assembly.
AST base-ident replacement
cmd/internal/migrations/v3/context_methods.go, cmd/internal/migrations/v3/redirect_methods.go
Replaces local expression-walking baseIdent logic with calls to GetBaseIdent(sel.X) for consistent AST identifier resolution.
Comment/value extraction
cmd/internal/migrations/v3/cache_config.go
Delegates CacheControl comment/value splitting to ExtractCommentAndValue; no behavioral change beyond extraction implementation.
Extractor-chain & field formatting
cmd/internal/migrations/v3/jwt_extractor.go, cmd/internal/migrations/v3/key_auth_config.go, cmd/internal/migrations/v3/paseto_extractor.go
Replaces ad-hoc extractor-chain assembly and inline TODO/comment formatting with BuildExtractorChain and FormatFieldWithComment, standardizing emitted field lines.
Config-block iteration refactor
cmd/internal/migrations/v3/csrfconfig.go, cmd/internal/migrations/v3/encryptcookie_config.go, cmd/internal/migrations/v3/session_config.go, cmd/internal/migrations/v3/session_extractor.go
Replaces manual scanning and manual content reassembly of <Type>.Config blocks with IterateConfigBlocks(content, reConfig, processor) callbacks; processors apply per-block transformations using the new helpers.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Areas needing close review:
    • common.go: AST traversal correctness in GetBaseIdent and edge-cases in IterateConfigBlocks.
    • csrfconfig.go, session_extractor.go: ensure per-block transformations preserve indentation, comments, and original block boundaries.
    • BuildExtractorChain / FormatFieldWithComment: verify produced extractor strings and comment placement match prior output.

Possibly related PRs

Suggested labels

codex

Suggested reviewers

  • gaby
  • sixcolors
  • efectn

Poem

🐰 Hopping through code with nimble paws,
I split comments, stitch extractors, mend small flaws.
Helpers planted neat in rows, tidy and spruce,
Blocks fall in line, migrations find their use. ✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning No pull request description was provided. The template requires explanation of details, the problem being solved, and commit formatting guidelines. Add a detailed description explaining the refactoring rationale, which duplicates were removed, how the new helper functions improve maintainability, and ensure commit messages follow emoji conventions.
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main objective—refactoring code to eliminate duplicate functionality across migration modules by extracting common helpers.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/refactor-code-duplicates-01SAVnQK9oMQTFA6aZLRVy6R

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e590146 and d625bc8.

📒 Files selected for processing (1)
  • cmd/internal/migrations/v3/common.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/internal/migrations/v3/common.go
⏰ 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). (4)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)

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: 2

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/session_extractor.go (1)

60-60: Orphaned comment fragment.

This appears to be a leftover documentation fragment that should either be completed or removed.

-// instead of KeyLookup/AuthScheme and removes the deprecated fields.
cmd/internal/migrations/v3/csrfconfig.go (1)

22-36: Malformed output due to double "Extractor:" prefix.

The extractor variable includes "Extractor: extractors.FromX(...)", but FormatFieldWithComment on line 35 expects the field name and value separately. The current code produces output like:

Extractor: extractors.FromHeader("key"):,

The extractor assignments should only contain the function call, and line 35 should pass "Extractor" as the field name.

 			return replaceKeyLookup(cfg, func(indent, val, comma, comment, newline string) string {
 				var extractor string
 				switch {
 				case strings.HasPrefix(val, "header:"):
-					extractor = fmt.Sprintf("Extractor: extractors.FromHeader(%q)", strings.TrimPrefix(val, "header:"))
+					extractor = fmt.Sprintf("extractors.FromHeader(%q)", strings.TrimPrefix(val, "header:"))
 				case strings.HasPrefix(val, "form:"):
-					extractor = fmt.Sprintf("Extractor: extractors.FromForm(%q)", strings.TrimPrefix(val, "form:"))
+					extractor = fmt.Sprintf("extractors.FromForm(%q)", strings.TrimPrefix(val, "form:"))
 				case strings.HasPrefix(val, "query:"):
-					extractor = fmt.Sprintf("Extractor: extractors.FromQuery(%q)", strings.TrimPrefix(val, "query:"))
+					extractor = fmt.Sprintf("extractors.FromQuery(%q)", strings.TrimPrefix(val, "query:"))
 				default:
 					return FormatFieldWithComment(indent, "// TODO: migrate KeyLookup", val, "", comment, newline)
 				}

-				return FormatFieldWithComment(indent, extractor, "", comma, comment, newline)
+				return FormatFieldWithComment(indent, "Extractor", extractor, comma, comment, newline)
 			})
🧹 Nitpick comments (3)
cmd/internal/migrations/v3/common.go (2)

528-537: Reorder struct fields for better memory alignment.

The linter reports a fieldalignment issue. Reordering fields can reduce memory usage from 40 to 32 pointer bytes.

 type LookupMapper struct {
-	// Map of prefix (e.g., "header") to extractor function name (e.g., "FromHeader")
-	Mappings map[string]string
 	// Package name for the extractor (e.g., "extractors")
 	Package string
+	// Default auth scheme if applicable (e.g., "Bearer")
+	DefaultAuthScheme string
+	// Map of prefix (e.g., "header") to extractor function name (e.g., "FromHeader")
+	Mappings map[string]string
 	// Whether auth scheme handling is needed (e.g., for JWT "Authorization: Bearer")
 	HasAuthScheme bool
-	// Default auth scheme if applicable (e.g., "Bearer")
-	DefaultAuthScheme string
 }

624-635: Consider consistency with ProcessLookupString for package naming.

BuildExtractorChain hardcodes "extractors.Chain", while ProcessLookupString uses mapper.Package for flexibility. If the extractor package is ever aliased differently, this could cause inconsistencies.

cmd/internal/migrations/v3/jwt_extractor.go (1)

41-73: Helper-based TokenLookup migration looks solid; extractor == "" guard is redundant dead code

The refactor to drive TokenLookup through FormatFieldWithComment and BuildExtractorChain looks correct and nicely aligned with the common helpers:

  • Unsupported token lookup parts now cleanly fall back to a commented line via
    FormatFieldWithComment(indent, "// TODO: migrate TokenLookup", val, "", comment, newline), which preserves the original value and any trailing comment while safely disabling the field.
  • When all parts are recognized, BuildExtractorChain(extractors) plus
    FormatFieldWithComment(indent, "Extractor", extractor, comma, comment, newline) yields a well‑formed Extractor field with the original comma/comment behavior preserved.

One minor clean-up opportunity:

  • Given the current control flow and BuildExtractorChain implementation, the if extractor == "" check is effectively unreachable:
    • If no parts are recognized, the default branch in the loop already returns the TODO comment.
    • If we reach BuildExtractorChain, then len(extractors) >= 1, so it always returns a non‑empty string.
  • You could simplify the tail of the callback by dropping that guard:
-					extractor := BuildExtractorChain(extractors)
-					if extractor == "" {
-						return FormatFieldWithComment(indent, "// TODO: migrate TokenLookup", val, "", comment, newline)
-					}
-
-					return FormatFieldWithComment(indent, "Extractor", extractor, comma, comment, newline)
+					extractor := BuildExtractorChain(extractors)
+					return FormatFieldWithComment(indent, "Extractor", extractor, comma, comment, newline)

Optionally, you might also factor "// TODO: migrate TokenLookup" into a local const to avoid repeating the literal in both fallback sites, but that’s purely style.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 339389a and f263084.

📒 Files selected for processing (11)
  • cmd/internal/migrations/v3/cache_config.go (1 hunks)
  • cmd/internal/migrations/v3/common.go (2 hunks)
  • cmd/internal/migrations/v3/context_methods.go (1 hunks)
  • cmd/internal/migrations/v3/csrfconfig.go (2 hunks)
  • cmd/internal/migrations/v3/encryptcookie_config.go (1 hunks)
  • cmd/internal/migrations/v3/jwt_extractor.go (1 hunks)
  • cmd/internal/migrations/v3/key_auth_config.go (1 hunks)
  • cmd/internal/migrations/v3/paseto_extractor.go (2 hunks)
  • cmd/internal/migrations/v3/redirect_methods.go (1 hunks)
  • cmd/internal/migrations/v3/session_config.go (1 hunks)
  • cmd/internal/migrations/v3/session_extractor.go (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (10)
cmd/internal/migrations/v3/redirect_methods.go (1)
cmd/internal/migrations/v3/common.go (1)
  • GetBaseIdent (488-501)
cmd/internal/migrations/v3/cache_config.go (1)
cmd/internal/migrations/v3/common.go (1)
  • ExtractCommentAndValue (506-516)
cmd/internal/migrations/v3/paseto_extractor.go (1)
cmd/internal/migrations/v3/common.go (1)
  • FormatFieldWithComment (520-525)
cmd/internal/migrations/v3/encryptcookie_config.go (1)
cmd/internal/migrations/v3/common.go (1)
  • IterateConfigBlocks (594-622)
cmd/internal/migrations/v3/session_extractor.go (1)
cmd/internal/migrations/v3/common.go (3)
  • IterateConfigBlocks (594-622)
  • FormatFieldWithComment (520-525)
  • BuildExtractorChain (626-635)
cmd/internal/migrations/v3/session_config.go (1)
cmd/internal/migrations/v3/common.go (1)
  • IterateConfigBlocks (594-622)
cmd/internal/migrations/v3/jwt_extractor.go (1)
cmd/internal/migrations/v3/common.go (2)
  • FormatFieldWithComment (520-525)
  • BuildExtractorChain (626-635)
cmd/internal/migrations/v3/csrfconfig.go (1)
cmd/internal/migrations/v3/common.go (2)
  • IterateConfigBlocks (594-622)
  • FormatFieldWithComment (520-525)
cmd/internal/migrations/v3/key_auth_config.go (1)
cmd/internal/migrations/v3/common.go (2)
  • FormatFieldWithComment (520-525)
  • BuildExtractorChain (626-635)
cmd/internal/migrations/v3/context_methods.go (1)
cmd/internal/migrations/v3/common.go (1)
  • GetBaseIdent (488-501)
🪛 GitHub Actions: golangci-lint
cmd/internal/migrations/v3/common.go

[error] 559-559: golangci-lint: string header has 3 occurrences, make it a constant (goconst)

🪛 GitHub Check: lint
cmd/internal/migrations/v3/common.go

[failure] 528-528:
fieldalignment: struct with 40 pointer bytes could be 32 (govet)


[failure] 559-559:
string header has 3 occurrences, make it a constant (goconst)

⏰ 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). (4)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
  • GitHub Check: Build (1.25.x, windows-latest)
🔇 Additional comments (11)
cmd/internal/migrations/v3/common.go (2)

488-501: LGTM - Clean AST traversal helper.

The recursive unwrapping pattern using an infinite loop with type switch is idiomatic for Go AST traversal. Good extraction of common logic.


506-516: LGTM - Useful comment extraction utility.

Correctly handles both line (//) and block (/*) comment styles.

cmd/internal/migrations/v3/redirect_methods.go (1)

41-44: LGTM - Good refactor to use shared helper.

The replacement of local baseIdent with GetBaseIdent is correct. The nil check and isFiberCtx validation logic remain unchanged.

cmd/internal/migrations/v3/context_methods.go (1)

38-41: LGTM - Consistent refactor with redirect_methods.go.

The inline usage of GetBaseIdent with nil check is clean and maintains the same behavior as the previous local implementation.

cmd/internal/migrations/v3/session_config.go (1)

17-19: Nice simplification using the shared helper.

The refactor is cleaner. Note that strings.ReplaceAll will replace all occurrences of "Expiration:" in the block, including in comments or string literals. This is likely acceptable for config structs, but worth being aware of.

cmd/internal/migrations/v3/key_auth_config.go (1)

51-60: LGTM - Good adoption of shared helpers.

The refactor correctly uses BuildExtractorChain and FormatFieldWithComment. The TODO comment formatting (line 51, 57) leverages FormatFieldWithComment in a slightly unconventional way but produces the intended output.

cmd/internal/migrations/v3/encryptcookie_config.go (1)

17-23: Clean refactor using the new IterateConfigBlocks helper.

The migration logic is now delegated to the centralized helper, simplifying the code and ensuring consistent block processing across migration files.

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

48-48: Consistent use of FormatFieldWithComment for TODO comments.

The formatting preserves the original value alongside the TODO comment, enabling developers to reference it during manual migration.


98-102: LGTM - Standardized field formatting.

Both the fallback TODO case and the successful extractor case now use the centralized FormatFieldWithComment helper, ensuring consistent output formatting.

cmd/internal/migrations/v3/cache_config.go (1)

38-41: Good use of ExtractCommentAndValue helper.

Delegating comment extraction to the centralized helper reduces duplication and ensures consistent handling of both // and /* comment styles.

cmd/internal/migrations/v3/session_extractor.go (1)

17-42: Clean refactor using centralized helpers.

The migration logic now properly leverages IterateConfigBlocks, BuildExtractorChain, and FormatFieldWithComment for consistent block processing and field formatting.

Removes unused exported functions that were added but not utilized:
- LookupMapper struct
- ProcessLookupString function
- ExtractorMapping struct
- StandardExtractorMappings function

These were added in anticipation of future use but are currently
not called anywhere in the codebase. Keeping them would add
unnecessary maintenance burden and increase the API surface.

This addresses linter feedback about unused code and keeps the
codebase focused on actively used utilities.
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: 0

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

503-516: Consider refactoring replaceFieldImpl to use this helper.

The comment extraction logic in replaceFieldImpl (lines 176-183) duplicates the logic now provided by ExtractCommentAndValue. Since this PR aims to remove duplicates, you could refactor replaceFieldImpl to call this helper function instead.

Apply this diff to replaceFieldImpl to use the helper:

 func replaceFieldImpl(src, field string, unquote bool, fn func(indent, val, comma, comment, newline string) string) string {
 	re := regexp.MustCompile(`(?m)^(\s*)` + regexp.QuoteMeta(field) + `:\s*([^\n]+)(\n?)`)
 	return re.ReplaceAllStringFunc(src, func(s string) string {
 		sub := re.FindStringSubmatch(s)
 		indent := sub[1]
 		val := strings.TrimSpace(sub[2])
 		newline := sub[3]
 
-		comment := ""
-		if idx := strings.Index(val, "//"); idx >= 0 {
-			comment = strings.TrimSpace(val[idx:])
-			val = strings.TrimSpace(val[:idx])
-		} else if idx := strings.Index(val, "/*"); idx >= 0 {
-			comment = strings.TrimSpace(val[idx:])
-			val = strings.TrimSpace(val[:idx])
-		}
+		val, comment := ExtractCommentAndValue(val)
 
 		comma := ""
 		if strings.HasSuffix(val, ",") {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f263084 and 9976cdd.

📒 Files selected for processing (1)
  • cmd/internal/migrations/v3/common.go (2 hunks)
⏰ 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). (4)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
🔇 Additional comments (4)
cmd/internal/migrations/v3/common.go (4)

485-501: LGTM! Clean AST traversal implementation.

The recursive resolution through Ident, SelectorExpr, and CallExpr is correct and handles the typical Go expression patterns for extracting base identifiers. The loop-based approach avoids stack overflow for deeply nested expressions.


518-525: LGTM! Clear and concise formatting helper.

The function correctly formats field assignments with consistent spacing and optional trailing comments.


527-558: LGTM! Robust block processing utility.

The function correctly handles multiple config blocks, extracts them using brace-aware parsing, and safely returns the original content if any errors occur during reconstruction.


560-571: LGTM! Extractor chain building logic is correct and properly used.

The function correctly handles all three cases (no extractors, single extractor, multiple extractors). Verification confirms it's actively used by jwt_extractor.go, key_auth_config.go, and session_extractor.go. The export is justified.

The extractor variable was incorrectly including the 'Extractor:'
prefix before being passed to FormatFieldWithComment, which then
added another ': ', resulting in invalid syntax like:
  Extractor: extractors.FromHeader(...): ,

Fixed by:
- Removing 'Extractor: ' prefix from extractor variable
- Passing 'Extractor' as the fieldName parameter to FormatFieldWithComment
- Now correctly generates: Extractor: extractors.FromHeader(...),

This fixes the test failures:
- Test_MigrateCSRFConfig_KeyLookup
- Test_MigrateCSRFConfig_KeyLookup_Form
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: 0

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

31-32: Unconventional but functional TODO formatting.

Using FormatFieldWithComment with a TODO comment as the fieldName produces output like // TODO: migrate KeyLookup: "cookie:csrf", which is valid but slightly abuses the helper's intended API. Consider whether a dedicated helper for TODO comments would improve clarity, or simply document this pattern if it's intentional across migrations.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9976cdd and 349c2da.

📒 Files selected for processing (1)
  • cmd/internal/migrations/v3/csrfconfig.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/csrfconfig.go (1)
cmd/internal/migrations/v3/common.go (2)
  • IterateConfigBlocks (530-558)
  • FormatFieldWithComment (520-525)
⏰ 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). (4)
  • GitHub Check: Build (1.25.x, macos-13)
  • 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 (3)
cmd/internal/migrations/v3/csrfconfig.go (3)

14-17: LGTM!

The function setup and regex patterns are well-defined. The reSession pattern correctly handles SessionKey lines with optional commas and trailing comments.


39-52: LGTM!

The conditional import addition, error handling, and success messaging are all correctly implemented. The extractors import is only added when actual changes occur.


18-21: Clean refactor using shared helpers.

The use of IterateConfigBlocks properly delegates block iteration logic to the common helper. The ExpirationIdleTimeout rename and SessionKey removal are straightforward. The replaceKeyLookup helper exists in common.go and is correctly invoked with the callback pattern to migrate KeyLookup to Extractor with appropriate prefix-based routing (header, form, query).

Note: The code snippet shown ends prematurely at line 20. The actual changes extend through line 36, including the full replaceKeyLookup callback that handles the extractor migration logic.

@ReneWerner87
Copy link
Member Author

/gemini review

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 is an excellent refactoring effort that successfully removes duplicated code and improves the overall structure of the migration scripts. By centralizing common logic into helper functions within cmd/internal/migrations/v3/common.go, the code becomes much more maintainable and easier to read. The changes are well-executed across all modified files. My review includes a few minor suggestions to remove some redundant error checks in the new IterateConfigBlocks helper function.

According to Go documentation, strings.Builder.WriteString always
returns a nil error, making the error checks unreachable. Simplified
the function by removing these checks and adding nolint directives
to document the intentional ignoring of return values.

Changes:
- Removed three unreachable if err != nil blocks (lines 539-541, 549-551, 554-556)
- Added //nolint:errcheck comments explaining why errors are ignored
- Reduces code complexity while maintaining identical behavior

This addresses code review feedback about unreachable error handling.
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

🧹 Nitpick comments (2)
cmd/internal/migrations/v3/common.go (2)

485-501: GetBaseIdent works, but consider handling more AST node wrappers.

The iterative walk over ast.Expr is correct for identifiers, selectors, and call expressions and avoids recursion depth issues. For slightly more robustness against common syntactic wrappers, you could also unwrap *ast.ParenExpr (and optionally *ast.StarExpr) before giving up, without changing existing behavior.

 func GetBaseIdent(expr ast.Expr) *ast.Ident {
 	for {
 		switch e := expr.(type) {
 		case *ast.Ident:
 			return e
 		case *ast.SelectorExpr:
 			expr = e.X
 		case *ast.CallExpr:
 			expr = e.Fun
+		case *ast.ParenExpr:
+			expr = e.X
+		case *ast.StarExpr:
+			expr = e.X
 		default:
 			return nil
 		}
 	}
 }

503-516: Comment/value splitter is correct; consider reusing it in existing code.

ExtractCommentAndValue mirrors the inline // / /* splitting logic already present in replaceFieldImpl, which keeps behavior consistent with previous code. To fully realize the deduplication goal of this PR, consider switching replaceFieldImpl’s manual parsing to call ExtractCommentAndValue instead of re-implementing the same logic there.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 349c2da and e590146.

📒 Files selected for processing (1)
  • cmd/internal/migrations/v3/common.go (2 hunks)
⏰ 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). (4)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
  • GitHub Check: Build (1.25.x, windows-latest)
🔇 Additional comments (3)
cmd/internal/migrations/v3/common.go (3)

3-10: Import of go/ast is appropriate and scoped.

go/ast is only used by GetBaseIdent and keeps the import set minimal; no issues here.


518-525: Field formatting helper looks solid.

FormatFieldWithComment centralizes the spacing rules and produces the expected Field: value, // comment layout while omitting extra whitespace when there’s no comment; no issues spotted.


554-565: BuildExtractorChain matches the intended API shape.

The helper cleanly encodes the 0/1/many cases for extractors and centralizes the extractors.Chain(...) construction; this should keep call sites much simpler.

Guards against potential panic from nested or overlapping pattern matches.
If a regex match falls inside a block that has already been processed
(m[0] < last), attempting content[last:m[0]] would panic with an invalid
slice range.

While current patterns (e.g., csrf.Config{) are unlikely to match within
their own blocks, this defensive check prevents edge cases and makes the
function more robust for future pattern additions.

Changes:
- Added if m[0] < last check to skip overlapping matches
- Added explanatory comment for the guard condition
- No behavior change for current usage patterns

This addresses code review feedback about potential slice panic scenarios.
@ReneWerner87 ReneWerner87 merged commit 50fd2fc into master Nov 30, 2025
15 checks passed
@ReneWerner87 ReneWerner87 deleted the claude/refactor-code-duplicates-01SAVnQK9oMQTFA6aZLRVy6R branch November 30, 2025 16:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants