github.com/aergoio/aergo@v1.3.1/cmd/brick/exec/exec.go (about) 1 package exec 2 3 import ( 4 "fmt" 5 "sort" 6 "strings" 7 8 "github.com/aergoio/aergo-lib/log" 9 "github.com/aergoio/aergo/cmd/brick/context" 10 ) 11 12 var logger = log.NewLogger("brick") 13 14 var storedCmdLine = "" 15 16 type Executor interface { 17 Command() string 18 Syntax() string 19 Usage() string 20 Describe() string 21 Validate(args string) error 22 Run(args string) (string, error) 23 } 24 25 var execImpls = make(map[string]Executor) 26 27 func registerExec(executor Executor) { 28 execImpls[executor.Command()] = executor 29 Index(context.CommandSymbol, executor.Command()) 30 } 31 32 func GetExecutor(cmd string) Executor { 33 return execImpls[cmd] 34 } 35 36 func AllExecutors() []Executor { 37 38 var result []Executor 39 40 for _, executor := range execImpls { 41 result = append(result, executor) 42 } 43 44 sort.Slice(result, func(i, j int) bool { 45 return strings.Compare(result[i].Command(), result[j].Command()) < 0 46 }) 47 48 return result 49 } 50 51 func Broker(cmdStr string) { 52 53 cmd, args := context.ParseFirstWord(cmdStr) 54 if len(cmd) == 0 || context.Comment == cmd { 55 return 56 } 57 58 Execute(cmd, args) 59 } 60 61 func Execute(cmd, args string) { 62 executor := GetExecutor(cmd) 63 64 if executor == nil { 65 letBatchKnowErr = fmt.Errorf("command not found: %s", cmd) 66 batchErrorCount++ 67 logger.Error().Str("cmd", cmd).Msg("command not found") 68 return 69 } 70 71 if err := executor.Validate(args); err != nil { 72 letBatchKnowErr = err 73 batchErrorCount++ 74 logger.Error().Err(err).Str("cmd", cmd).Msg("validation fail") 75 return 76 } 77 78 result, err := executor.Run(args) 79 if err != nil { 80 letBatchKnowErr = err 81 batchErrorCount++ 82 logger.Error().Err(err).Str("cmd", cmd).Msg("execution fail") 83 return 84 } 85 86 //logger.Info().Str("result", result).Str("cmd", cmd).Msg("execution success") 87 logger.Info().Str("cmd", cmd).Msg(result) 88 }