-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathglue.go
332 lines (272 loc) · 7.16 KB
/
glue.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright 2018 Sergey Novichkov. All rights reserved.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
package glue
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"github.com/gozix/di"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
//go:generate mockery --case=underscore --output=mock --outpkg=mock --name=Bundle|BundleDependsOn
type (
// App interface.
App interface {
Execute() error
}
// Option interface.
Option interface {
apply(kernel *app) error
}
// Bundle is an node interface.
Bundle interface {
Name() string
Build(builder di.Builder) error
}
// BundleDependsOn is an node with dependencies interface.
BundleDependsOn interface {
Bundle
DependsOn() []string
}
// PreRunner is a persistent prerunner interface.
PreRunner interface {
Run(ctx context.Context) error
}
// PreRunnerFunc is syntax sugar for usage PreRunner.
PreRunnerFunc func(ctx context.Context) error
// app is implementation of App.
app struct {
ctx context.Context
mux sync.Mutex
bundles map[string]Bundle
builder di.Builder
}
// optionFunc wraps a func, so it satisfies the Option interface.
optionFunc func(kernel *app) error
)
var (
// ErrNilContext is error triggered when detected nil context in option value.
ErrNilContext = errors.New("nil context")
_ PreRunner = (*PreRunnerFunc)(nil)
)
// Context option.
func Context(ctx context.Context) Option {
return optionFunc(func(a *app) error {
if ctx == nil {
return ErrNilContext
}
a.ctx = ctx
return nil
})
}
// Bundles option.
func Bundles(bundles ...Bundle) Option {
return optionFunc(func(a *app) error {
for _, bundle := range bundles {
if _, ok := a.bundles[bundle.Name()]; ok {
return fmt.Errorf(`trying to register two bundles with the same name "%s"`, bundle.Name())
}
a.bundles[bundle.Name()] = bundle
}
return nil
})
}
// Version option.
func Version(version string) Option {
return optionFunc(func(a *app) error {
a.withValue("app.version", version)
return nil
})
}
// NewApp is app constructor.
func NewApp(options ...Option) (_ App, err error) {
var a = app{
ctx: context.Background(),
bundles: make(map[string]Bundle, 8),
}
// apply options
for _, option := range options {
if err = option.apply(&a); err != nil {
return nil, err
}
}
// create di builder
if a.builder, err = a.initBuilder(); err != nil {
return nil, err
}
// register bundles
if err = a.registerBundles(); err != nil {
return nil, err
}
return &a, nil
}
// Execute implementation.
func (a *app) Execute() (err error) {
a.mux.Lock()
defer a.mux.Unlock()
// app.path
var appPath string
if appPath, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
return fmt.Errorf("unable resolve app.path : %w", err)
}
// modify context
var cancelFunc = a.withCancel()
a.withValue("app.path", appPath)
// build container
var container di.Container
if container, err = a.builder.Build(); err != nil {
return err
}
defer func() {
cancelFunc()
if err != nil {
_ = container.Close()
return
}
err = container.Close()
}()
// wait signal, cancel execution context
var sigChan = make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
go func() {
select {
case <-sigChan:
cancelFunc()
}
}()
// resolve cli root
var root *cobra.Command
if err = container.Resolve(&root, withRootCommand()); err != nil {
return err
}
err = root.ExecuteContext(a.ctx)
return
}
// builder initialize di builder
func (a *app) initBuilder() (di.Builder, error) {
return di.NewBuilder(
di.Provide(a.provideRootContext, di.Unshared()),
di.Provide(
a.provideRootCmd,
di.Constraint(0, di.Optional(true), withPersistentPreRunner()),
di.Constraint(1, di.Optional(true), withPersistentFlags()),
di.Constraint(2, di.Optional(true), withCliCommand()),
asRootCommand(),
),
di.Provide(a.provideVersionCmd, AsCliCommand()),
)
}
func (a *app) provideRootCmd(preRunners []PreRunner, flagSets []*pflag.FlagSet, subCommands []*cobra.Command) *cobra.Command {
var rootCmd = &cobra.Command{
Use: fmt.Sprintf("%s [command]", os.Args[0]), // TODO: replace to binary name
SilenceUsage: true,
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
a.withValue("cli.cmd", cmd)
a.withValue("cli.args", args)
for _, preRunner := range preRunners {
if err = preRunner.Run(a.ctx); err != nil {
return err
}
}
return nil
},
}
// register flagSets
for _, flagSet := range flagSets {
rootCmd.PersistentFlags().AddFlagSet(flagSet)
}
// register sub commands
rootCmd.AddCommand(subCommands...)
return rootCmd
}
func (a *app) provideVersionCmd(ctx context.Context) *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Application version",
SilenceUsage: true,
SilenceErrors: true,
Run: func(cmd *cobra.Command, args []string) {
if v, ok := ctx.Value("app.version").(string); ok {
fmt.Println(v)
}
},
}
}
func (a *app) provideRootContext() context.Context {
return a.ctx
}
// registerBundles resolve bundles dependencies and register them.
func (a *app) registerBundles() (err error) {
// resolve dependencies
var (
resolved = make([]string, 0, len(a.bundles))
unresolved = make([]string, 0, len(a.bundles))
)
for _, bundle := range a.bundles {
if err = a.resolveDependencies(bundle, &resolved, &unresolved); err != nil {
return err
}
}
// register
for _, name := range resolved {
if err = a.bundles[name].Build(a.builder); err != nil {
return err
}
}
return nil
}
// dependencies generate dependencies graph.
func (a *app) resolveDependencies(bundle Bundle, resolved *[]string, unresolved *[]string) (err error) {
for _, name := range *unresolved {
if bundle.Name() == name {
return fmt.Errorf(`"%s" has circular dependency of itself`, bundle.Name())
}
}
*unresolved = append(*unresolved, bundle.Name())
if v, ok := bundle.(BundleDependsOn); ok {
for _, name := range v.DependsOn() {
if v.Name() == name {
return fmt.Errorf(`"%s" can not depends on itself`, v.Name())
}
if _, ok := a.bundles[name]; !ok {
return fmt.Errorf(`"%s" has unresoled dependency "%s"`, v.Name(), name)
}
if err = a.resolveDependencies(a.bundles[name], resolved, unresolved); err != nil {
return err
}
}
}
*unresolved = (*unresolved)[:len(*unresolved)-1]
for _, name := range *resolved {
if bundle.Name() == name {
return nil
}
}
*resolved = append(*resolved, bundle.Name())
return nil
}
// withCancel append cancellation to current context. Method is non thread safe.
func (a *app) withCancel() (fn context.CancelFunc) {
a.ctx, fn = context.WithCancel(a.ctx)
return fn
}
// withValue append any value to current context. Method is non thread safe.
func (a *app) withValue(key, value interface{}) context.Context {
a.ctx = context.WithValue(a.ctx, key, value)
return a.ctx
}
func (p PreRunnerFunc) Run(ctx context.Context) error {
return p(ctx)
}
// apply implements Option.
func (f optionFunc) apply(kernel *app) error {
return f(kernel)
}