Skip to content

Enhance client usage migration for acquire agent patterns#247

Merged
ReneWerner87 merged 8 commits into
masterfrom
codex/2025-12-01-13-56-00
Dec 2, 2025
Merged

Enhance client usage migration for acquire agent patterns#247
ReneWerner87 merged 8 commits into
masterfrom
codex/2025-12-01-13-56-00

Conversation

@ReneWerner87
Copy link
Copy Markdown
Member

@ReneWerner87 ReneWerner87 commented Dec 1, 2025

Summary

  • extend the client usage migration to rewrite AcquireAgent flows with nested SetRequestURI calls and Struct handling
  • default assignment handling and header parsing now produce proper response status/body extraction and JSON decoding
  • add targeted tests to cover AcquireAgent rewrites alongside existing migration scenarios

Testing

  • make lint
  • make test

Codex Task

Summary by CodeRabbit

  • New Features

    • Added a migration step that updates client usage patterns and related imports for upgrades in the 2.x→4.0 range; changes are applied automatically during matching releases and surface in verbose migration output.
  • Tests

    • Added extensive tests covering many client-usage scenarios, import updates, AcquireAgent-to-client transformations, response/error handling, headers/queries/auth/TLS cases, and no-change validations.

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

@ReneWerner87 ReneWerner87 requested a review from a team as a code owner December 1, 2025 13:56
@ReneWerner87 ReneWerner87 requested review from efectn, gaby and sixcolors and removed request for a team December 1, 2025 13:56
@gemini-code-assist
Copy link
Copy Markdown
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 significantly extends the client usage migration tool to handle a broader range of patterns, particularly focusing on the AcquireAgent mechanism. The changes ensure that client calls involving complex request configurations, such as setting URIs and headers, and subsequent response processing, including status, body, and JSON struct decoding, are correctly transformed. This update aims to provide a more complete and accurate migration path for existing codebases.

Highlights

  • Enhanced AcquireAgent Migration: The client usage migration now supports more complex AcquireAgent patterns, including those with nested SetRequestURI calls and Struct handling for JSON decoding.
  • Improved Response Handling: Default assignment handling and header parsing have been refined to ensure proper response status/body extraction and accurate JSON decoding during migration.
  • Comprehensive Testing: New targeted tests have been added to cover the expanded AcquireAgent rewrites, alongside existing migration scenarios, ensuring the robustness of the changes.
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
Copy Markdown
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 introduces a migration script to update Fiber client usage patterns, specifically for AcquireAgent flows. The implementation relies heavily on regular expressions and line-by-line parsing, which can be fragile. I've identified a couple of bugs in the implementation related to parsing code blocks and handling imports that could lead to incorrect migrations. Additionally, I've suggested improvements to the new tests to align them with the project's existing testing style for better maintainability. Overall, the changes are a good step towards automating migrations, but the identified issues should be addressed to ensure robustness.

Comment thread cmd/internal/migrations/v3/client_usage.go
Comment thread cmd/internal/migrations/v3/client_usage.go Outdated
Comment thread cmd/internal/migrations/v3/client_usage_internal_test.go
Comment thread cmd/internal/migrations/v3/client_usage_internal_test.go Outdated
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 1, 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 a new v3 migration that rewrites various Fiber client usage patterns (including AcquireAgent flows), registers it for versions >=2.0.0-0 and <4.0.0-0, and includes helpers and tests. Changes are additive and do not modify existing public signatures outside registration. (48 words)

Changes

Cohort / File(s) Summary
Migration Registration
cmd/internal/migrations/lists.go
Added v3migrations.MigrateClientUsage to the Functions slice of the second Migration entry.
Migration Implementation
cmd/internal/migrations/v3/client_usage.go
New file implementing MigrateClientUsage: pattern-based rewrites for Fiber client usage and AcquireAgent blocks, helpers for method mapping, headers/config, bytes/string/struct variants, import injection (github.com/gofiber/fiber/v3/client, conditional encoding/base64), and error-handling normalization.
Tests
cmd/internal/migrations/v3/client_usage_internal_test.go, cmd/internal/migrations/v3/client_usage_test.go
New unit and integration-style tests covering AcquireAgent rewrites, multiple client call-pattern conversions (Bytes/String/Struct, WithBody variants), headers/queries/timeouts, auth/TLS cases, import updates, and overall migration behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Focus review on regex/AST-based rewrite correctness and edge-case handling in cmd/internal/migrations/v3/client_usage.go.
  • Verify import-injection logic (ensureClientImport, conditional base64) and that formatting assumptions match gofmt expectations.
  • Check tests for brittle whitespace/formatting assertions and coverage of critical patterns.

