Skip to content

Commit 62b18e4

Browse files
authored
fix(tools): imports not handling recursion (#298)
Recursive imports (import cycle) is allowed and handled well in Jsonnet, but not by our `tool imports`. This adds that property
1 parent 5bbbed3 commit 62b18e4

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

pkg/jsonnet/imports.go

+23-10
Original file line numberDiff line numberDiff line change
@@ -44,24 +44,29 @@ func TransitiveImports(dir string) ([]string, error) {
4444
return nil, errors.Wrap(err, "creating Jsonnet AST")
4545
}
4646

47-
imports := make([]string, 0)
48-
if err = importRecursive(&imports, vm, node, "main.jsonnet"); err != nil {
47+
imports := make(map[string]bool)
48+
if err = importRecursive(imports, vm, node, "main.jsonnet"); err != nil {
4949
return nil, err
5050
}
5151

52-
uniq := append(uniqueStringSlice(imports), mainFile)
53-
for i := range uniq {
54-
uniq[i], _ = filepath.Rel(rootDir, uniq[i])
52+
paths := make([]string, 0, len(imports)+1)
53+
for k := range imports {
54+
paths = append(paths, k)
5555
}
56-
sort.Strings(uniq)
56+
paths = append(paths, mainFile)
5757

58-
return uniq, nil
58+
for i := range paths {
59+
paths[i], _ = filepath.Rel(rootDir, paths[i])
60+
}
61+
sort.Strings(paths)
62+
63+
return paths, nil
5964
}
6065

6166
// importRecursive takes a Jsonnet VM and recursively imports the AST. Every
6267
// found import is added to the `list` string slice, which will ultimately
6368
// contain all recursive imports
64-
func importRecursive(list *[]string, vm *jsonnet.VM, node ast.Node, currentPath string) error {
69+
func importRecursive(list map[string]bool, vm *jsonnet.VM, node ast.Node, currentPath string) error {
6570
switch node := node.(type) {
6671
// we have an `import`
6772
case *ast.Import:
@@ -73,7 +78,11 @@ func importRecursive(list *[]string, vm *jsonnet.VM, node ast.Node, currentPath
7378
}
7479

7580
abs, _ := filepath.Abs(foundAt)
76-
*list = append(*list, abs)
81+
if list[abs] {
82+
return nil
83+
}
84+
85+
list[abs] = true
7786

7887
if err := importRecursive(list, vm, contents, foundAt); err != nil {
7988
return err
@@ -89,7 +98,11 @@ func importRecursive(list *[]string, vm *jsonnet.VM, node ast.Node, currentPath
8998
}
9099

91100
abs, _ := filepath.Abs(foundAt)
92-
*list = append(*list, abs)
101+
if list[abs] {
102+
return nil
103+
}
104+
105+
list[abs] = true
93106

94107
// neither `import` nor `importstr`, probably object or similar: try children
95108
default:

0 commit comments

Comments
 (0)