-
Notifications
You must be signed in to change notification settings - Fork 591
/
env.go
39 lines (31 loc) · 948 Bytes
/
env.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
package rootcmd
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const envKeyPrefix = "CONTROLLER_"
// bindEnvVars, for each flag defined on `cmd` (local or parent persistent), looks up the corresponding environment
// variable and (if the flag is unset) takes that environment variable value as the flag value.
func bindEnvVars(cmd *cobra.Command, _ []string) (err error) {
var envKey string
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("environment binding failed for variable %s: %v", envKey, r)
}
}()
cmd.Flags().VisitAll(func(f *pflag.Flag) {
envKey = fmt.Sprintf("%s%s", envKeyPrefix, strings.ToUpper(strings.ReplaceAll(f.Name, "-", "_")))
if f.Changed {
return // flags take precedence over environment variables
}
if envValue, envSet := os.LookupEnv(envKey); envSet {
if err := f.Value.Set(envValue); err != nil {
panic(err)
}
}
})
return
}