This repository has been archived by the owner on Jun 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapply.go
115 lines (100 loc) · 2.49 KB
/
apply.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
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"os"
"strings"
"github.com/b4b4r07/stein/lint"
"github.com/fatih/color"
"github.com/hashicorp/hcl2/hcl"
)
// ApplyCommand is one of the subcommands
type ApplyCommand struct {
CLI
Option ApplyOption
runningFile lint.File
}
// ApplyOption is the options for ApplyCommand
type ApplyOption struct {
PolicyPath string
}
func (c *ApplyCommand) flagSet() *flag.FlagSet {
flags := flag.NewFlagSet("apply", flag.ExitOnError)
flags.StringVar(&c.Option.PolicyPath, "policy", "", "path to the policy files or the directory where policy files are located")
flags.VisitAll(func(f *flag.Flag) {
if s := os.Getenv(strings.ToUpper(envEnvPrefix + f.Name)); s != "" {
f.Value.Set(s)
}
})
return flags
}
// Run run apply command
func (c *ApplyCommand) Run(args []string) int {
flags := c.flagSet()
if err := flags.Parse(args); err != nil {
return c.exit(err)
}
args = flags.Args()
if len(args) == 0 {
return c.exit(errors.New("No config files given as arguments"))
}
linter, err := lint.NewLinter(args, strings.Split(c.Option.PolicyPath, ",")...)
if err != nil {
return c.exit(err)
}
var results []lint.Result
for _, file := range linter.Files() {
c.runningFile = file
result, err := linter.Run(file)
if err != nil {
return c.exit(err)
}
results = append(results, result)
}
for _, result := range results {
linter.Print(result)
}
linter.PrintSummary(results...)
return c.exit(linter.Status(results...))
}
// Synopsis returns synopsis
func (c *ApplyCommand) Synopsis() string {
return "Applies a policy to arbitrary config files."
}
// Help returns help message
func (c *ApplyCommand) Help() string {
var b bytes.Buffer
flags := c.flagSet()
flags.SetOutput(&b)
flags.PrintDefaults()
return fmt.Sprintf(
"Usage of %s:\n %s\n\nOptions:\n%s", flags.Name(), c.Synopsis(), b.String(),
)
}
// exit overwides CLI.exit
func (c *ApplyCommand) exit(msg interface{}) int {
wr := hcl.NewDiagnosticTextWriter(
c.Stderr, // writer to send messages to
c.runningFile.Policy.Files, // the parser's file cache, for source snippets
100, // wrapping width
true, // generate colored/highlighted output
)
switch m := msg.(type) {
case error:
// TODO
color.New(color.Underline).Fprintln(c.Stderr, c.runningFile.Path)
switch diags := m.(type) {
case hcl.Diagnostics:
if len(diags) == 0 {
return 1
}
wr.WriteDiagnostic(diags[0])
return 1
}
case lint.Status:
return int(m)
}
return c.CLI.exit(msg)
}