forked from spacewander/boltcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.go
73 lines (65 loc) · 1.41 KB
/
cli.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
package main
import (
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/chzyer/readline"
)
func buildCompleter() readline.AutoCompleter {
cmds := []readline.PrefixCompleterInterface{}
for k := range CmdMap {
cmds = append(cmds, readline.PcItem(k))
}
return readline.NewPrefixCompleter(cmds...)
}
func getHomeDir() string {
env := "HOME"
if runtime.GOOS == "windows" {
env = "USERPROFILE"
}
return os.Getenv(env)
}
// StartCli starts the repl environment
func StartCli() {
historyFileDir := filepath.Join(getHomeDir(), ".cache")
if _, err := os.Stat(historyFileDir); os.IsNotExist(err) {
// simply ignore error since the history feature is optional.
os.Mkdir(historyFileDir, 0644)
}
l, err := readline.NewEx(&readline.Config{
AutoComplete: buildCompleter(),
Prompt: DbPath + "> ",
HistoryFile: filepath.Join(historyFileDir, "boltclihistory"),
HistoryLimit: 1000,
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
panic(err)
}
defer l.Close()
for {
line, err := l.Readline()
if err == readline.ErrInterrupt {
if len(line) == 0 {
break
} else {
continue
}
} else if err == io.EOF {
break
}
fields := strings.Fields(strings.TrimSpace(line))
if len(fields) == 0 {
continue
}
result := ExecCmdInCli(fields[0], fields[1:]...)
if result != "" {
println(result)
} else {
println("(empty list or set)")
}
}
}