-
Notifications
You must be signed in to change notification settings - Fork 9
/
readline.go
114 lines (99 loc) · 2.39 KB
/
readline.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
102
103
104
105
106
107
108
109
110
111
112
113
114
package console
import (
"fmt"
"io"
"github.com/alecthomas/kong"
"github.com/chzyer/readline"
"github.com/mattn/go-shellwords"
"github.com/hideckies/hermit/pkg/client/state"
"github.com/hideckies/hermit/pkg/common/parser"
"github.com/hideckies/hermit/pkg/common/stdin"
"github.com/hideckies/hermit/pkg/common/stdout"
"github.com/hideckies/hermit/pkg/common/utils"
servState "github.com/hideckies/hermit/pkg/server/state"
)
func Readline(clientState *state.ClientState) error {
ri, err := stdin.InitReadline(true, "/tmp/readline_client.tmp")
if err != nil {
stdout.LogFailed(fmt.Sprint(err))
return err
}
defer ri.Close()
ri.CaptureExitSignal()
isAgentMode := false
var currentParser *kong.Kong
// This is only used for passing the ctx.Run function as argument.
serverState, err := servState.NewServerState(nil, nil, nil)
if err != nil {
return err
}
for {
isAgentMode = clientState.AgentMode.Name != ""
// Make prompt
var p string
if !isAgentMode {
p = stdin.MakePrompt("client", "")
} else {
p = stdin.MakePrompt("client", clientState.AgentMode.Name)
}
ri.SetPrompt(p)
// Set parser
if isAgentMode {
currentParser, err = parser.NewParser(
&parser.GrammarAgentMode{},
clientState.Conf.Server.Host,
clientState.Conf.Server.Domains,
)
if err != nil {
stdout.LogFailed(fmt.Sprintf("Parse Error: %s"))
break
}
} else {
currentParser, err = parser.NewParser(
&parser.GrammarRoot{},
clientState.Conf.Server.Host,
clientState.Conf.Server.Domains,
)
if err != nil {
stdout.LogFailed(fmt.Sprintf("Parse Error: %s"))
break
}
}
clientState.Parser = currentParser
// Read input
line, err := ri.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
// Remove redundant spaces
line = utils.StandardizeSpaces(line)
args, err := shellwords.Parse(line)
if err != nil {
stdout.LogFailed(fmt.Sprint(err))
continue
}
ctx, err := clientState.Parser.Parse(args)
if err != nil {
if err, ok := err.(*kong.ParseError); ok {
stdout.LogFailed(err.Error())
stdout.LogInfo("Run 'help <command>' for usage.")
}
continue
}
err = ctx.Run(ctx, serverState, clientState)
if err != nil {
stdout.LogFailed(fmt.Sprint(err))
continue
}
if !clientState.Continue {
break
}
}
return nil
}