This repository was archived by the owner on Sep 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathrepl.go
More file actions
107 lines (88 loc) · 1.97 KB
/
repl.go
File metadata and controls
107 lines (88 loc) · 1.97 KB
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
package repl
import (
"fmt"
"io"
"os"
"strings"
"github.com/chzyer/readline"
"github.com/erikh/box/builder"
mruby "github.com/mitchellh/go-mruby"
)
const (
normalPrompt = "box> "
multilinePrompt = "box*> "
)
// 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(normalPrompt)
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
var stackKeep int
var val *mruby.MrbValue
p := mruby.NewParser(r.builder.Mrb())
context := mruby.NewCompileContext(r.builder.Mrb())
context.CaptureErrors(true)
for {
tmp, err := r.readline.Readline()
if err == io.EOF {
return nil
}
if err != nil && err.Error() == "Interrupt" {
if line != "" {
r.readline.SetPrompt(normalPrompt)
} else {
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 + "\n"
switch strings.TrimSpace(line) {
case "quit":
fallthrough
case "exit":
os.Exit(0)
}
if _, err := p.Parse(line, context); err != nil {
r.readline.SetPrompt(multilinePrompt)
continue
}
val, stackKeep, err = r.builder.RunCode(p.GenerateCode(), stackKeep)
line = ""
r.readline.SetPrompt(normalPrompt)
if err != nil {
fmt.Printf("+++ Error: %v\n", err)
continue
}
if val.String() != "" {
fmt.Println(val)
}
}
}