-
Notifications
You must be signed in to change notification settings - Fork 1
/
env.go
46 lines (39 loc) · 1003 Bytes
/
env.go
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
package king
import (
"os"
"strings"
"github.com/alecthomas/kong"
)
var ignoredFlagsNames = map[string]bool{
"help": true,
"env-help": true,
}
// EnvResolver returns a Resolver that retrieves values from environment variables.
//
// Hyphens in flag names are replaced with underscores.
// Flag names are prefixed with app name and converted to uppercase.
//
// Usage:
// ctx := kong.Parse(&cli,
// kong.Resolvers(pfkong.EnvResolver()),
// )
// }
func EnvResolver() kong.Resolver {
var f kong.ResolverFunc = func(context *kong.Context, parent *kong.Path, flag *kong.Flag) (interface{}, error) {
if ok := ignoredFlagsNames[flag.Name]; ok {
return nil, nil
}
raw, ok := os.LookupEnv(toEnvVarName(context.Model.Name, flag.Value))
if !ok {
return nil, nil
}
return raw, nil
}
return f
}
func toEnvVarName(prefix string, value *kong.Value) string {
if prefix != "" {
prefix += "_"
}
return strings.ToUpper(prefix + strings.ReplaceAll(value.Name, "-", "_"))
}