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

Skip to content

Conversation

@ljluestc
Copy link
Contributor

Description

This PR addresses issue #4428 where gf gen ctrl -m incorrectly generates duplicate controller methods. This happens when the controller file imports a package that shares the same version suffix as the API (e.g., v2) but uses an alias or is a different library (e.g., excelize "github.com/xuri/excelize/v2").

Problem:
When scanning existing controllers, the generator attempts to identify which methods have already been generated by matching imports against the API version. Previously, this logic was flawed:

  1. It relied on simple string splitting to parse imports, which is brittle.
  2. It did not correctly distinguish between the API package and other packages that might share a similar name or version suffix (like v2).

As a result, the generator would fail to recognize existing API method implementations, assume they were missing, and regenerate them, causing duplication errors.

Solution:

  1. AST-Based Import Parsing: Updated genctrl_ast_parse.go to use Go's AST (go/ast) to robustly parse imports, correctly capturing both the package path and any explicit aliases.
  2. Strict Alias Matching: Updated genctrl_calculate.go to utilize the parsed alias information.
    • If an import has an explicit alias, the generator now strictly compares that alias against the API version name used in the method signature.
    • If the alias does not match, the import is correctly ignored, preventing false positives (e.g., excelize aliasing .../v2 will no longer match API version v2).

Test

Added a reproduction test case Test_Gen_Ctrl_Issue4428 in cmd/gf/internal/cmd/cmd_z_unit_gen_ctrl_issue_4428_test.go:

  1. Initializes a V2 API project.
  2. Generates the initial controller.
  3. Injects a conflicting import (excelize "github.com/xuri/excelize/v2") into the generated controller.
  4. Adds a new API endpoint.
  5. Runs the generator again.
  6. Verifies that no duplicate methods are created for existing endpoints.

Verification:
The test passes, confirming that the generator now correctly handles aliased imports and avoids duplication.

=== RUN   Test_Gen_Ctrl_Issue4428
...
--- PASS: Test_Gen_Ctrl_Issue4428 (0.35s)
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant