|
| 1 | +// Package envy automatically exposes environment |
| 2 | +// variables for all of your flags. |
| 3 | +package envy |
| 4 | + |
| 5 | +import ( |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +// Parse takes a prefix string and exposes environment variables |
| 13 | +// for all flags in the default FlagSet (flag.CommandLine) in the |
| 14 | +// form of PREFIX_FLAGNAME. |
| 15 | +func Parse(p string) { |
| 16 | + update(p, flag.CommandLine) |
| 17 | +} |
| 18 | + |
| 19 | +// update takes a prefix string p and *flag.FlagSet. Each flag |
| 20 | +// in the FlagSet is exposed as an upper case environment variable |
| 21 | +// prefixed with p. Any flag that was not explicitly set by a user |
| 22 | +// is updated to the environment variable, if set. |
| 23 | +func update(p string, fs *flag.FlagSet) { |
| 24 | + // Build a map of explicitly set flags. |
| 25 | + set := map[string]interface{}{} |
| 26 | + fs.Visit(func(f *flag.Flag) { |
| 27 | + set[f.Name] = nil |
| 28 | + }) |
| 29 | + |
| 30 | + fs.VisitAll(func(f *flag.Flag) { |
| 31 | + // Create an env var name |
| 32 | + // based on the supplied prefix. |
| 33 | + envVar := fmt.Sprintf("%s_%s", p, strings.ToUpper(f.Name)) |
| 34 | + envVar = strings.Replace(envVar, "-", "_", -1) |
| 35 | + |
| 36 | + // Update the Flag.Value if the |
| 37 | + // env var is non "". |
| 38 | + if val := os.Getenv(envVar); val != "" { |
| 39 | + // Update the value if it hasn't |
| 40 | + // already been set. |
| 41 | + if _, defined := set[f.Name]; !defined { |
| 42 | + fs.Set(f.Name, val) |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + // Append the env var to the |
| 47 | + // Flag.Usage field. |
| 48 | + f.Usage = fmt.Sprintf("%s [%s]", f.Usage, envVar) |
| 49 | + }) |
| 50 | +} |
0 commit comments