Skip to content

Commit

Permalink
feat: Recursively search directories for Rego files when compiling po…
Browse files Browse the repository at this point in the history
…licies
  • Loading branch information
Blokje5 committed Sep 8, 2019
1 parent 9ef20ef commit 0f2f6b0
Showing 1 changed file with 22 additions and 20 deletions.
42 changes: 22 additions & 20 deletions pkg/commands/test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,40 +281,25 @@ func runQuery(ctx context.Context, query string, input interface{}, compiler *as
}

func buildCompiler(path string) (*ast.Compiler, error) {
info, err := os.Stat(path)
files, err := recursivelySearchDirForRegoFiles(path)
if err != nil {
return nil, err
}
var files []os.FileInfo
var dirPath string
if info.IsDir() {
files, err = ioutil.ReadDir(path)
if err != nil {
return nil, err
}
dirPath = path
} else {
files = []os.FileInfo{info}
dirPath = filepath.Dir(path)
}

modules := map[string]*ast.Module{}

for _, file := range files {
if !strings.HasSuffix(file.Name(), ".rego") {
continue
}

out, err := ioutil.ReadFile(dirPath + "/" + file.Name())
out, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}

parsed, err := ast.ParseModule(file.Name(), string(out[:]))
name := filepath.Base(file)
parsed, err := ast.ParseModule(name, string(out[:]))
if err != nil {
return nil, err
}
modules[file.Name()] = parsed
modules[name] = parsed
}

compiler := ast.NewCompiler()
Expand All @@ -326,3 +311,20 @@ func buildCompiler(path string) (*ast.Compiler, error) {

return compiler, nil
}

func recursivelySearchDirForRegoFiles(path string) ([]string, error) {
var filepaths []string
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

if !info.IsDir() && strings.HasSuffix(info.Name(), ".rego"){
filepaths = append(filepaths, path)
}

return nil
})

return filepaths, err
}

0 comments on commit 0f2f6b0

Please sign in to comment.