Possibly related PRs

Suggested labels

✏️ Feature

Suggested reviewers

  • gaby
  • sixcolors
  • efectn

Poem

🐇 I hop through code and nudge each old client call,
I stitch new imports in and tidy blocks small,
Tests lined up like carrots, ready to munch,
A swift little migration — a cozy lunchtime lunch,
Hop, patch, commit — a rabbit's gentle scrawl.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding enhancements to the client usage migration specifically for acquire agent patterns, which aligns with the primary modifications in the changeset.
Description check ✅ Passed The description provides a clear summary of changes, testing instructions, and reference to the task, covering the main objectives. However, it lacks detailed explanation of the problems being solved and the rationale behind specific implementation choices.
✨ 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 codex/2025-12-01-13-56-00

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
Copy Markdown

@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

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

8-67: Consider adding t.Parallel() for consistency with other tests.

Other tests in this package (e.g., Test_MigrateClientUsage, Test_MigrateClientUsage_NoChanges) use t.Parallel(). Adding it here would maintain consistency and allow parallel test execution.

Also, consider adding negative assertions to verify old patterns are removed (e.g., fiber.AcquireAgent, a.Parse()).

 func Test_rewriteAcquireAgentBlocks(t *testing.T) {
+	t.Parallel()
+
 	content := `package main
cmd/internal/migrations/v3/client_usage.go (1)

126-137: Brace counting doesn't account for braces in strings or comments.

The brace depth tracking at lines 128-136 (and similarly at 175-184) uses simple string containment checks. This can miscount if a line contains { or } within string literals or comments (e.g., fmt.Println("{")).

For a migration tool, this edge case could produce malformed output. Consider using a more robust approach or documenting this limitation.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 036ded6 and d07031c.

📒 Files selected for processing (4)
  • cmd/internal/migrations/lists.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_internal_test.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
cmd/internal/migrations/lists.go (1)
cmd/internal/migrations/v3/client_usage.go (1)
  • MigrateClientUsage (37-58)
cmd/internal/migrations/v3/client_usage_test.go (1)
cmd/internal/migrations/v3/client_usage.go (1)
  • MigrateClientUsage (37-58)
cmd/internal/migrations/v3/client_usage.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
⏰ 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-13)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-latest)
🔇 Additional comments (6)
cmd/internal/migrations/lists.go (1)

42-42: LGTM!

The MigrateClientUsage function is correctly integrated into the migration pipeline with the appropriate version range constraints.

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

165-219: Test for AcquireAgent rewrite validates the complex transformation.

This test covers the most complex migration path involving AcquireAgent, request setup, header configuration, and struct parsing. The expected output on line 214 is quite long - consider whether this specific assertion might become fragile if the output format changes slightly.


14-102: Comprehensive test coverage for the migration scenarios.

The test validates multiple aspects of the client usage migration including imports, method calls, status/body extraction, and error handling transformations. The assertions are thorough and check both presence of new patterns and absence of old ones. Helper functions (writeTempFile, readFile, newCmd) are properly defined in common_test.go and accessible to this test.

cmd/internal/migrations/v3/client_usage.go (3)

37-58: Migration message printed after changes are written.

The message "Migrating client usage" is printed after the files have already been modified. This is slightly misleading from a UX perspective - typically migration messages are shown before or during the operation. This pattern appears consistent with other migrations in the codebase, so it may be intentional.


260-291: Well-structured pattern-based rewrite loop.

The use of a slice of pattern/builder pairs with ReplaceAllStringFunc is a clean approach that makes it easy to add new patterns. The changed flag is correctly tracked across all replacements.


377-402: Import injection handles both grouped and single import styles.

Good coverage of the two common import syntaxes. The single import conversion to a block import (line 398) is a nice touch that keeps imports organized.

Comment thread cmd/internal/migrations/v3/client_usage.go
Comment thread cmd/internal/migrations/v3/client_usage.go Outdated
@ReneWerner87
Copy link
Copy Markdown
Member Author

/gemini review

Copy link
Copy Markdown
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 introduces a migration script to update client usage patterns from an older API to a new one. The changes are extensive and cover many patterns, including the AcquireAgent flow. The implementation uses regex to find and replace code, which is a practical approach for this kind of task. The accompanying tests are comprehensive and cover a wide range of scenarios.

I've found a few areas where the migration script could be made more robust:

  • The script can fail to migrate code if comments are present in specific locations.
  • One of the regular expressions for parsing assignments is a bit fragile and could be made more specific.
  • The migration for error handling is incomplete as it doesn't update the variable declaration from []error to error, which will leave the code in a non-compilable state.

I've left detailed comments with suggestions for these points. Overall, this is a great addition that will help users migrate their codebases.

Comment thread cmd/internal/migrations/v3/client_usage.go
Comment thread cmd/internal/migrations/v3/client_usage.go Outdated
Comment thread cmd/internal/migrations/v3/client_usage.go Outdated
Copy link
Copy Markdown

@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

♻️ Duplicate comments (2)
cmd/internal/migrations/v3/client_usage.go (2)

685-722: Import injection logic is better, but could be simplified given imports.Process

ensureImport / ensureClientImport now correctly handle multi‑line blocks and single‑line imports, which fixes the earlier bug where multiple import() blocks could be generated. However, given that ChangeFileContent always runs imports.Process on the final source, you don’t really need to micro‑manage grouping, ordering, or even whether there are multiple import declarations.

A simpler and more robust approach would be:

  • If the target import path isn’t already present, just append a plain import "github.com/gofiber/fiber/v3/client" immediately after the package line (and similarly for encoding/base64 when needed).
  • Let imports.Process normalize everything (merge blocks, sort, drop unused imports).

That would reduce the number of regexes and edge cases you have to maintain here, while still producing clean import sets thanks to the existing goimports pass.

If you’d like to confirm that imports.Process handles these cases as expected across Go versions, you can quickly prototype a few source strings with multiple import forms and run them through goimports locally or via a small Go snippet calling imports.Process.


724-731: Global errserr rewrite is unsafe and currently produces non‑compiling migrations

rewriteClientErrorHandling is doing several very broad text‑level rewrites:

updated := clientErrIfPattern.ReplaceAllString(content, "if err != nil {")
updated = clientErrLenPattern.ReplaceAllString(updated, "err != nil")
updated = clientErrComparePattern.ReplaceAllString(updated, "err != nil")
updated = clientErrMapPattern.ReplaceAllString(updated, `"err": err`)
updated = clientErrVarPattern.ReplaceAllString(updated, "err")

This has a few concrete problems:

  • Type error for flows that declare errs []error.
    For patterns like the AcquireAgent struct example, you start with:

    var (
        retCode int
        retBody []byte
        errs    []error
        t       map[string]any
    )
    // ...
    resp, err := client.Post(...)

    After this function runs, errs becomes err in the declaration, yielding err []error, but resp, err := client.Post(...) is assigning the second result of client.Post, which is an error (per the v3 client docs), into that variable. (docs.gofiber.io) This is a compile‑time type mismatch in the migrated code.

  • Overly broad identifier rewrite.
    clientErrVarPattern (\berrs\b) replaces every errs token in the file, including:

    • Unrelated aggregated error slices (e.g. errs = append(errs, ...)),
    • Declarations, not just uses near the migrated client patterns,
    • Any helper code using errs for non‑HTTP concerns.

    This was already raised in a previous review and remains a real risk: a migration pass rewriting entire projects should avoid such global identifier renames unless it can prove they are tied to the transformed constructs.

  • len(errs) rewrites can corrupt expressions.
    clientErrLenPattern blindly rewrites len(errs) to err != nil, and clientErrComparePattern tries to patch up err != nil > 0, but:

    • clientErrComparePattern’s pattern (err\s*!=\s*nil\s*>\s*0) looks incorrect and most likely never fires.
    • Non‑canonical uses like if len(errs) != 0, if len(errs) > 1, or log.Println(len(errs)) will become syntactically invalid or semantically wrong (e.g. if err != nil != 0).

Suggestion

I’d strongly recommend tightening this function rather than letting it operate on arbitrary code:

  • Restrict rewrites to known shapes produced by the earlier migration steps, for example:
    • Exact matches of if len(errs) > 0 {if err != nil {.
    • Exact matches of "errs": errs"err": err.
    • Optional: specific panic(errs) / return ..., errs patterns immediately following rewritten client calls.
  • Either:
    • Handle errs []error declarations explicitly by converting them to err error before you introduce client.*(..., error) assignments, or
    • Avoid touching declarations at all and only rename errs in expressions where you know the new single err exists (i.e., within the migrated blocks).

Given this runs over entire user codebases and can currently produce non‑compiling output, I’d treat fixing/scope‑limiting this function as a blocker before shipping the migration.

To gauge impact, you can scan a real project for errs []error and other errs usages not tied to Fiber v2 client patterns, then run this migration and try go build to see where the rewritten code fails. A small script like the following can help locate problematic sites before and after the migration:

#!/bin/bash
# Before migration: find potential non-client errs usages
rg -nP '\berrs\b' --type=go -C2

# After running the migration, re-run to see how many got renamed to `err`
rg -nP '\berrs\b' --type=go -C2
rg -nP '\berr\b' --type=go -C2 | sed -n '1,40p'

This should highlight how much unrelated code the current patterns are touching.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 397e900 and 7cbb4ec.

📒 Files selected for processing (3)
  • cmd/internal/migrations/v3/client_usage.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_internal_test.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
cmd/internal/migrations/v3/client_usage.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
cmd/internal/migrations/v3/client_usage_test.go (1)
cmd/internal/migrations/v3/client_usage.go (1)
  • MigrateClientUsage (55-76)
⏰ 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). (1)
  • GitHub Check: Build (1.25.x, macos-latest)
🔇 Additional comments (1)
cmd/internal/migrations/v3/client_usage_internal_test.go (1)

11-89: Targeted internal test for rewriteAcquireAgentBlocks looks solid

Nice focused coverage: the test exercises the full AcquireAgent → client.Post transformation (imports, headers, URI, status/body extraction, and JSON decode scaffolding) and normalizes formatting via gofmtSource, which keeps the assertion robust against spacing. No changes needed here.

Comment thread cmd/internal/migrations/v3/client_usage_test.go
Copy link
Copy Markdown

@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 (1)
cmd/internal/migrations/v3/client_usage_test.go (1)

472-488: Remove redundant second err check in generated client.Get pattern

In Test_MigrateClientUsage_RewritesParseBytesFlow's expected output, the second if err != nil check after resp.StatusCode() and resp.Body() is redundant. Per Fiber v3 client documentation, a single error check immediately after client.Get() is sufficient; the response methods are safe to call afterward without re-checking the same err variable.

Update the migration to generate:

resp, err := client.Get("https://httpbin.org/json")
if err != nil {
    panic(err)
}
status := resp.StatusCode()
body := resp.Body()

instead of duplicating the error check.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7cbb4ec and d28f069.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/client_usage.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/internal/migrations/v3/client_usage.go
🧰 Additional context used
🧬 Code graph analysis (1)
cmd/internal/migrations/v3/client_usage_test.go (1)
cmd/internal/migrations/v3/client_usage.go (1)
  • MigrateClientUsage (56-77)
⏰ 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, windows-latest)
  • GitHub Check: Build (1.25.x, macos-13)
🔇 Additional comments (3)
cmd/internal/migrations/v3/client_usage_test.go (3)

165-188: No-change scenario test looks solid

Test_MigrateClientUsage_NoChanges correctly asserts that a simple handler using only fiber.Ctx is left untouched and that the command output buffer stays empty. This is a good guard that the migration is not over-eager.


295-321: AcquireAgent struct rewrite now matches client API types

The expected output for Test_MigrateClientUsage_RewritesAcquireAgentStruct declares err error (not []error) and uses:

  • resp, err := client.Post(...)
  • retCode = resp.StatusCode()
  • retBody = resp.Body()
  • err = resp.JSON(&t) guarded by if err == nil { ... }

This aligns with the client.Post signature and avoids the earlier []error vs error type mismatch, while preserving status/body capture and structured JSON decoding.


627-633: gofmtSource helper is appropriate and keeps assertions stable

Wrapping format.Source in gofmtSource with require.NoError is a clean way to normalize both input and expected snippets, avoiding test fragility due to formatting differences.

Comment thread cmd/internal/migrations/v3/client_usage_test.go
Copy link
Copy Markdown

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

701-729: Consider simplifying import injection logic.

The ensureImport function handles three cases manually (import block, single import, package declaration). While functional, this could be simplified since imports.Process (from golang.org/x/tools/imports) is called afterward in the migration flow (see cmd/internal/helpers.go:53-109).

A simpler approach would be to just insert the import statement and let goimports handle the formatting and deduplication.

Based on past review comments, this could be simplified for better maintainability.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d28f069 and a9f4979.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/client_usage.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
cmd/internal/migrations/v3/client_usage.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
cmd/internal/migrations/v3/client_usage_test.go (1)
cmd/internal/migrations/v3/client_usage.go (1)
  • MigrateClientUsage (58-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). (4)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, windows-latest)
  • GitHub Check: Build (1.25.x, macos-13)
  • GitHub Check: Build (1.25.x, ubuntu-latest)
🔇 Additional comments (12)
cmd/internal/migrations/v3/client_usage_test.go (3)

96-108: LGTM! Error handling pattern correctly defers response access.

The expected output shows the proper pattern: the error is checked first (if err != nil), and only after confirming err == nil are StatusCode() and Body() called. This prevents nil-pointer panics when the client call fails.

Based on past review comments, this pattern has been correctly implemented.


313-339: LGTM! Variable declaration correctly updated to singular error type.

The expected output properly declares err error (line 317) instead of err []error, which matches the v3 client API that returns a single error rather than []error. The migration correctly updates both the declaration and all error handling logic.

Based on past review comments, this type mismatch issue has been resolved.


665-671: LGTM! Helper function provides consistent formatting for test assertions.

The gofmtSource helper ensures both expected and actual code are formatted consistently using go/format, making test comparisons reliable.

cmd/internal/migrations/v3/client_usage.go (9)

29-29: LGTM! Variable declaration pattern correctly handles type conversion.

The clientErrsDeclPattern regex properly matches errs []error declarations, and line 741 in rewriteClientErrorHandling replaces them with err error, ensuring the migrated code uses the correct singular error type.

Based on past review comments, this issue has been resolved.


155-163: LGTM! Brace counting logic correctly handles complex structures.

The implementation counts all occurrences of { and } on each line using strings.Count, which properly handles lines with multiple braces (like } else {). This is more robust than checking for single brace presence.

Based on past review comments, this fragile logic has been strengthened.


101-101: LGTM! Comment handling improves migration resilience.

The logic correctly skips comment lines (strings.HasPrefix(trimmed, "//")) when searching for the Request() call, preventing false negatives when comments appear between the AcquireAgent and Request calls.

Based on past review comments, this robustness issue has been addressed.


218-223: LGTM! Consistent assignment operator usage with proper spacing.

Both status and body assignments correctly use the assignOp variable (which can be := or =) with proper spacing, ensuring the generated code matches the original assignment style.

Based on past review comments, the inconsistent operator issue has been resolved.


37-37: LGTM! Struct assignment pattern uses specific capture groups.

The regex captures status and body variables in separate, explicit groups (([^,]+?) for each), making the pattern more reliable and less prone to parsing errors from formatting variations.

Based on past review comments, this fragile regex has been improved.


304-318: LGTM! Config builder ensures deterministic output.

The function sorts header keys before building the config string, ensuring consistent and deterministic migration output across runs.


494-534: LGTM! Generated code safely guards response access behind error checks.

The replacement builder correctly generates the pattern where status and body are only extracted inside an if err == nil block (line 520), preventing nil-pointer panics when the client call fails.


58-79: LGTM! Migration orchestration follows a logical flow.

The function applies transformations in the correct order:

  1. Rewrite client examples and AcquireAgent blocks (lines 60-61)
  2. Only proceed if changes were made (line 63)
  3. Normalize error handling globally (line 67)
  4. Ensure imports via internal.ChangeFileContent which calls imports.Process

The early return optimization (line 64) avoids unnecessary processing for files without client usage.


740-748: The broad \berrs\b pattern at line 746 is applied only to files containing old fiber client patterns (e.g., status, body, errs := client.Bytes()). The migration runs selectively—only when earlier patterns match and rewrite client code—and no other errs variables exist in the codebase that could be affected. While the pattern is technically broad, it operates in a controlled context with no actual risk of corrupting unrelated code.

Likely an incorrect or invalid review comment.

@ReneWerner87
Copy link
Copy Markdown
Member Author

/gemini review

Copy link
Copy Markdown
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 introduces a comprehensive migration script for updating fiber client usage patterns to the new v3 API. The use of regex-based rewriting is a practical approach for this kind of codemod. The changes are extensive and cover many different usage patterns, including the complex AcquireAgent flow. The addition of thorough tests is excellent and crucial for such a fragile task.

I've found a critical issue with how TLSConfig is migrated, which changes per-request settings to global ones. I've also included some suggestions to improve the robustness and maintainability of the migration script. Please see my detailed comments below.

Comment thread cmd/internal/migrations/v3/client_usage.go Outdated
Comment thread cmd/internal/migrations/v3/client_usage.go
Comment thread cmd/internal/migrations/v3/client_usage.go
Comment thread cmd/internal/migrations/v3/client_usage.go
Copy link
Copy Markdown

@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

♻️ Duplicate comments (2)
cmd/internal/migrations/v3/client_usage.go (2)

701-738: Simplify ensureImport by relying on imports.Process instead of manual rewrites

ensureImport manually rewrites import blocks and single-line imports using regexes and ReplaceAllString, which is relatively complex and can produce multiple import blocks or unusual layouts, especially when there are several single-line imports.

Since ChangeFileContent already runs imports.Process on the final source, you can take a much simpler and safer approach: just inject the needed import after the package line (if not already present) and let goimports handle grouping, sorting, and deduplication.

For example:

 func ensureImport(content, pkg string) string {
-	importLiteral := fmt.Sprintf("%q", pkg)
-	if strings.Contains(content, importLiteral) {
-		return content
-	}
-
-	blockRegex := regexp.MustCompile(`(?m)^import \(([^)]*)\)`) // import block
-	if blockRegex.MatchString(content) {
-		return blockRegex.ReplaceAllStringFunc(content, func(m string) string {
-			return strings.Replace(m, ")", "\t"+importLiteral+"\n)", 1)
-		})
-	}
-
-	singleImport := regexp.MustCompile(`(?m)^import\s+\"([^\"]+)\"`)
-	if matches := singleImport.FindStringSubmatch(content); len(matches) == 2 {
-		existing := matches[1]
-		if existing == pkg {
-			return content
-		}
-		return singleImport.ReplaceAllString(content, fmt.Sprintf("import (\n\t%q\n\t%q\n)", existing, pkg))
-	}
-
-	packageRegex := regexp.MustCompile(`(?m)^package\s+\w+`)
-	if match := packageRegex.FindString(content); match != "" {
-		return strings.Replace(content, match, match+"\n\nimport \""+pkg+"\"", 1)
-	}
-
-	return "import \"" + pkg + "\"\n" + content
+	importLiteral := fmt.Sprintf("%q", pkg)
+	if strings.Contains(content, importLiteral) {
+		return content
+	}
+	packageRegex := regexp.MustCompile(`(?m)^package\s+\w+`)
+	if match := packageRegex.FindString(content); match != "" {
+		return strings.Replace(content, match, match+"\n\nimport "+importLiteral, 1)
+	}
+	// Fallback for malformed files without a package clause.
+	return "import " + importLiteral + "\n" + content
 }

