-
Notifications
You must be signed in to change notification settings - Fork 41
/
exec.go
88 lines (67 loc) · 1.7 KB
/
exec.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
package exec
import (
"fmt"
"sort"
"strings"
"github.com/aergoio/aergo-lib/log"
"github.com/aergoio/aergo/cmd/brick/context"
)
var logger = log.NewLogger("brick")
var storedCmdLine = ""
type Executor interface {
Command() string
Syntax() string
Usage() string
Describe() string
Validate(args string) error
Run(args string) (string, error)
}
var execImpls = make(map[string]Executor)
func registerExec(executor Executor) {
execImpls[executor.Command()] = executor
Index(context.CommandSymbol, executor.Command())
}
func GetExecutor(cmd string) Executor {
return execImpls[cmd]
}
func AllExecutors() []Executor {
var result []Executor
for _, executor := range execImpls {
result = append(result, executor)
}
sort.Slice(result, func(i, j int) bool {
return strings.Compare(result[i].Command(), result[j].Command()) < 0
})
return result
}
func Broker(cmdStr string) {
cmd, args := context.ParseFirstWord(cmdStr)
if len(cmd) == 0 || context.Comment == cmd {
return
}
Execute(cmd, args)
}
func Execute(cmd, args string) {
executor := GetExecutor(cmd)
if executor == nil {
letBatchKnowErr = fmt.Errorf("command not found: %s", cmd)
batchErrorCount++
logger.Error().Str("cmd", cmd).Msg("command not found")
return
}
if err := executor.Validate(args); err != nil {
letBatchKnowErr = err
batchErrorCount++
logger.Error().Err(err).Str("cmd", cmd).Msg("validation fail")
return
}
result, err := executor.Run(args)
if err != nil {
letBatchKnowErr = err
batchErrorCount++
logger.Error().Err(err).Str("cmd", cmd).Msg("execution fail")
return
}
//logger.Info().Str("result", result).Str("cmd", cmd).Msg("execution success")
logger.Info().Str("cmd", cmd).Msg(result)
}