forked from Nomon/gonfig
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathargv.go
51 lines (44 loc) · 1.2 KB
/
argv.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
package unicon
import (
"flag"
"os"
"strings"
)
// ArgvConfig is the Argv configurable.
type ArgvConfig struct {
Configurable
Prefix string
namespaces []string
}
// NewArgvConfig creates a new ArgvConfig and returns it as a ReadableConfig
func NewArgvConfig(prefix string, namespaces ...string) ReadableConfig {
cfg := &ArgvConfig{
Configurable: NewMemoryConfig(),
Prefix: prefix,
namespaces: nsSlice(namespaces),
}
return cfg
}
// Load loads all the variables from argv to the underlaying Configurable.
// If a Prefix is provided for ArgvConfig then keys are imported with the
// Prefix removed so --test.asd=1 with Prefix 'test.' imports "asd" with
// value of 1
func (ac *ArgvConfig) Load() (err error) {
flagset := flag.NewFlagSet("arguments", flag.ContinueOnError)
flagset.Parse(os.Args)
flagset.VisitAll(func(f *flag.Flag) {
name := f.Name
if ac.Prefix != "" && strings.HasPrefix(f.Name, ac.Prefix) {
name = strings.Replace(name, ac.Prefix, "", 1)
}
var value interface{}
if getter, ok := f.Value.(flag.Getter); ok {
value = getter.Get().(string)
} else {
value = f.Value.String()
}
name = namespaceKey(name, ac.namespaces)
ac.Set(name, value)
})
return nil
}