Skip to content

Commit 31bff9a

Browse files
committed
pkg/rules: add entrypoint for side-loading fs.FS rego files
Signed-off-by: Stephan Renatus <[email protected]>
1 parent d869abe commit 31bff9a

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

pkg/rules/rules.go

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"path/filepath"
1010
"sort"
1111
"sync"
12+
"sync/atomic"
1213

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

54-
return Input{
55+
i := Input{
5556
FileContent: fileContent,
5657
FileNames: filenames,
5758
Modules: modules,
5859
}
60+
61+
if vi := virtualInput.Load(); vi != nil {
62+
return i.Merge(*vi)
63+
}
64+
65+
return i
66+
}
67+
68+
func (i Input) Merge(o Input) Input {
69+
for _, name := range o.FileNames {
70+
i.FileContent[name] = o.FileContent[name]
71+
i.Modules[name] = o.Modules[name]
72+
i.FileNames = append(i.FileNames, name)
73+
}
74+
75+
return i
76+
}
77+
78+
var virtualInput atomic.Pointer[Input] //nolint:gochecknoglobals
79+
80+
func SetVirtualInput(fsys fs.FS) error {
81+
paths := []string{}
82+
83+
if err := fs.WalkDir(fsys, ".", func(p string, _ fs.DirEntry, _ error) error {
84+
if filepath.Ext(p) == ".rego" {
85+
paths = append(paths, filepath.Join("/", p))
86+
}
87+
88+
return nil
89+
}); err != nil {
90+
return fmt.Errorf("walking fs.FS: %w", err)
91+
}
92+
93+
in, err := inputFromPathsFS(fsys, paths)
94+
if err != nil {
95+
return fmt.Errorf("read input from fs.FS: %w", err)
96+
}
97+
98+
virtualInput.Store(&in)
99+
100+
return nil
59101
}
60102

61103
// InputFromPaths creates a new Input from a set of file or directory paths. Note that this function assumes that the

0 commit comments

Comments
 (0)