-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrepository.go
103 lines (87 loc) · 2.34 KB
/
repository.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
package zconfig
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
"sync"
)
const ProviderDefault = "default"
// A Repository is list of configuration providers and hooks.
type Repository struct {
lock sync.Mutex
providers []Provider
parsers []Parser
}
// Register a new Provider in this repository.
func (r *Repository) AddProviders(providers ...Provider) {
r.lock.Lock()
defer r.lock.Unlock()
r.providers = append(r.providers, providers...)
sort.Slice(r.providers, func(a, b int) bool {
return r.providers[a].Priority() < r.providers[b].Priority()
})
}
// Retrieve a key from the provider, by priority order.
func (r *Repository) Retrieve(key string) (value interface{}, provider string, found bool, err error) {
for _, p := range r.providers {
value, found, err = p.Retrieve(key)
if err != nil {
return nil, p.Name(), false, err
}
if found {
return value, p.Name(), true, nil
}
}
return nil, "", false, nil
}
var ErrNotParseable = errors.New("not parseable")
// Register allow anyone to add a custom parser to the list.
func (r *Repository) AddParsers(parsers ...Parser) {
r.lock.Lock()
defer r.lock.Unlock()
r.parsers = append(r.parsers, parsers...)
}
// Parse the parameter depending on the kind of the field, returning an
// appropriately typed reflect.Value.
func (r *Repository) Parse(raw, res interface{}) (err error) {
for _, p := range r.parsers {
err = p(raw, res)
if err == ErrNotParseable {
continue
}
if err != nil {
return fmt.Errorf("unable to parse %T: %w", res, err)
}
return nil
}
return fmt.Errorf("no parser for type %T", res)
}
func (r *Repository) Hook(ctx context.Context, f *Field) (err error) {
if !f.Configurable {
return nil
}
raw, provider, found, err := r.Retrieve(f.ConfigurationKey)
if err != nil {
return fmt.Errorf("configuring field %s: retrieving key %s: %w", f.Path, f.ConfigurationKey, err)
}
if !found {
def, ok := f.Tags.Lookup(TagDefault)
if !ok {
return fmt.Errorf("configuring field %s: missing key %s", f.Path, f.ConfigurationKey)
}
raw = def
provider = ProviderDefault
}
var val = f.Value
if val.Kind() != reflect.Ptr {
val = val.Addr()
}
err = r.Parse(raw, val.Interface())
if err != nil {
return fmt.Errorf("configuring field %s: parsing value for key %s: %w", f.Path, f.ConfigurationKey, err)
}
f.Provider = provider
return nil
}