/
repl.go
103 lines (85 loc) · 2.04 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
package repl
import (
"fmt"
"io"
"os"
"strings"
"github.com/chzyer/readline"
"github.com/errordeveloper/kubeplay/rubykube"
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 play with quebes & pods.
type Repl struct {
rubykube *rubykube.RubyKube
readline *readline.Instance
}
// NewRepl constructs a new Repl.
func NewRepl() (*Repl, error) {
rl, err := readline.New("kubeplay ()> ")
if err != nil {
return nil, err
}
rk, err := rubykube.NewRubyKube([]string{}, rl)
if err != nil {
rl.Close()
return nil, err
}
return &Repl{rubykube: rk, readline: rl}, 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 {
panic(fmt.Errorf("repl.Loop: %v", err))
}
}()
var line string
var stackKeep int
//var val *mruby.MrbValue
parser := mruby.NewParser(r.rubykube.Mrb())
context := mruby.NewCompileContext(r.rubykube.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.rubykube.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)
case "help":
fmt.Println("Please take a look at usage examples\n\t\thttps://github.com/errordeveloper/kubeplay/blob/master/README.md")
}
if _, err := parser.Parse(line, context); err != nil {
r.rubykube.MultiLinePrompt()
continue
}
_, stackKeep, err = r.rubykube.RunCode(parser.GenerateCode(), stackKeep)
line = ""
r.rubykube.NormalPrompt()
if err != nil {
fmt.Printf("+++ Error: %v\n", err)
continue
}
//if val.String() != "" {
// fmt.Println(val)
//}
}
}