/
root.go
97 lines (83 loc) · 2.61 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
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
//
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package options
import (
"fmt"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
const EnvPrefix = "COSIGN"
// RootOptions define flags and options for the root cosign cli.
type RootOptions struct {
OutputFile string
Verbose bool
Timeout time.Duration
}
// DefaultTimeout specifies the default timeout for commands.
const DefaultTimeout = 3 * time.Minute
var _ Interface = (*RootOptions)(nil)
// AddFlags implements Interface
func (o *RootOptions) AddFlags(cmd *cobra.Command) {
cmd.PersistentFlags().StringVar(&o.OutputFile, "output-file", "",
"log output to a file")
_ = cmd.Flags().SetAnnotation("output-file", cobra.BashCompFilenameExt, []string{})
cmd.PersistentFlags().BoolVarP(&o.Verbose, "verbose", "d", false,
"log debug output")
cmd.PersistentFlags().DurationVarP(&o.Timeout, "timeout", "t", DefaultTimeout,
"timeout for commands")
}
func BindViper(cmd *cobra.Command, args []string) {
callPersistentPreRun(cmd, args)
v := viper.New()
v.SetEnvPrefix(EnvPrefix)
v.AutomaticEnv()
bindFlags(cmd, v)
}
// callPersistentPreRun calls parent commands. PersistentPreRun
// does not call parents PersistentPreRun functions
func callPersistentPreRun(cmd *cobra.Command, args []string) {
if parent := cmd.Parent(); parent != nil {
if parent.PersistentPreRun != nil {
parent.PersistentPreRun(parent, args)
}
if parent.PersistentPreRunE != nil {
err := parent.PersistentPreRunE(parent, args)
if err != nil {
cmd.PrintErrln("Error:", err.Error())
os.Exit(1)
}
}
callPersistentPreRun(parent, args)
}
}
func bindFlags(cmd *cobra.Command, v *viper.Viper) {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if strings.Contains(f.Name, "-") {
_ = v.BindEnv(f.Name, flagToEnvVar(f.Name))
}
if !f.Changed && v.IsSet((f.Name)) {
val := v.Get(f.Name)
_ = cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val))
}
})
}
func flagToEnvVar(f string) string {
f = strings.ToUpper(f)
return fmt.Sprintf("%s_%s", EnvPrefix, strings.ReplaceAll(f, "-", "_"))
}