/
runner.go
59 lines (49 loc) · 980 Bytes
/
runner.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
package tools
import (
"os"
"strings"
"github.com/1xyz/pryrite/app"
"github.com/mattn/go-shellwords"
"github.com/spf13/cobra"
)
type RunnerContext interface {
NewRootCmd() *cobra.Command
HistoryAppend(string) error
}
type Runner struct {
ctx RunnerContext
}
func NewRunner(ctx RunnerContext) *Runner {
return &Runner{
ctx: ctx,
}
}
func (r *Runner) Execute(cmd string) {
cmd = strings.TrimSpace(cmd)
if len(cmd) == 0 {
return
}
if strings.HasPrefix(cmd, "#") {
return
}
if cmd == "q" || cmd == "quit" || cmd == "exit" {
os.Exit(0)
return
}
args, _ := shellwords.Parse(cmd)
if args[0] == app.Name {
args = args[1:]
}
if len(args) == 0 {
return
}
c := r.ctx.NewRootCmd()
c.SetArgs(args)
// Don't handle the error (kobra does it for you)
if err := c.Execute(); err == nil {
// append to command history if there is no error
if err := r.ctx.HistoryAppend(cmd); err != nil {
Log.Err(err).Msgf("history.Append %s", cmd)
}
}
}