-
Notifications
You must be signed in to change notification settings - Fork 16
Refactor code to remove duplicates and improve structure #233
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
Refactor code to remove duplicates and improve structure #233
Conversation
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**
Summary of ChangesHello @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 Highlights
Using Gemini Code AssistThe 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
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 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
|
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 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.
|
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. WalkthroughAdds 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
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. Comment |
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: 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
extractorvariable includes"Extractor: extractors.FromX(...)", butFormatFieldWithCommenton 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
fieldalignmentissue. 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.
BuildExtractorChainhardcodes"extractors.Chain", whileProcessLookupStringusesmapper.Packagefor 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 codeThe refactor to drive
TokenLookupthroughFormatFieldWithCommentandBuildExtractorChainlooks 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‑formedExtractorfield with the original comma/comment behavior preserved.One minor clean-up opportunity:
- Given the current control flow and
BuildExtractorChainimplementation, theif extractor == ""check is effectively unreachable:
- If no parts are recognized, the
defaultbranch in the loop already returns the TODO comment.- If we reach
BuildExtractorChain, thenlen(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 localconstto avoid repeating the literal in both fallback sites, but that’s purely style.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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
baseIdentwithGetBaseIdentis correct. The nil check andisFiberCtxvalidation logic remain unchanged.cmd/internal/migrations/v3/context_methods.go (1)
38-41: LGTM - Consistent refactor with redirect_methods.go.The inline usage of
GetBaseIdentwith 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.ReplaceAllwill 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
BuildExtractorChainandFormatFieldWithComment. The TODO comment formatting (line 51, 57) leveragesFormatFieldWithCommentin 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.
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: 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 byExtractCommentAndValue. Since this PR aims to remove duplicates, you could refactorreplaceFieldImplto call this helper function instead.Apply this diff to
replaceFieldImplto 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
📒 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, andsession_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
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: 0
🧹 Nitpick comments (1)
cmd/internal/migrations/v3/csrfconfig.go (1)
31-32: Unconventional but functional TODO formatting.Using
FormatFieldWithCommentwith a TODO comment as thefieldNameproduces 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
📒 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
reSessionpattern 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
extractorsimport is only added when actual changes occur.
18-21: Clean refactor using shared helpers.The use of
IterateConfigBlocksproperly delegates block iteration logic to the common helper. TheExpiration→IdleTimeoutrename andSessionKeyremoval are straightforward. ThereplaceKeyLookuphelper exists in common.go and is correctly invoked with the callback pattern to migrateKeyLookuptoExtractorwith 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
replaceKeyLookupcallback that handles the extractor migration logic.
|
/gemini review |
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 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.
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
🧹 Nitpick comments (2)
cmd/internal/migrations/v3/common.go (2)
485-501:GetBaseIdentworks, but consider handling more AST node wrappers.The iterative walk over
ast.Expris 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.
ExtractCommentAndValuemirrors the inline////*splitting logic already present inreplaceFieldImpl, which keeps behavior consistent with previous code. To fully realize the deduplication goal of this PR, consider switchingreplaceFieldImpl’s manual parsing to callExtractCommentAndValueinstead of re-implementing the same logic there.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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 ofgo/astis appropriate and scoped.
go/astis only used byGetBaseIdentand keeps the import set minimal; no issues here.
518-525: Field formatting helper looks solid.
FormatFieldWithCommentcentralizes the spacing rules and produces the expectedField: value, // commentlayout while omitting extra whitespace when there’s no comment; no issues spotted.
554-565:BuildExtractorChainmatches 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.
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.