-
Notifications
You must be signed in to change notification settings - Fork 43
/
executor.go
101 lines (87 loc) · 2.32 KB
/
executor.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
package cmds
import (
"context"
)
type Executor interface {
Execute(req *Request, re ResponseEmitter, env Environment) error
}
// Environment is the environment passed to commands.
type Environment interface{}
// MakeEnvironment takes a context and the request to construct the environment
// that is passed to the command's Run function.
// The user can define a function like this to pass it to cli.Run.
type MakeEnvironment func(context.Context, *Request) (Environment, error)
// MakeExecutor takes the request and environment variable to construct the
// executor that determines how to call the command - i.e. by calling Run or
// making an API request to a daemon.
// The user can define a function like this to pass it to cli.Run.
type MakeExecutor func(*Request, interface{}) (Executor, error)
func NewExecutor(root *Command) Executor {
return &executor{
root: root,
}
}
type executor struct {
root *Command
}
func (x *executor) Execute(req *Request, re ResponseEmitter, env Environment) error {
cmd := req.Command
if cmd.Run == nil {
return ErrNotCallable
}
err := cmd.CheckArguments(req)
if err != nil {
return err
}
if cmd.PreRun != nil {
err = cmd.PreRun(req, env)
if err != nil {
return err
}
}
maybeStartPostRun := func(formatters PostRunMap) <-chan error {
var (
postRun func(Response, ResponseEmitter) error
postRunCh = make(chan error)
)
// Check if we have a formatter for this emitter type.
typer, isTyper := re.(interface {
Type() PostRunType
})
if isTyper {
postRun = formatters[typer.Type()]
}
// If not, just return nil via closing.
if postRun == nil {
close(postRunCh)
return postRunCh
}
// Otherwise, relay emitter responses
// from Run to PostRun, and
// from PostRun to the original emitter.
var (
postRes Response
postEmitter = re
)
re, postRes = NewChanResponsePair(req)
go func() {
defer close(postRunCh)
postRunCh <- postEmitter.CloseWithError(postRun(postRes, postEmitter))
}()
return postRunCh
}
postRunCh := maybeStartPostRun(cmd.PostRun)
runCloseErr := re.CloseWithError(cmd.Run(req, re, env))
postCloseErr := <-postRunCh
switch runCloseErr {
case ErrClosingClosedEmitter, nil:
default:
return runCloseErr
}
switch postCloseErr {
case ErrClosingClosedEmitter, nil:
default:
return postCloseErr
}
return nil
}