Skip to content

Commit

Permalink
pkg/rules: add entrypoint for side-loading fs.FS rego files
Browse files Browse the repository at this point in the history
Signed-off-by: Stephan Renatus <[email protected]>
  • Loading branch information
srenatus committed Oct 2, 2024
1 parent d869abe commit 61add84
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion pkg/rules/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"path/filepath"
"sort"
"sync"
"sync/atomic"

"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/loader"
Expand Down Expand Up @@ -51,11 +52,52 @@ func NewInput(fileContent map[string]string, modules map[string]*ast.Module) Inp
filenames := util.Keys(modules)
sort.Strings(filenames)

return Input{
i := Input{
FileContent: fileContent,
FileNames: filenames,
Modules: modules,
}

if vi := virtualInput.Load(); vi != nil {
return i.Merge(*vi)
}

return i
}

func (i Input) Merge(o Input) Input {
for _, name := range o.FileNames {
i.FileContent[name] = o.FileContent[name]
i.Modules[name] = o.Modules[name]
i.FileNames = append(i.FileNames, name)
}

return i
}

var virtualInput atomic.Pointer[Input] //nolint:gochecknoglobals

func SetVirtualInput(fsys fs.FS) error {
paths := []string{}

if err := fs.WalkDir(fsys, ".", func(p string, _ fs.DirEntry, _ error) error {
if filepath.Ext(p) == ".rego" {
paths = append(paths, filepath.Join("/", p))
}

return nil
}); err != nil {
return fmt.Errorf("walking fs.FS: %w", err)
}

in, err := inputFromPathsFS(fsys, paths)
if err != nil {
return fmt.Errorf("read input from fs.FS: %w", err)
}

virtualInput.Store(&in)

return nil
}

// InputFromPaths creates a new Input from a set of file or directory paths. Note that this function assumes that the
Expand Down Expand Up @@ -92,6 +134,7 @@ func inputFromPathsFS(fsys fs.FS, paths []string) (Input, error) {

if err != nil {
errors = append(errors, err)

return
}

Expand Down

0 comments on commit 61add84

Please sign in to comment.