-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathflagenv.go
More file actions
56 lines (54 loc) · 1.69 KB
/
flagenv.go
File metadata and controls
56 lines (54 loc) · 1.69 KB
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
// flagenv implements a simple way to expose all your flags as environmental variables.
// Modified from the archived copy at https://github.com/vmware-archive/flagenv/blob/master/flagenv.go
//
// SPDX-License-Identifier: Apache-2.0
//
// Commandline flags have more precedence over environment variables.
// In order to use it just call flagenv.SetFlagsFromEnv from an init function or from your main.
//
// You can call it either before or after your your flag.Parse invocation.
//
// This example will make it possible to set the default of --my_flag also via the MY_PROG_MY_FLAG
// env var:
//
// var myflag = flag.String("my_flag", "", "some flag")
//
// func init() {
// flagenv.SetFlagsFromEnv("MY_PROG", flag.CommandLine)
// }
//
// func main() {
// flags.Parse()
// ...
// }
package main
import (
"flag"
"fmt"
"os"
"strings"
)
// SetFlagsFromEnv sets flag values from environment, e.g. PREFIX_FOO_BAR set -foo_bar.
// It sets only flags that haven't been set explicitly. The defaults are preserved and -help
// will still show the defaults provided in the code.
func SetFlagsFromEnv(prefix string, fs *flag.FlagSet) {
set := map[string]bool{}
fs.Visit(func(f *flag.Flag) {
set[f.Name] = true
})
fs.VisitAll(func(f *flag.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, "_")
if len(cleanPrefix) > 0 {
cleanPrefix += "_"
}
name := fmt.Sprintf("%s%s", cleanPrefix, strings.Replace(strings.ToUpper(f.Name), "-", "_", -1))
if e, ok := os.LookupEnv(name); ok {
_ = f.Value.Set(e)
}
})
}