-
Notifications
You must be signed in to change notification settings - Fork 0
/
conf.go
92 lines (84 loc) · 2.16 KB
/
conf.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
package conf
import (
"os"
"github.com/nofeaturesonlybugs/conf/parser"
"github.com/nofeaturesonlybugs/errors"
"github.com/nofeaturesonlybugs/set"
)
// Conf is a parsed configuration.
type Conf struct {
parsed parser.Parsed
}
// File returns a Conf type by reading and parsing the given file.
func File(file string) (*Conf, error) {
handle, err := os.Open(file)
if err != nil {
return nil, errors.Go(err)
}
defer handle.Close()
//
parsed, err := parser.DefaultParser.ParseReader(handle)
if err != nil {
return nil, errors.Go(err)
}
//
return &Conf{parsed}, nil
}
// String returns a Conf type by parsing the given string of configuration data.
func String(s string) (*Conf, error) {
parsed, err := parser.DefaultParser.Parse(s)
if err != nil {
return nil, errors.Go(err)
}
//
return &Conf{parsed}, nil
}
// fill populates target either ByTag or ByFieldName as determined by tag == "".
func (me *Conf) fill(target interface{}, tag string) error {
if me == nil {
return errors.NilReceiver()
}
//
value := set.V(target)
//
var fields []set.Field
if tag == "" {
fields = value.Fields()
} else {
fields = value.FieldsByTag(tag)
}
//
m := me.parsed.Map()
globalSection, getter := set.MapGetter(m[""][len(m[""])-1]), set.MapGetter(m)
scalars := map[string]set.Getter{}
for _, field := range fields {
if field.Value.IsScalar || (field.Value.IsSlice && field.Value.ElemTypeInfo.IsScalar) {
if tag == "" {
scalars[field.Field.Name] = globalSection
} else {
scalars[field.TagValue] = globalSection
}
}
}
//
fn := set.GetterFunc(func(name string) interface{} {
if scalarGetter, ok := scalars[name]; ok {
return scalarGetter.Get(name)
}
return getter.Get(name)
})
if tag == "" {
return value.Fill(fn)
}
return value.FillByTag(tag, fn)
}
// Fill places the data from the configuration into the given target which should be
// a pointer to struct.
func (me *Conf) Fill(target interface{}) error {
return me.fill(target, "")
}
// FillByTag places the data from the configuration into the given target which should be
// a pointer to struct.
func (me *Conf) FillByTag(tag string, target interface{}) error {
return me.fill(target, tag)
}