From a2d61268f2acd9fb1b78dc53f5979052a250b55d Mon Sep 17 00:00:00 2001 From: Brad Davidson Date: Fri, 20 Dec 2024 20:03:36 +0000 Subject: [PATCH] Don't alias imports if the alias would be ineffective Fixes stuff like `context "context"` and `http "net/http"`. Signed-off-by: Brad Davidson --- v2/generator/import_tracker.go | 8 +++++++- v2/generator/import_tracker_test.go | 23 ++++++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/v2/generator/import_tracker.go b/v2/generator/import_tracker.go index 22393e4d..801c9727 100644 --- a/v2/generator/import_tracker.go +++ b/v2/generator/import_tracker.go @@ -47,7 +47,13 @@ func NewImportTrackerForPackage(local string, typesToAdd ...*types.Type) *namer. tracker := namer.NewDefaultImportTracker(types.Name{Package: local}) tracker.IsInvalidType = func(*types.Type) bool { return false } tracker.LocalName = func(name types.Name) string { return goTrackerLocalName(&tracker, local, name) } - tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" } + tracker.PrintImport = func(path, name string) string { + dirs := strings.Split(path, namer.GoSeperator) + if len(dirs) > 0 && name == dirs[len(dirs)-1] { + return "\"" + path + "\"" + } + return name + " \"" + path + "\"" + } tracker.AddTypes(typesToAdd...) return &tracker diff --git a/v2/generator/import_tracker_test.go b/v2/generator/import_tracker_test.go index 56087da8..d69d3ab6 100644 --- a/v2/generator/import_tracker_test.go +++ b/v2/generator/import_tracker_test.go @@ -38,10 +38,14 @@ func TestNewImportTracker(t *testing.T) { { name: "builtin", inputTypes: []*types.Type{ + {Name: types.Name{Package: "context"}}, {Name: types.Name{Package: "net/http"}}, + {Name: types.Name{Package: "x/net/http"}}, }, expectedImports: []string{ - `http "net/http"`, + `"context"`, + `"net/http"`, + `nethttp "x/net/http"`, }, }, { @@ -51,8 +55,21 @@ func TestNewImportTracker(t *testing.T) { {Name: types.Name{Package: "foo/bar/pkg1"}}, }, expectedImports: []string{ - `pkg1 "foo/bar/pkg1"`, - `pkg2 "foo/bar/pkg2"`, + `"foo/bar/pkg1"`, + `"foo/bar/pkg2"`, + }, + }, + { + name: "duplicate", + inputTypes: []*types.Type{ + {Name: types.Name{Package: "foo/bar/pkg2/v1"}}, + {Name: types.Name{Package: "foo/bar/pkg3/v1"}}, + {Name: types.Name{Package: "foo/bar/pkg1/v1"}}, + }, + expectedImports: []string{ + `pkg1v1 "foo/bar/pkg1/v1"`, + `"foo/bar/pkg2/v1"`, + `pkg3v1 "foo/bar/pkg3/v1"`, }, }, {