Skip to content

Commit f270d32

Browse files
authored
Merge pull request #44 from OpsLevel/eo/rego-read-file
Adding function to read files in policies
2 parents f0dd715 + f25970e commit f270d32

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
kind: Feature
2+
body: Add ability to read file contents with Rego
3+
time: 2022-08-03T14:05:02.946375-05:00

src/cmd/policy.go

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
package cmd
22

33
import (
4+
"bufio"
45
"context"
56
"encoding/json"
67
"fmt"
8+
"github.com/open-policy-agent/opa/ast"
79
"github.com/open-policy-agent/opa/rego"
8-
"github.com/spf13/cobra"
10+
"github.com/open-policy-agent/opa/types"
11+
"github.com/rs/zerolog/log"
12+
cobra "github.com/spf13/cobra"
913
"io/ioutil"
1014
"os"
1115
"path/filepath"
@@ -43,6 +47,12 @@ opslevel run policy -f policy.rego | jq
4347
rego.Module("test.rego",
4448
string(policy),
4549
),
50+
rego.Function1(
51+
&rego.Function{
52+
Name: "opslevel.read_file",
53+
Decl: types.NewFunction(types.Args(types.S), types.S),
54+
},
55+
RegoFuncReadFile),
4656
rego.Input(input),
4757
)
4858
rs, err := rego.Eval(context.Background())
@@ -54,6 +64,26 @@ opslevel run policy -f policy.rego | jq
5464
},
5565
}
5666

67+
func RegoFuncReadFile(ctx rego.BuiltinContext, a *ast.Term) (*ast.Term, error) {
68+
if str, ok := a.Value.(ast.String); ok {
69+
if _, err := os.Stat(string(str)); err != nil {
70+
log.Warn().Msgf("%s", err)
71+
} else {
72+
file, err := os.Open(string(str))
73+
defer file.Close()
74+
cobra.CheckErr(err)
75+
76+
var lines []*ast.Term
77+
scanner := bufio.NewScanner(file)
78+
for scanner.Scan() {
79+
lines = append(lines, ast.StringTerm(scanner.Text()))
80+
}
81+
return ast.ArrayTerm(lines...), nil
82+
}
83+
}
84+
return nil, nil
85+
}
86+
5787
func init() {
5888
runCmd.AddCommand(policyCmd)
5989

0 commit comments

Comments
 (0)