forked from box-builder/box
/
repl.go
127 lines (104 loc) · 2.5 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
115
116
117
118
119
120
121
122
123
124
125
126
127
package repl
import (
"context"
"fmt"
"io"
"os"
"strings"
"github.com/chzyer/readline"
"github.com/erikh/box/builder"
"github.com/erikh/box/signal"
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(omit []string) (*Repl, error) {
rl, err := readline.New(normalPrompt)
if err != nil {
return nil, err
}
signal.Handler.Exit = false
signal.Handler.IgnoreRunners = true
ctx, cancel := context.WithCancel(context.Background())
b, err := builder.NewBuilder(builder.BuildConfig{
OmitFuncs: omit,
TTY: true,
Cache: false,
Context: ctx,
ShowRun: true,
})
if err != nil {
cancel()
rl.Close()
return nil, err
}
signal.Handler.AddFunc(cancel)
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 err := recover(); err != nil {
fmt.Printf("Aborting due to interpreter error: %v\n", err)
os.Exit(2)
}
}()
var line string
var stackKeep int
var result builder.BuildResult
p := mruby.NewParser(r.builder.Mrb())
compileContext := mruby.NewCompileContext(r.builder.Mrb())
compileContext.CaptureErrors(true)
for {
tmp, err := r.readline.Readline()
if err == io.EOF {
return nil
}
if _, ok := err.(*readline.InterruptError); ok || err != nil {
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, compileContext); err != nil {
r.readline.SetPrompt(multilinePrompt)
continue
}
ctx, cancel := context.WithCancel(context.Background())
r.builder.SetContext(ctx)
signal.Handler.AddFunc(cancel)
result, stackKeep = r.builder.RunCode(p.GenerateCode(), stackKeep)
line = ""
r.readline.SetPrompt(normalPrompt)
if result.Err != nil {
fmt.Printf("+++ Error: %v\n", result.Err)
continue
}
if result.Value.String() != "" {
fmt.Println(result.Value)
}
}
}