imports.Process will then normalize imports across blocks, so you avoid edge cases while keeping the helper small and easier to reason about.


24-30: Global errserr normalization is still very broad and can break unrelated code

rewriteClientErrorHandling rewrites all occurrences of errs/len(errs)/"errs": errs in a file once any client migration has happened:

  • clientErrsDeclPattern changes every var errs []error to var err error.
  • clientErrIfPattern / clientErrLenPattern / clientErrComparePattern aggressively rewrite len(errs) usages.
  • clientErrVarPattern (\berrs\b) then renames every remaining errs identifier to err.

This has a couple of risks:

  • Any non-Fiber use of errs []error in the same file (e.g. validation error aggregation) will silently become err error with all references renamed, changing behavior or even failing to compile.
  • Expressions like if len(errs) > 1 { ... } will be turned into if err != nil > 1 { ... }, which does not match clientErrComparePattern (it only handles > 0) and leaves an invalid boolean expression in place.
  • Other patterns like panic(errs) or return errs are also rewritten purely by name, regardless of origin.

Given this is an automated migration that can run across whole projects, that blast radius is pretty high.

Consider constraining the normalization more tightly, for example:

  • Prefer clientErrIfPattern for the common if len(errs) > 0 { ... } case instead of the generic clientErrLenPattern.
  • Extend clientErrComparePattern (or add new targeted patterns) to cover the exact shapes you expect from Fiber client usage, and avoid rewriting arbitrary len(errs) arithmetic.
  • Limit clientErrVarPattern/clientErrsDeclPattern to scopes where you know the errs slice came from the old Fiber client (e.g. heuristics around the rewritten fiber.* / AcquireAgent blocks), instead of the entire file.

