Skip to content

Commit

Permalink
rules: Add InputFromTextWithOptions for go users
Browse files Browse the repository at this point in the history
This creates a helper function that creates an `Input` given a module as
a string in a given version of Rego. This is being added for the
rego-playground primarily.

Signed-off-by: Charlie Egan <charlie@styra.com>
  • Loading branch information
charlieegan3 committed Nov 27, 2024
1 parent f61f52b commit d855fce
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
11 changes: 11 additions & 0 deletions pkg/rules/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
40 changes: 40 additions & 0 deletions pkg/rules/rules_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit d855fce

Please sign in to comment.