This repository has been archived by the owner on Sep 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
repl.go
87 lines (72 loc) · 1.55 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
package repl
import (
"fmt"
"io"
"os"
"strings"
"github.com/chzyer/readline"
"github.com/erikh/box/builder"
mruby "github.com/mitchellh/go-mruby"
)
// Repl encapsulates a series of items used to create a read-evaluate-print
// loop so that end users can manually enter build instructions.
type Repl struct {
readline *readline.Instance
builder *builder.Builder
}
// NewRepl constructs a new Repl.
func NewRepl() (*Repl, error) {
rl, err := readline.New("box> ")
if err != nil {
return nil, err
}
b, err := builder.NewBuilder(true, []string{})
if err != nil {
rl.Close()
return nil, err
}
return &Repl{readline: rl, builder: b}, nil
}
// Loop runs the loop. Returns nil on io.EOF, otherwise errors are forwarded.
func (r *Repl) Loop() error {
defer func() {
if recover() != nil {
// interpreter signal or other badness, just abort.
os.Exit(0)
}
}()
var line string
for {
tmp, err := r.readline.Readline()
if err == io.EOF {
return nil
}
if err != nil && err.Error() == "Interrupt" {
fmt.Println("You can press ^D or type \"quit\", \"exit\" to exit the shell")
line = ""
continue
}
if err != nil {
fmt.Printf("+++ Error %#v\n", err)
os.Exit(1)
}
line += tmp
switch strings.TrimSpace(line) {
case "quit":
fallthrough
case "exit":
os.Exit(0)
}
p := mruby.NewParser(mruby.NewMrb())
if _, err := p.Parse(line, nil); err != nil {
continue
}
val, err := r.builder.Run(line)
line = ""
if err != nil {
fmt.Printf("+++ Error: %v\n", err)
continue
}
fmt.Println(val)
}
}