-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrepl.go
109 lines (90 loc) · 1.88 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
package main
import (
"fmt"
"os"
"strings"
"unicode"
"github.com/peterh/liner"
)
func RunRepl(store *Secstore, line *liner.State) {
var sections []string
var l string
var err error
line.SetCompleter(completer)
for {
l, err = line.Prompt("> ")
if err != nil {
break
}
line.AppendHistory(l)
sections = splitSections(l)
if len(sections) == 0 {
} else if strings.HasPrefix("quit", sections[0]) {
if store.Saved {
break
} else {
l, err = line.Prompt("There are unsaved changes, really exit? [y/n] ")
if err == nil && l == "y" {
break
}
}
} else {
err = EvalCommand(store, line, sections)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
}
}
func splitSections(s string) (sections []string) {
var i, j int
var quote bool = false
var section string
i = 0
for i < len(s) {
section = ""
for j = i; j < len(s); j++ {
if s[j] == '\'' {
quote = !quote
} else if unicode.IsSpace(rune(s[j])) && !quote {
break
} else {
section = section + string(s[j])
}
}
sections = append(sections, section)
for i = j; i < len(s); i++ {
if !unicode.IsSpace(rune(s[i])) {
break
}
}
}
return sections
}
func EvalCommand(store *Secstore, line *liner.State, sections []string) error {
args := []string(nil)
if len(sections) > 1 {
args = sections[1:]
}
if f, err := MatchCommand(sections[0]); err == nil {
return f(store, line, args)
} else {
return err
}
}
func completer(line string) []string {
sections := splitSections(line)
if len(sections) > 1 {
return []string(nil)
} else if len(sections) == 1 {
var matches []string = []string(nil)
for c, _ := range Commands {
if strings.HasPrefix(c, sections[0]) {
matches = append(matches, c)
}
}
return matches
} else {
return []string(nil)
}
}