Skip to content

Commit a236553

Browse files
committed
fix: ensure conflicting aliases are handled
Signed-off-by: Piaras Hoban <[email protected]>
1 parent 1813a37 commit a236553

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# reproduction for https://github.com/cue-lang/cue/issues/3974
2+
exec cue exp gengotypes
3+
cmp cue_types_main_gen.go expect-gengo
4+
5+
-- cue.mod/module.cue --
6+
module: "mod.test"
7+
language: version: "v0.13.0"
8+
9+
-- pkg/foo/p1/p1.cue --
10+
package p1
11+
12+
#Foo: int
13+
14+
-- pkg/bar/p2/p2.cue --
15+
package p2
16+
17+
#Bar: string
18+
19+
-- f1.cue --
20+
package main
21+
22+
import (
23+
same "mod.test/pkg/foo/p1"
24+
)
25+
26+
#A: {
27+
foo: same.#Foo
28+
}
29+
30+
-- f2.cue --
31+
package main
32+
33+
import (
34+
same "mod.test/pkg/bar/p2"
35+
)
36+
37+
#B: {
38+
bar: same.#Bar
39+
}
40+
41+
-- expect-gengo --
42+
// Code generated by "cue exp gengotypes"; DO NOT EDIT.
43+
44+
package main
45+
46+
import (
47+
same1 "mod.test/pkg/bar/p2"
48+
same "mod.test/pkg/foo/p1"
49+
)
50+
51+
type A struct {
52+
Foo same.Foo `json:"foo"`
53+
}
54+
55+
type B struct {
56+
Bar same1.Bar `json:"bar"`
57+
}

internal/encoding/gotypes/generate.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,9 @@ type generator struct {
231231
// def tracks the generation state for a single CUE definition.
232232
def *generatedDef
233233

234-
// importAliases maps package names to the alias
234+
// importAliases maps package names to a given alias. In the case that there are multiple aliases present for
235+
// same package then we will use the first alias encountered. When the same alias is used for multiple packages
236+
// across different files, then a number will be added to the end of the alias to avoid conflicts.
235237
importAliases map[string]string
236238
}
237239

@@ -797,6 +799,7 @@ func emitDocs(printf func(string, ...any), name string, groups []*ast.CommentGro
797799
// gatherImportAliases collects the aliases from imports across the instance.
798800
func gatherImportAliases(inst *build.Instance) (map[string]string, error) {
799801
fileAliases := make(map[string]string)
802+
trackedAliases := make(map[string]int32)
800803
for _, f := range inst.Files {
801804
for _, s := range f.Imports {
802805
if s.Path == nil || s.Name == nil {
@@ -807,7 +810,11 @@ func gatherImportAliases(inst *build.Instance) (map[string]string, error) {
807810
if err != nil {
808811
return nil, err
809812
}
813+
if count, found := trackedAliases[alias]; found {
814+
alias = fmt.Sprintf("%s%d", alias, count)
815+
}
810816
fileAliases[path] = alias
817+
trackedAliases[alias]++
811818
}
812819
}
813820
return fileAliases, nil

0 commit comments

Comments
 (0)