-
Notifications
You must be signed in to change notification settings - Fork 2
/
multi_sourcer.go
99 lines (77 loc) · 1.85 KB
/
multi_sourcer.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
package config
import (
"sort"
)
type multiSourcer struct {
sourcers []Sourcer
tags []string
}
var _ Sourcer = &multiSourcer{}
// NewMultiSourcer creates a sourcer that reads form each sourcer. The last value
// found is returned - sourcers should be provided from low priority to high priority.
func NewMultiSourcer(sourcers ...Sourcer) Sourcer {
return &multiSourcer{sourcers: sourcers}
}
func (s *multiSourcer) Init() error {
tagSet := map[string]struct{}{}
for _, sourcer := range s.sourcers {
if err := sourcer.Init(); err != nil {
return err
}
for _, tag := range sourcer.Tags() {
tagSet[tag] = struct{}{}
}
}
tags := []string{}
for tag := range tagSet {
tags = append(tags, tag)
}
sort.Strings(tags)
s.tags = tags
return nil
}
func (s *multiSourcer) Tags() []string {
return s.tags
}
func (s *multiSourcer) Get(values []string) (string, SourcerFlag, error) {
correlation := map[string]string{}
for i, value := range values {
correlation[s.tags[i]] = value
}
skip := true
for i := len(s.sourcers) - 1; i >= 0; i-- {
sourcer := s.sourcers[i]
sourcerValues := []string{}
for _, tag := range sourcer.Tags() {
sourcerValues = append(sourcerValues, correlation[tag])
}
val, flag, err := sourcer.Get(sourcerValues)
if err != nil {
return "", FlagMissing, err
}
if flag == FlagFound {
return val, FlagFound, nil
}
skip = skip && flag == FlagSkip
}
if skip {
return "", FlagSkip, nil
}
return "", FlagMissing, nil
}
func (s *multiSourcer) Assets() []string {
assets := []string{}
for _, sourcer := range s.sourcers {
assets = append(assets, sourcer.Assets()...)
}
return assets
}
func (s *multiSourcer) Dump() map[string]string {
values := map[string]string{}
for i := len(s.sourcers) - 1; i >= 0; i-- {
for k, v := range s.sourcers[i].Dump() {
values[k] = v
}
}
return values
}