Skip to content

Commit 7fbfe8e

Browse files
committed
Don't alias imports if the alias would be ineffective
Fixes stuff like `context "context"` and `http "net/http"`. Signed-off-by: Brad Davidson <[email protected]>
1 parent 2b36238 commit 7fbfe8e

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

v2/generator/import_tracker.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,13 @@ func NewImportTrackerForPackage(local string, typesToAdd ...*types.Type) *namer.
4747
tracker := namer.NewDefaultImportTracker(types.Name{Package: local})
4848
tracker.IsInvalidType = func(*types.Type) bool { return false }
4949
tracker.LocalName = func(name types.Name) string { return goTrackerLocalName(&tracker, local, name) }
50-
tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" }
50+
tracker.PrintImport = func(path, name string) string {
51+
dirs := strings.Split(path, namer.GoSeperator)
52+
if len(dirs) > 0 && name == dirs[len(dirs)-1] {
53+
return "\"" + path + "\""
54+
}
55+
return name + " \"" + path + "\""
56+
}
5157

5258
tracker.AddTypes(typesToAdd...)
5359
return &tracker

v2/generator/import_tracker_test.go

+20-3
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,14 @@ func TestNewImportTracker(t *testing.T) {
3838
{
3939
name: "builtin",
4040
inputTypes: []*types.Type{
41+
{Name: types.Name{Package: "context"}},
4142
{Name: types.Name{Package: "net/http"}},
43+
{Name: types.Name{Package: "x/net/http"}},
4244
},
4345
expectedImports: []string{
44-
`http "net/http"`,
46+
`"context"`,
47+
`"net/http"`,
48+
`nethttp "x/net/http"`,
4549
},
4650
},
4751
{
@@ -51,8 +55,21 @@ func TestNewImportTracker(t *testing.T) {
5155
{Name: types.Name{Package: "foo/bar/pkg1"}},
5256
},
5357
expectedImports: []string{
54-
`pkg1 "foo/bar/pkg1"`,
55-
`pkg2 "foo/bar/pkg2"`,
58+
`"foo/bar/pkg1"`,
59+
`"foo/bar/pkg2"`,
60+
},
61+
},
62+
{
63+
name: "duplicate",
64+
inputTypes: []*types.Type{
65+
{Name: types.Name{Package: "foo/bar/pkg2/v1"}},
66+
{Name: types.Name{Package: "foo/bar/pkg3/v1"}},
67+
{Name: types.Name{Package: "foo/bar/pkg1/v1"}},
68+
},
69+
expectedImports: []string{
70+
`pkg1v1 "foo/bar/pkg1/v1"`,
71+
`"foo/bar/pkg2/v1"`,
72+
`pkg3v1 "foo/bar/pkg3/v1"`,
5673
},
5774
},
5875
{

0 commit comments

Comments
 (0)