-
Notifications
You must be signed in to change notification settings - Fork 1
/
type_struct.go
106 lines (91 loc) · 2.06 KB
/
type_struct.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
96
97
98
99
100
101
102
103
104
105
106
package envconf
import (
"errors"
"reflect"
"github.com/antonmashko/envconf/external"
)
type structType struct {
*configField
sname string
v reflect.Value
ext external.ExternalSource
hasValue bool
fields []field
}
func newParentStructType(data interface{}, parser *EnvConf) (*structType, error) {
v := reflect.ValueOf(data)
for v.Kind() == reflect.Ptr {
// check on nil
if v.IsNil() {
return nil, ErrNilData
}
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, errors.New("invalid type")
}
s := newStructType(v, newConfigField(nil, reflect.StructField{}, parser))
return s, nil
}
func newStructType(val reflect.Value, f *configField) *structType {
sname := f.Tag.Get("envconf")
return &structType{
sname: sname,
configField: f,
v: val,
ext: external.NilContainer{},
fields: make([]field, val.NumField()),
}
}
func (s *structType) name() string {
if s.sname != "" {
return s.sname
}
return s.Name
}
func (s *structType) isSet() bool {
return s.hasValue
}
func (s *structType) externalSource() external.ExternalSource {
return s.ext
}
func (s *structType) init() error {
s.fields = make([]field, s.v.NumField())
rt := s.v.Type()
for i := 0; i < s.v.NumField(); i++ {
rfield := s.v.Field(i)
f := createFieldFromValue(rfield, newConfigField(s, rt.Field(i), s.parser))
if err := f.init(); err != nil {
return err
}
s.parser.fieldInitialized(f)
s.fields[i] = f
}
return nil
}
func (s *structType) define() error {
if s.parentField != nil {
s.ext = external.AsExternalSource(s.Name, s.parentField.externalSource())
}
for _, f := range s.fields {
err := f.define()
if err != nil {
s.parser.fieldNotDefined(f, err)
if !errors.Is(err, ErrConfigurationNotFound) {
return err
}
if rf, ok := f.(requiredField); ok && rf.IsRequired() {
return &Error{
Message: "failed to define field",
Inner: err,
FieldName: fullname(f, fieldNameDelim),
}
}
}
if f.isSet() {
s.hasValue = true
s.parser.fieldDefined(f)
}
}
return nil
}