Skip to content

Commit

Permalink
fix(tools): imports not handling recursion (#298)
Browse files Browse the repository at this point in the history
Recursive imports (import cycle) is allowed and handled well in Jsonnet,
but not by our `tool imports`. This adds that property
  • Loading branch information
sh0rez authored Jun 18, 2020
1 parent 5bbbed3 commit 62b18e4
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions pkg/jsonnet/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,29 @@ func TransitiveImports(dir string) ([]string, error) {
return nil, errors.Wrap(err, "creating Jsonnet AST")
}

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

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

return uniq, nil
for i := range paths {
paths[i], _ = filepath.Rel(rootDir, paths[i])
}
sort.Strings(paths)

return paths, nil
}

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

abs, _ := filepath.Abs(foundAt)
*list = append(*list, abs)
if list[abs] {
return nil
}

list[abs] = true

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

abs, _ := filepath.Abs(foundAt)
*list = append(*list, abs)
if list[abs] {
return nil
}

list[abs] = true

// neither `import` nor `importstr`, probably object or similar: try children
default:
Expand Down

0 comments on commit 62b18e4

Please sign in to comment.