-
Notifications
You must be signed in to change notification settings - Fork 24
/
root.go
54 lines (47 loc) · 1.38 KB
/
root.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
package cmd
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "preflight",
Short: "Kubernetes cluster configuration checker 🚀",
Long: `Preflight is a tool to automatically perform Kubernetes cluster
configuration checks using Open Policy Agent (OPA).
Preflight checks are bundled into Packages`,
}
func init() {
for _, command := range rootCmd.Commands() {
setFlagsFromEnv("PREFLIGHT_", command.PersistentFlags())
}
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func setFlagsFromEnv(prefix string, fs *pflag.FlagSet) {
set := map[string]bool{}
fs.Visit(func(f *pflag.Flag) {
set[f.Name] = true
})
fs.VisitAll(func(f *pflag.Flag) {
// ignore flags set from the commandline
if set[f.Name] {
return
}
// remove trailing _ to reduce common errors with the prefix, i.e. people setting it to MY_PROG_
cleanPrefix := strings.TrimSuffix(prefix, "_")
name := fmt.Sprintf("%s_%s", cleanPrefix, strings.Replace(strings.ToUpper(f.Name), "-", "_", -1))
if e, ok := os.LookupEnv(name); ok {
_ = f.Value.Set(e)
}
})
}