2020-02-10 12:26:18 +01:00
|
|
|
package envflag
|
|
|
|
|
|
|
|
import (
|
|
|
|
"flag"
|
2020-02-10 15:08:04 +01:00
|
|
|
"log"
|
2020-02-10 12:26:18 +01:00
|
|
|
"os"
|
2020-02-24 20:14:22 +01:00
|
|
|
"strings"
|
2020-02-10 12:26:18 +01:00
|
|
|
)
|
|
|
|
|
2020-02-10 14:58:30 +01:00
|
|
|
var enable = flag.Bool("envflag.enable", false, "Whether to enable reading flags from environment variables additionally to command line. "+
|
2020-02-27 20:47:49 +01:00
|
|
|
"Command line flag values have priority over values from environment vars. "+
|
2020-02-10 14:58:30 +01:00
|
|
|
"Flags are read only from command line if this flag isn't set")
|
|
|
|
|
2020-02-10 12:26:18 +01:00
|
|
|
// Parse parses environment vars and command-line flags.
|
|
|
|
//
|
|
|
|
// Flags set via command-line override flags set via environment vars.
|
|
|
|
//
|
|
|
|
// This function must be called instead of flag.Parse() before using any flags in the program.
|
|
|
|
func Parse() {
|
|
|
|
flag.Parse()
|
2020-02-10 14:58:30 +01:00
|
|
|
if !*enable {
|
|
|
|
return
|
|
|
|
}
|
2020-02-10 12:26:18 +01:00
|
|
|
|
|
|
|
// Remember explicitly set command-line flags.
|
|
|
|
flagsSet := make(map[string]bool)
|
|
|
|
flag.Visit(func(f *flag.Flag) {
|
|
|
|
flagsSet[f.Name] = true
|
|
|
|
})
|
|
|
|
|
|
|
|
// Obtain the remaining flag values from environment vars.
|
|
|
|
flag.VisitAll(func(f *flag.Flag) {
|
|
|
|
if flagsSet[f.Name] {
|
|
|
|
// The flag is explicitly set via command-line.
|
|
|
|
return
|
|
|
|
}
|
2020-02-10 14:58:30 +01:00
|
|
|
// Get flag value from environment var.
|
2020-02-24 20:14:22 +01:00
|
|
|
fname := getEnvFlagName(f.Name)
|
|
|
|
if v, ok := os.LookupEnv(fname); ok {
|
2020-02-10 15:08:04 +01:00
|
|
|
if err := f.Value.Set(v); err != nil {
|
|
|
|
// Do not use lib/logger here, since it is uninitialized yet.
|
2020-02-24 20:14:22 +01:00
|
|
|
log.Fatalf("cannot set flag %s to %q, which is read from environment variable %q: %s", f.Name, v, fname, err)
|
2020-02-10 15:08:04 +01:00
|
|
|
}
|
2020-02-10 12:26:18 +01:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2020-02-24 20:14:22 +01:00
|
|
|
|
|
|
|
func getEnvFlagName(s string) string {
|
|
|
|
// Substitute dots with underscores, since env var names cannot contain dots.
|
|
|
|
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/311#issuecomment-586354129 for details.
|
|
|
|
return strings.ReplaceAll(s, ".", "_")
|
|
|
|
}
|