-
Notifications
You must be signed in to change notification settings - Fork 15
Update migration for moved config fields #149
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
WalkthroughThe migration logic in Changes
Sequence Diagram(s)sequenceDiagram
participant AppConfig as App Config
participant Migration as Migration Logic
participant ListenCall as .Listen Call
AppConfig->>Migration: Contains DisableStartupMessage, EnablePrintRoutes
Migration->>AppConfig: Removes DisableStartupMessage, EnablePrintRoutes
Migration->>ListenCall: Adds fields to fiber.ListenConfig (creates or extends)
ListenCall->>Migration: Confirm fields present
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~15 minutes Suggested labels
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ 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. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
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 introduces an update to the v3 migration script, specifically addressing the relocation of certain configuration fields related to application listening behavior. The primary goal is to ensure that DisableStartupMessage
and EnablePrintRoutes
are correctly migrated from the general fiber.Config
to the more specific fiber.ListenConfig
associated with app.Listen
calls, maintaining application functionality during the upgrade process.
Highlights
- Configuration Field Migration: Implemented a migration strategy to move
DisableStartupMessage
andEnablePrintRoutes
fields from the mainfiber.Config
struct to thefiber.ListenConfig
used inapp.Listen
calls. This ensures that these settings are applied directly to the listener. - Dynamic Listener Configuration: The migration now intelligently injects the collected
DisableStartupMessage
andEnablePrintRoutes
values intoapp.Listen
calls. If afiber.ListenConfig
is not already present, one is created; otherwise, the existingfiber.ListenConfig
is extended with these fields. - Enhanced Migration Testing: Added comprehensive tests to validate the new migration logic, covering scenarios where configuration fields are spread across multiple files and when
fiber.ListenConfig
is already explicitly used inapp.Listen
calls.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command>
or @gemini-code-assist <command>
. Below is a summary of the supported commands.
Feature | Command | Description |
---|---|---|
Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/
folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.
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 updates the v3 migration script to handle moving DisableStartupMessage
and EnablePrintRoutes
from fiber.Config
to fiber.ListenConfig
. The implementation correctly handles finding these settings and injecting them into app.Listen
calls, including cases where ListenConfig
is already present. The new tests cover these scenarios well.
My review focuses on improving the robustness of the regular expression-based code modifications by adding bounds checks to prevent panics and by making one of the regexes more specific to avoid incorrect matches.
sub := reWithCfg.FindStringSubmatch(s) | ||
addr := sub[1] |
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.
Accessing slice elements from FindStringSubmatch
without checking the slice length can lead to a panic if the regex matches but fails to capture the expected groups. It's safer to check the length of sub
before accessing its elements.
sub := reWithCfg.FindStringSubmatch(s)
if len(sub) < 3 {
return s
}
addr := sub[1]
return s | ||
} | ||
|
||
addr := rePlain.FindStringSubmatch(s)[1] |
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.
return fmt.Sprintf(".Listen(%s, fiber.ListenConfig{%s})", addr, cfg) | ||
}) | ||
|
||
rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\)`) |
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.
This regular expression can be made more specific to only match .Listen
calls with a single argument. By ensuring no other arguments follow the address (\s*\)
), you can then remove the strings.Contains
check on lines 435-437, which makes the migration logic more robust.
rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\s*\)`)
if strings.Contains(s, "fiber.ListenConfig") { | ||
return s | ||
} |
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.
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)
405-454
: Consider edge cases in regex patterns for Listen call matching.The regex patterns for matching
.Listen
calls may not handle all edge cases properly:
- The pattern
\.Listen\(([^,\n)]+)\)
could match non-Fiber Listen methods- Whitespace and comment handling could be improved
- Multi-line Listen calls might not be handled correctly
Consider making the regex patterns more robust:
-reWithCfg := regexp.MustCompile(`\.Listen\(([^,]+),\s*fiber.ListenConfig\{([^}]*)\}\)`) +reWithCfg := regexp.MustCompile(`\.Listen\s*\(\s*([^,]+),\s*fiber\.ListenConfig\s*\{\s*([^}]*)\s*\}\s*\)`) -rePlain := regexp.MustCompile(`\.Listen\(([^,\n)]+)\)`) +rePlain := regexp.MustCompile(`\.Listen\s*\(\s*([^,\n)]+)\s*\)`)Also consider adding validation to ensure we're only matching Fiber app Listen calls by checking for common patterns like
app.Listen
or similar variable names.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
cmd/internal/migrations/v3/common.go
(1 hunks)cmd/internal/migrations/v3/common_test.go
(1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: ReneWerner87
PR: gofiber/contrib#0
File: :0-0
Timestamp: 2024-07-03T11:59:00.303Z
Learning: The i18n functionality in the gofiber/contrib repository is being refactored from middleware to a global container to improve robustness and performance. The global container will be initialized once before setting up routes and will manage the i18n bundle and localizer map.
Learnt from: ReneWerner87
PR: gofiber/contrib#0
File: :0-0
Timestamp: 2024-10-16T10:04:06.328Z
Learning: The i18n functionality in the gofiber/contrib repository is being refactored from middleware to a global container to improve robustness and performance. The global container will be initialized once before setting up routes and will manage the i18n bundle and localizer map.
cmd/internal/migrations/v3/common_test.go (11)
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the Test
method in app.go
.
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
.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within clean-code/app/datasources/database/db_mock.go
, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/server/server.go:14-16
Timestamp: 2024-11-23T19:50:41.765Z
Learning: In the clean-code
example at clean-code/app/server/server.go
using the Go Fiber framework, it's acceptable to omit production-level features like context usage and graceful shutdown handling to keep the example simple.
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.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/main.go:0-0
Timestamp: 2024-11-23T19:35:36.767Z
Learning: In the Go clean-code
example (clean-code/app/main.go
) in the gofiber/recipes
repository, it's acceptable to omit graceful shutdown handling, as the example code prioritizes simplicity over production-level practices.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for Session.Save
already exist in the middleware/session/session_test.go
file, specifically in the Test_Session_Save
and Test_Session_Save_Expiration
functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for Session.Save
already exist in the middleware/session/session_test.go
file, specifically in the Test_Session_Save
and Test_Session_Save_Expiration
functions.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
🧬 Code Graph Analysis (1)
cmd/internal/migrations/v3/common.go (1)
cmd/internal/helpers.go (1)
ChangeFileContent
(36-68)
🔇 Additional comments (5)
cmd/internal/migrations/v3/common.go (3)
416-430
: LGTM! Comma handling logic is well implemented.The logic for handling comma placement in both existing and new
ListenConfig
structs is correct:
- Checks for existing fields to avoid duplicates
- Properly handles comma placement
- Removes trailing commas appropriately
Minor suggestion: Consider extracting the comma handling logic into a helper function to reduce duplication:
func appendConfigField(cfg, fieldName, fieldValue string) string { if len(cfg) > 0 && !strings.HasSuffix(cfg, ",") { cfg += "," } return cfg + " " + fieldName + ": " + fieldValue + "," }Also applies to: 441-448
401-403
: LGTM! Error handling is well implemented.The error handling approach is solid:
- Both transformation steps have appropriate error handling
- Error messages provide clear context about which step failed
- Success message is printed only after both transformations complete successfully
Also applies to: 455-461
367-400
: Address potential race condition with package-level variables.The use of package-level variables
disableStartup
andenablePrint
to pass state between the twoChangeFileContent
calls creates a race condition risk if multiple migrations run concurrently.Consider refactoring to avoid shared state:
func MigrateConfigListenerFields(cmd *cobra.Command, cwd string, _, _ *semver.Version) error { - var disableStartup string - var enablePrint string + type extractedFields struct { + disableStartup string + enablePrint string + } + + var extracted extractedFields err := internal.ChangeFileContent(cwd, func(content string) string { replacer := strings.NewReplacer( "Prefork:", "EnablePrefork:", "Network:", "ListenerNetwork:", ) content = replacer.Replace(content) reStartup := regexp.MustCompile(`(?m)^\s*DisableStartupMessage:\s*([^,]+),?\n`) content = reStartup.ReplaceAllStringFunc(content, func(s string) string { - if disableStartup == "" { + if extracted.disableStartup == "" { sub := reStartup.FindStringSubmatch(s) if len(sub) > 1 { - disableStartup = strings.TrimSpace(sub[1]) + extracted.disableStartup = strings.TrimSpace(sub[1]) } } return "" }) rePrint := regexp.MustCompile(`(?m)^\s*EnablePrintRoutes:\s*([^,]+),?\n`) content = rePrint.ReplaceAllStringFunc(content, func(s string) string { - if enablePrint == "" { + if extracted.enablePrint == "" { sub := rePrint.FindStringSubmatch(s) if len(sub) > 1 { - enablePrint = strings.TrimSpace(sub[1]) + extracted.enablePrint = strings.TrimSpace(sub[1]) } } return "" }) return content })Then update the second transformation to use
extracted.disableStartup
andextracted.enablePrint
.⛔ Skipped due to learnings
Learnt from: sixcolors PR: gofiber/fiber#3625 File: middleware/session/config.go:57-58 Timestamp: 2025-07-27T17:28:53.403Z Learning: In the session middleware `Config` struct, the `Extractor` field uses function closures (like `FromCookie(key)`), making it impossible to introspect extractor parameters at runtime for validation purposes without complex reflection techniques.
cmd/internal/migrations/v3/common_test.go (2)
475-515
: Excellent test refactoring! The separation of concerns improves realism.The refactoring to split the test into separate
app.go
andmain.go
files is a great improvement:
- Better simulates real-world project structure where app configuration and Listen calls are often in different files
- Comprehensive assertions verify both the removal of fields from app config and their addition to the Listen call
- Proper use of testify assertions as per project standards
The test thoroughly validates the migration behavior and covers the primary use case effectively.
517-555
: Excellent addition! This test covers a critical edge case.The new test function provides essential coverage for the scenario where
app.Listen
already uses afiber.ListenConfig
parameter:
- Tests the merging behavior to ensure existing fields (
EnablePrefork
) are preserved- Verifies that extracted fields (
DisableStartupMessage
,EnablePrintRoutes
) are properly added- Maintains consistent test structure and proper assertions
- Uses realistic file separation like the main test
This test case is crucial for ensuring the migration doesn't break existing ListenConfig usage and properly merges the configuration fields.
Summary
fiber.Config
and add them to Listen callsTesting
go test ./...
go run github.com/golangci/golangci-lint/cmd/[email protected] run ./...
(fails: can't load config because go1.23 is lower than target 1.24)https://chatgpt.com/codex/tasks/task_e_6888ca5c6558832686a65efdaf1d37de
Summary by CodeRabbit
DisableStartupMessage
andEnablePrintRoutes
are correctly moved to the listener configuration.