At minimum, it’s worth scanning the repo for other errs []error usages to ensure you’re not unintentionally mutating unrelated code when this migration runs.

-	updated = clientErrLenPattern.ReplaceAllString(updated, "err != nil")
-	updated = clientErrComparePattern.ReplaceAllString(updated, "err != nil")
-	updated = clientErrVarPattern.ReplaceAllString(updated, "err")
+	// TODO: consider narrowing these rewrites to only known Fiber-client error
+	// handling patterns (or to regions around migrated calls) to avoid touching
+	// unrelated `errs` usage in the same file.
+	updated = clientErrLenPattern.ReplaceAllString(updated, "err != nil")
+	updated = clientErrComparePattern.ReplaceAllString(updated, "err != nil")
+	updated = clientErrVarPattern.ReplaceAllString(updated, "err")
#!/bin/bash
# Quick sanity check for potential non-Fiber `errs` usage that this migration
# might rewrite.

echo "== Declarations of errs []error =="
rg -n '\berrs\s*\[\]error\b' -C3

echo
echo "== len(errs) comparisons that are not > 0 (may become invalid after rewrite) =="
rg -n 'len\(\s*errs\s*\)\s*(?!>\s*0)' -C3

echo
echo "== Files containing both Fiber client usage and errs slice =="
rg -n 'fiber\.(Get|Head|Post|Put|Patch|Delete)\(' -n
rg -n 'fiber\.AcquireAgent\(' -n

