-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl.go
114 lines (96 loc) · 2.14 KB
/
repl.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 repl
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path"
"regexp"
"strings"
"github.com/peterh/liner"
)
var (
cmd string
debug bool
compDir string
histDir string
histFile string
)
func Run() {
parseFlags()
if flag.NArg() == 0 {
printUsage()
}
readLine := liner.NewLiner()
defer readLine.Close()
readLine.SetCtrlCAborts(true)
loadCompletions(readLine)
loadHistory(readLine)
for {
input, err := readLine.Prompt(cmd + ">> ")
if err == io.EOF {
saveHistory(readLine)
os.Exit(0)
}
if input == "exit" || input == "quit" {
fmt.Println("Use Ctrl-D (i.e. EOF) to exit")
continue
}
if debug {
fmt.Printf("EXECUTING: %s %s\n\n", cmd, input)
}
args := regexp.MustCompile(`\s+`).Split(input, -1)
if cmdOut, err := exec.Command(cmd, args...).Output(); err == nil {
fmt.Println(string(cmdOut))
readLine.AppendHistory(input)
}
}
}
func parseFlags() {
homeDir := os.Getenv(("HOME"))
flag.BoolVar(&debug, "debug", false, "Enable debug output")
flag.StringVar(&compDir, "compdir", homeDir+"/.repl", "Directory for completion files")
flag.StringVar(&histDir, "histdir", homeDir, "Directory for history file")
flag.Parse()
cmd = flag.Arg(0)
histFile = path.Join(histDir, ".repl_history")
}
func printUsage() {
prog := path.Base(cmd)
fmt.Fprintf(flag.CommandLine.Output(), "Usage:\n %s cmd [options]\n\nOptions:\n", prog)
flag.PrintDefaults()
os.Exit(0)
}
func loadCompletions(line *liner.State) {
compFile := path.Join(compDir, cmd)
if f, err := os.Open(compFile); err == nil {
defer f.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(f)
comps := buf.String()
line.SetCompleter(func(line string) (c []string) {
for _, comp := range strings.Split(comps, " ") {
if strings.HasPrefix(comp, strings.ToLower(line)) {
c = append(c, comp)
}
}
return
})
}
}
func loadHistory(line *liner.State) {
if f, err := os.Open(histFile); err == nil {
line.ReadHistory(f)
f.Close()
}
}
func saveHistory(line *liner.State) {
if f, err := os.Create(histFile); err != nil {
fmt.Println("Error writing history file: ", err)
} else {
line.WriteHistory(f)
f.Close()
}
}