forked from synthesio/zconfig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.go
95 lines (76 loc) · 2.47 KB
/
provider.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package zconfig
import (
"os"
"strings"
)
// A Provider that implements the repository.Provider interface.
type ArgsProvider struct {
Args map[string]string
}
// NewArgsProvider lookup keys based on the command-line string.
func NewArgsProvider() (p *ArgsProvider) {
p = new(ArgsProvider)
// Initialize the flags map.
p.Args = make(map[string]string, len(os.Args))
// For each argument, check if it starts with two dashes. If it does,
// trim it, split around the first equal sign and set the flag value.
// If there is no equal sign, and the next argument starts with a
// double-dash, the flag is added without value, which allows to
// differentiate between an empty and a non-existing flag.
for i := 0; i < len(os.Args); i++ {
arg := os.Args[i]
if !strings.HasPrefix(arg, "--") {
continue
}
arg = strings.TrimPrefix(arg, "--")
parts := strings.SplitN(arg, "=", 2)
if len(parts) == 1 && i+1 < len(os.Args) && !strings.HasPrefix(os.Args[i+1], "--") {
parts = append(parts, os.Args[i+1])
i += 1
}
parts = append(parts, "") // Avoid out-of-bound errors.
p.Args[parts[0]] = parts[1]
}
return p
}
// Retrieve will return the value from the parsed command-line arguments.
// Arguments are parsed the first time the method is called. Arguments are
// expected to be in the form `--key=value` exclusively (for now).
func (p *ArgsProvider) Retrieve(key string) (value interface{}, found bool, err error) {
value, found = p.Args[key]
return value, found, nil
}
// Name of the provider.
func (ArgsProvider) Name() string {
return "args"
}
// Priority of the provider.
func (ArgsProvider) Priority() int {
return 1
}
// A Provider that implements the repository.Provider interface.
type EnvProvider struct{}
// NewEnvProvider returns a provider that will lookup keys in the environment
// variables.
func NewEnvProvider() (p EnvProvider) {
return p
}
// Retrieve will return the value from the parsed environment variables.
// Variables are parsed the first time the method is called.
func (p EnvProvider) Retrieve(key string) (value interface{}, found bool, err error) {
value, found = os.LookupEnv(p.FormatKey(key))
return value, found, nil
}
// Name of the provider.
func (EnvProvider) Name() string {
return "env"
}
// Priority of the provider.
func (EnvProvider) Priority() int {
return 2
}
func (EnvProvider) FormatKey(key string) (env string) {
env = strings.ToUpper(key)
env = strings.Replace(env, ".", "_", -1)
return strings.Replace(env, "-", "_", -1)
}