update takes a prefix string p and *flag.FlagSet. Each flag in the FlagSet is exposed as an upper case environment variable prefixed with p. Any flag that was not explicitly set by a user is updated to the environment variable, if set.
(p string, fs *flag.FlagSet)
| 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 | } |