-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
102 lines (90 loc) · 2.2 KB
/
cli.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"github.com/m-mizutani/goerr"
"github.com/m-mizutani/zlog"
"github.com/urfave/cli/v2"
)
var logger = zlog.New()
const outputStdout = "-"
type config struct {
PolicyFile string
OutputFile string
LogLevel string
}
func Run(args []string) error {
var cfg config
app := &cli.App{
Name: "regolint",
Usage: "Linting Rego file with policy written by Rego",
ArgsUsage: "<rego dir> [<rego dir> [...]]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "policy",
Aliases: []string{"p"},
Usage: "lint policy file/dir. If no policy file, output only parsed rego files",
EnvVars: []string{"REGOLINT_POLICY"},
Destination: &cfg.PolicyFile,
},
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "specify output file. `-` means stdout",
EnvVars: []string{"REGOLINT_OUTPUT"},
Destination: &cfg.OutputFile,
Value: outputStdout,
},
&cli.StringFlag{
Name: "log-level",
Aliases: []string{"l"},
Usage: "Log level [trace|debug|info|warn|error]",
Destination: &cfg.LogLevel,
Value: "info",
},
},
Before: func(c *cli.Context) error {
created, err := zlog.NewWithError(zlog.WithLogLevel(cfg.LogLevel))
if err != nil {
return err
}
logger = created
logger.With("config", cfg).Debug("starting regolint...")
return nil
},
Action: func(c *cli.Context) error {
targets, err := loadDirs(c.Args().Slice()...)
if err != nil {
return err
}
var output io.Writer = os.Stdout
if cfg.OutputFile != outputStdout {
f, err := os.Create(cfg.OutputFile)
if err != nil {
return goerr.Wrap(err)
}
output = f
}
if cfg.PolicyFile != "" {
if err := evalWithFile(cfg.PolicyFile, targets, output); err != nil {
return err
}
} else {
raw, err := json.MarshalIndent(input{Files: targets}, "", " ")
if err != nil {
return goerr.Wrap(err)
}
fmt.Fprint(output, string(raw))
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
logger.Error(err.Error())
logger.Err(err).Debug("Error detail")
return err
}
return nil
}