Add a default-enabled EnvResolver for the env tag.

This commit is contained in:
Alec Thomas
2018-06-12 20:54:29 +10:00
parent e9d88d6528
commit 0fb3de514f
4 changed files with 41 additions and 8 deletions
+16 -2
View File
@@ -62,8 +62,9 @@ func jsonDecodeValue(sep rune, value interface{}) (string, error) {
}
// PerFlagEnvResolver automatically determines environment variables based on the name of each flag, transformed to
// uppercase and underscored, e.g. `my-flag` -> `MY_FLAG` The environment variable key can be overridden with the `env`
// tag.
// uppercase and underscored, e.g. `my-flag` -> `MY_FLAG`.
//
// The environment variable key can be overridden with the `env:"<name>"` tag.
func PerFlagEnvResolver(prefix string) ResolverFunc {
return func(context *Context, parent *Path, flag *Flag) (string, error) {
v, _ := os.LookupEnv(envString(prefix, flag))
@@ -71,6 +72,19 @@ func PerFlagEnvResolver(prefix string) ResolverFunc {
}
}
// EnvResolver resolves flag values using the `env:"<name>"` tag. It ignores flags without this tag.
//
// This resolver is installed by default.
func EnvResolver() ResolverFunc {
return func(context *Context, parent *Path, flag *Flag) (string, error) {
if flag.Tag.Env == "" {
return "", nil
}
v, _ := os.LookupEnv(flag.Tag.Env)
return v, nil
}
}
func envString(prefix string, flag *Flag) string {
if env, ok := flag.Tag.Get("env"); ok {
return env