forked from Nomon/gonfig
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpflag.go
54 lines (46 loc) · 1.3 KB
/
pflag.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
package unicon
import (
"flag"
"os"
"strings"
"github.com/spf13/pflag"
)
// PflagConfig can be used to read arguments in the posix flag style
// into the underlaying Configurable
type PflagConfig struct {
Configurable
Prefix string
namespaces []string
}
// NewPflagConfig creates a new PflagConfig and returns it as a ReadableConfig
func NewPflagConfig(prefix string, namespaces ...string) ReadableConfig {
cfg := &PflagConfig{
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 PflagConfig then keys are imported with the
// Prefix removed so --test.asd=1 with Prefix 'test.' imports "asd" with
// value of 1
func (pc *PflagConfig) Load() (err error) {
flagset := pflag.NewFlagSet("arguments", pflag.ContinueOnError)
flagset.Parse(os.Args)
flagset.VisitAll(func(f *pflag.Flag) {
name := f.Name
if pc.Prefix != "" && strings.HasPrefix(f.Name, pc.Prefix) {
name = strings.Replace(name, pc.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, pc.namespaces)
pc.Set(name, value)
})
return nil
}