@@ -18,6 +18,7 @@ package generator
18
18
19
19
import (
20
20
"go/token"
21
+ "path/filepath"
21
22
"strings"
22
23
23
24
"k8s.io/klog/v2"
@@ -45,7 +46,7 @@ import (
45
46
func NewImportTrackerForPackage (local string , typesToAdd ... * types.Type ) * namer.DefaultImportTracker {
46
47
tracker := namer .NewDefaultImportTracker (types.Name {Package : local })
47
48
tracker .IsInvalidType = func (* types.Type ) bool { return false }
48
- tracker .LocalName = func (name types.Name ) string { return goTrackerLocalName (& tracker , name ) }
49
+ tracker .LocalName = func (name types.Name ) string { return goTrackerLocalName (& tracker , local , name ) }
49
50
tracker .PrintImport = func (path , name string ) string { return name + " \" " + path + "\" " }
50
51
51
52
tracker .AddTypes (typesToAdd ... )
@@ -56,14 +57,15 @@ func NewImportTracker(typesToAdd ...*types.Type) *namer.DefaultImportTracker {
56
57
return NewImportTrackerForPackage ("" , typesToAdd ... )
57
58
}
58
59
59
- func goTrackerLocalName (tracker namer.ImportTracker , t types.Name ) string {
60
+ func goTrackerLocalName (tracker namer.ImportTracker , localPkg string , t types.Name ) string {
60
61
path := t .Package
61
62
62
63
// Using backslashes in package names causes gengo to produce Go code which
63
64
// will not compile with the gc compiler. See the comment on GoSeperator.
64
65
if strings .ContainsRune (path , '\\' ) {
65
66
klog .Warningf ("Warning: backslash used in import path '%v', this is unsupported.\n " , path )
66
67
}
68
+ localLeaf := filepath .Base (localPkg )
67
69
68
70
dirs := strings .Split (path , namer .GoSeperator )
69
71
for n := len (dirs ) - 1 ; n >= 0 ; n -- {
@@ -74,8 +76,13 @@ func goTrackerLocalName(tracker namer.ImportTracker, t types.Name) string {
74
76
// packages, but aren't legal go names. So we'll sanitize.
75
77
name = strings .ReplaceAll (name , "." , "" )
76
78
name = strings .ReplaceAll (name , "-" , "" )
77
- if _ , found := tracker .PathOf (name ); found {
78
- // This name collides with some other package
79
+ if _ , found := tracker .PathOf (name ); found || name == localLeaf {
80
+ // This name collides with some other package.
81
+ // Or, this name is tne same name as the local package,
82
+ // which we avoid because it can be confusing. For example,
83
+ // if the local package is v1, we to avoid importing
84
+ // another package using the v1 name, and instead import
85
+ // it with a more qualified name, such as metav1.
79
86
continue
80
87
}
81
88
0 commit comments