diff --git a/pkg/rules/rules.go b/pkg/rules/rules.go index 63b1e1e3..321f85b9 100644 --- a/pkg/rules/rules.go +++ b/pkg/rules/rules.go @@ -132,6 +132,17 @@ func InputFromText(fileName, text string) (Input, error) { return NewInput(map[string]string{fileName: text}, map[string]*ast.Module{fileName: mod}), nil } +// InputFromTextWithOptions creates a new Input from raw Rego text while +// respecting the provided options. +func InputFromTextWithOptions(fileName, text string, opts ast.ParserOptions) (Input, error) { + mod, err := ast.ParseModuleWithOpts(fileName, text, opts) + if err != nil { + return Input{}, fmt.Errorf("failed to parse module: %w", err) + } + + return NewInput(map[string]string{fileName: text}, map[string]*ast.Module{fileName: mod}), nil +} + func AllGoRules(conf config.Config) []Rule { return []Rule{ NewOpaFmtRule(conf), diff --git a/pkg/rules/rules_test.go b/pkg/rules/rules_test.go new file mode 100644 index 00000000..f41c9c74 --- /dev/null +++ b/pkg/rules/rules_test.go @@ -0,0 +1,40 @@ +package rules + +import ( + "testing" + + "github.com/open-policy-agent/opa/ast" +) + +func TestInputFromTextWithOptions(t *testing.T) { + t.Parallel() + + testCases := map[string]struct { + Module string + RegoVersion ast.RegoVersion + }{ + "regov1": { + Module: `package test +p if { true }`, + RegoVersion: ast.RegoV1, + }, + "regov0": { + Module: `package test +p { true }`, + RegoVersion: ast.RegoV0, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + t.Parallel() + + _, err := InputFromTextWithOptions("p.rego", tc.Module, ast.ParserOptions{ + RegoVersion: tc.RegoVersion, + }) + if err != nil { + t.Errorf("Expected no error, got %v", err) + } + }) + } +}