Skip to content

Commit

Permalink
Fix panic when an import is not found (#129)
Browse files Browse the repository at this point in the history
This adds error handling for when a Rego import is not found and returns the
name of the missing import to the user.
  • Loading branch information
jalseth authored Feb 13, 2021
1 parent ade1d2e commit 04cc532
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions internal/rego/rego.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,10 @@ func parseDirectory(directory string) ([]Rego, error) {

var regos []Rego
for _, file := range files {
importPaths := getRecursiveImportPaths(file, files)
importPaths, err := getRecursiveImportPaths(file, files)
if err != nil {
return nil, fmt.Errorf("getRecursiveImportPaths: %w", err)
}
importPaths = dedupe(importPaths)

var dependencies []string
Expand Down Expand Up @@ -377,16 +380,24 @@ func trimString(text string) string {
return text
}

func getRecursiveImportPaths(regoFile *loader.RegoFile, regoFiles map[string]*loader.RegoFile) []string {
func getRecursiveImportPaths(regoFile *loader.RegoFile, regoFiles map[string]*loader.RegoFile) ([]string, error) {
var recursiveImports []string
for i := range regoFile.Parsed.Imports {
imported := regoFiles[regoFile.Parsed.Imports[i].Path.String()]
importPath := regoFile.Parsed.Imports[i].Path.String()
imported := regoFiles[importPath]
if imported == nil {
return nil, fmt.Errorf("import not found: %s", importPath)
}

recursiveImports = append(recursiveImports, imported.Parsed.Package.Path.String())
recursiveImports = append(recursiveImports, getRecursiveImportPaths(imported, regoFiles)...)
remainingImports, err := getRecursiveImportPaths(imported, regoFiles)
if err != nil {
return nil, err
}
recursiveImports = append(recursiveImports, remainingImports...)
}

return recursiveImports
return recursiveImports, nil
}

func dedupe(collection []string) []string {
Expand Down

0 comments on commit 04cc532

Please sign in to comment.