Also applies to: 740-748

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

453-527: Consider dropping the redundant second if err != nil in the parse-bytes flow

In Test_MigrateClientUsage_RewritesParseBytesFlow, the expected migrated code includes:

resp, err := client.Get("https://httpbin.org/json")
if err != nil {
    panic(err)
}
status := resp.StatusCode()
body := resp.Body()
if err != nil {
    panic(err)
}

err is not modified between the two checks, so the second if err != nil is redundant and will never fire if the first one didn’t. It makes the generated code a bit noisier for readers.

If preserving two separate error sites from the original (a.Parse and a.Bytes) isn’t important, you could simplify the generator and expected output to a single check:

-    resp, err := client.Get("https://httpbin.org/json")
-    if err != nil {
-        panic(err)
-    }
-    status := resp.StatusCode()
-    body := resp.Body()
-    if err != nil {
-        panic(err)
-    }
+    resp, err := client.Get("https://httpbin.org/json")
+    if err != nil {
+        panic(err)
+    }
+    status := resp.StatusCode()
+    body := resp.Body()

This keeps the behavior but produces slightly cleaner migrated code.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9f4979 and 8735877.

📒 Files selected for processing (2)
  • cmd/internal/migrations/v3/client_usage.go (1 hunks)
  • cmd/internal/migrations/v3/client_usage_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
cmd/internal/migrations/v3/client_usage_test.go (1)
cmd/internal/migrations/v3/client_usage.go (1)
  • MigrateClientUsage (58-79)
cmd/internal/migrations/v3/client_usage.go (1)
cmd/internal/helpers.go (1)
  • ChangeFileContent (54-110)
⏰ 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-13)
  • GitHub Check: Build (1.25.x, macos-latest)
  • GitHub Check: Build (1.25.x, windows-latest)

Comment thread cmd/internal/migrations/v3/client_usage.go
@ReneWerner87 ReneWerner87 merged commit 49022d5 into master Dec 2, 2025
15 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-12-01-13-56-00 branch December 2, 2025 20:46
@ReneWerner87 ReneWerner87 added the ✏️ Feature New feature or request label Dec 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex ✏️ Feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant