-
Notifications
You must be signed in to change notification settings - Fork 0
/
inject.go
223 lines (188 loc) · 4.68 KB
/
inject.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Package inject is the improved version of https://github.com/facebookgo/inject.
//
// Improvements are listed as below:
//
// 1. More intuitive declaration about dependency relations.
// 2. Support constructor.
// 3. Return the initialized dependency graph (retrieve object outside self scope).
//
// The usage example is in the `inject_test.go`, run `go test` and the output should be like as below
// [:~ … /inject] $ go test
// 2017/07/31 22:36:21 Tillage 3 hours
// 2017/07/31 22:36:21 Got rice
// 2017/07/31 22:36:21 Boeing787 Fly from C++ to Go
// 2017/07/31 22:36:21 Tillage 5 hours
// PASS
// ok github.com/browny/inject 0.018s
package inject
import (
"bytes"
"fmt"
"reflect"
"github.com/facebookgo/inject"
)
type iConstruct interface {
Setup() error
}
// Weave sets up dependencies and returns the result graph.
//
// `depMap` is the map describing the dependency relations.
// The key of depMap is the reference to the dependency providing object.
// The value is the list of dependency requiring objects.
func Weave(depMap map[interface{}][]string) (map[reflect.Type]interface{}, error) {
deps := buildObjects(depMap)
return run(deps...)
}
func run(deps ...*inject.Object) (map[reflect.Type]interface{}, error) {
var g inject.Graph
err := g.Provide(deps...)
if err != nil {
return nil, err
}
err = g.Populate()
if err != nil {
return nil, err
}
// constructing
c := newConstruct()
initializedDeps, err := c.populate(g.Objects())
if err != nil {
return nil, err
}
return initializedDeps, nil
}
func newConstruct() *construct {
return &construct{
constructed: make(map[reflect.Type]bool),
initializedDeps: make(map[reflect.Type]interface{}),
}
}
type construct struct {
current interface{}
constructed map[reflect.Type]bool
initializedDeps map[reflect.Type]interface{}
}
func (c *construct) populate(objs []*inject.Object) (map[reflect.Type]interface{}, error) {
objs = dedup(objs)
var errs []error
for _, obj := range objs {
c.current = obj.Value
if err := c.recurConstruct(obj); err != nil {
errs = append(errs, err)
}
}
return c.initializedDeps, combine(errs...)
}
func (c *construct) recurConstruct(obj *inject.Object) error {
// has been constructed
if c.constructed[reflect.TypeOf(obj.Value)] {
return nil
}
// without constructor, look it as constructed
if !withConstructor(obj.Value) {
c.constructed[reflect.TypeOf(obj.Value)] = true
c.initializedDeps[reflect.TypeOf(obj.Value)] = obj.Value
return nil
}
objVal := reflect.ValueOf(obj.Value)
objTyp := reflect.TypeOf(obj.Value)
// make sure all members with `inject` tag have been constructed
for i := 0; i < objVal.Elem().NumField(); i++ {
fieldVal := objVal.Elem().Field(i)
fieldTyp := objTyp.Elem().Field(i)
_, ok := fieldTyp.Tag.Lookup("inject")
if !ok {
continue
}
if fieldVal.Interface() == c.current {
return fmt.Errorf(
"Dep loop: curr[%s], obj[%s]",
reflect.TypeOf(c.current).String(), reflect.TypeOf(obj.Value).String(),
)
}
err := c.recurConstruct(&inject.Object{Value: fieldVal.Interface()})
if err != nil {
return err
}
}
ctor := obj.Value.(iConstruct)
err := ctor.Setup()
if err != nil {
return err
}
c.constructed[reflect.TypeOf(obj.Value)] = true
c.initializedDeps[reflect.TypeOf(obj.Value)] = obj.Value
return nil
}
func buildObjects(depMap map[interface{}][]string) []*inject.Object {
deps := []*inject.Object{}
for value, names := range depMap {
if len(names) == 0 {
deps = append(deps, &inject.Object{
Value: value,
})
}
// named dependencies
for _, name := range names {
deps = append(deps, &inject.Object{
Value: value,
Name: name,
})
}
}
return deps
}
func withConstructor(i interface{}) bool {
_, ok := i.(iConstruct)
if ok {
return true
}
return false
}
// dedup removes duplication
func dedup(objs []*inject.Object) []*inject.Object {
result := []*inject.Object{}
bucket := map[reflect.Type]bool{}
for _, obj := range objs {
objType := reflect.TypeOf(obj.Value)
if bucket[objType] {
continue
}
bucket[objType] = true
result = append(result, obj)
}
return result
}
type multiError struct {
errs []error
}
func (e *multiError) Error() string {
b := bytes.NewBuffer(nil)
for i, err := range e.errs {
if i > 0 {
b.WriteString("; ")
}
b.WriteString(err.Error())
}
return b.String()
}
func combine(errs ...error) error {
if len(errs) == 0 {
return nil
}
nonNilErrs := make([]error, 0, len(errs))
for _, err := range errs {
if err != nil {
nonNilErrs = append(nonNilErrs, err)
}
}
if len(nonNilErrs) == 0 {
return nil
}
if len(nonNilErrs) == 1 {
return nonNilErrs[0]
}
return &multiError{
errs: nonNilErrs,
}
}