11package cmd
22
33import (
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+
5787func init () {
5888 runCmd .AddCommand (policyCmd )
5989
0 commit comments