-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcore_keeper.go
More file actions
121 lines (106 loc) · 2.54 KB
/
core_keeper.go
File metadata and controls
121 lines (106 loc) · 2.54 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package gone
import "reflect"
func newKeeper() *keeper {
return &keeper{
coffins: []*coffin{},
nameMap: make(map[string]*coffin),
defaultTypeMap: make(map[reflect.Type]*coffin),
}
}
type keeper struct {
Flag
coffins []*coffin
nameMap map[string]*coffin
defaultTypeMap map[reflect.Type]*coffin
}
func (s *keeper) getAllCoffins() []*coffin {
return s.coffins
}
func (s *keeper) getByName(name string) *coffin {
return s.nameMap[name]
}
func (s *keeper) getByTypeAndPattern(t reflect.Type, pattern string) (coffins []*coffin) {
for _, co := range s.coffins {
if co.onlyForName {
continue
}
if err := co.CoundProvide(t, false); err == nil && isMatch(co.name, pattern) {
coffins = append(coffins, co)
}
}
SortCoffins(coffins)
return coffins
}
func (s *keeper) selectOneCoffin(t reflect.Type, pattern string, warn func()) (depCo *coffin) {
if depCos := s.getByTypeAndPattern(t, pattern); depCos != nil && len(depCos) > 0 {
l := len(depCos)
if l == 1 {
depCo = depCos[0]
} else if l > 1 {
for _, c := range depCos {
if c.isDefault(t) {
depCo = c
break
}
}
if depCo == nil {
if warn != nil {
warn()
}
depCo = depCos[0]
}
}
}
return
}
func (s *keeper) load(goner Goner, options ...Option) error {
if goner == nil {
return NewInnerError("goner cannot be nil - must provide a valid Goner instance", LoadedError)
}
co := newCoffin(goner)
for _, o := range options {
if err := o.Apply(co); err != nil {
return ToError(err)
}
}
if co.name != "" {
if _, ok := s.nameMap[co.name]; ok && !co.forceReplace {
return NewInnerErrorWithParams(LoadedError, "goner with name %q is already loaded - use ForceReplace() option to override", co.name)
} else {
s.nameMap[co.name] = co
}
}
var forceReplaceFind = false
if co.forceReplace && co.name != "" {
var replacedCo *coffin
for i := range s.coffins {
if s.coffins[i].name == co.name {
replacedCo = s.coffins[i]
s.coffins[i] = co
forceReplaceFind = true
break
}
}
for t, typeCo := range s.defaultTypeMap {
if typeCo == replacedCo {
delete(s.defaultTypeMap, t)
}
}
}
if !forceReplaceFind {
s.coffins = append(s.coffins, co)
}
for t := range co.defaultTypeMap {
if _, ok := s.defaultTypeMap[t]; ok {
return NewInnerErrorWithParams(
LoadedError,
"type %q is already registered as default - cannot use IsDefault option when Loading named provider: %q",
GetTypeName(t),
co.Name(),
)
} else {
s.defaultTypeMap[t] = co
}
}
return nil
}