-
Notifications
You must be signed in to change notification settings - Fork 268
/
Copy pathinject.go
56 lines (46 loc) · 1.81 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
package command
import (
"context"
"github.com/urfave/cli"
)
// InjectContext injects an existing Context as the first middleware
// and then wraps a function with middleware using that context. It
// returns a cli.ActionFunc with the cli.Context added to the Context.
// By injecting the existing context as the first middleware, we ensure
// that it's the Context all later middlewares operate on.
func InjectContext(injectedCtx context.Context, fn func(context.Context) error, middleware ...func(context.Context) (context.Context, error)) cli.ActionFunc {
injectedMiddleware := []func(context.Context) (context.Context, error){
func(context.Context) (context.Context, error) {
return injectedCtx, nil
},
}
injectedMiddleware = append(injectedMiddleware, middleware...)
//nolint:contextcheck // context is injected in fn
return wrap(fn, injectedMiddleware...)
}
type cliCtxKey struct{}
// withCLIContext adds a cli.Context to the Context.
func withCLIContext(ctx context.Context, clictx *cli.Context) context.Context {
return context.WithValue(ctx, cliCtxKey{}, clictx)
}
// CLIContextFromContext returns a pointer to a cli.Context
// It panics when the cli.Context is not set.
func CLIContextFromContext(ctx context.Context) *cli.Context {
return ctx.Value(cliCtxKey{}).(*cli.Context)
}
// wrap wraps a function with middleware using a new context. It returns a cli.ActionFunc with
// the cli.Context added to the Context.
func wrap(fn func(context.Context) error, middleware ...func(context.Context) (context.Context, error)) cli.ActionFunc {
return func(clictx *cli.Context) error {
ctx := context.Background()
// apply middleware to the new context
for _, fn := range middleware {
var err error
if ctx, err = fn(ctx); err != nil {
return err
}
}
ctx = withCLIContext(ctx, clictx)
return fn(ctx)
}
}