Skip to content

Commit f105475

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 f105475

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

v2/generator/import_tracker.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ limitations under the License.
1717
package generator
1818

1919
import (
20+
"fmt"
2021
"go/token"
2122
"path/filepath"
2223
"strings"
@@ -47,7 +48,14 @@ func NewImportTrackerForPackage(local string, typesToAdd ...*types.Type) *namer.
4748
tracker := namer.NewDefaultImportTracker(types.Name{Package: local})
4849
tracker.IsInvalidType = func(*types.Type) bool { return false }
4950
tracker.LocalName = func(name types.Name) string { return goTrackerLocalName(&tracker, local, name) }
50-
tracker.PrintImport = func(path, name string) string { return name + " \"" + path + "\"" }
51+
tracker.PrintImport = func(path, name string) string {
52+
fmt.Printf("%s imported as %s\n", path, name)
53+
dirs := strings.Split(path, namer.GoSeperator)
54+
if len(dirs) > 0 && name == dirs[len(dirs)-1] {
55+
return "\"" + path + "\""
56+
}
57+
return name + " \"" + path + "\""
58+
}
5159

5260
tracker.AddTypes(typesToAdd...)
5361
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)