forked from open-policy-agent/opa
/
parse.go
74 lines (62 loc) · 1.5 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2018 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package cmd
import (
"encoding/json"
"fmt"
"os"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/loader"
"github.com/open-policy-agent/opa/util"
"github.com/spf13/cobra"
)
const (
parseFormatPretty = "pretty"
parseFormatJSON = "json"
)
var parseParams = struct {
format *util.EnumFlag
}{
format: util.NewEnumFlag(parseFormatPretty, []string{parseFormatPretty, parseFormatJSON}),
}
var parseCommand = &cobra.Command{
Use: "parse <path>",
Short: "Parse Rego source file",
Long: `Parse Rego source file and print AST.`,
PreRunE: func(Cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return fmt.Errorf("no source file specified")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
os.Exit(parse(args))
},
}
func parse(args []string) int {
if len(args) == 0 {
return 0
}
result, err := loader.Rego(args[0])
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
switch parseParams.format.String() {
case parseFormatJSON:
bs, err := json.MarshalIndent(result.Parsed, "", " ")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
fmt.Println(string(bs))
default:
ast.Pretty(os.Stdout, result.Parsed)
}
return 0
}
func init() {
parseCommand.Flags().VarP(parseParams.format, "format", "f", "set output format")
RootCommand.AddCommand(parseCommand)
}