-
Notifications
You must be signed in to change notification settings - Fork 0
/
lalash.go
120 lines (99 loc) · 2.11 KB
/
lalash.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
package lalash
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/peterh/liner"
"github.com/w-haibara/lalash/history"
)
const (
historyFileName = ".lalash_history"
exitCodeOK = iota - 1
exitCodeErr
)
var (
shellExitErr = errors.New("shell exit")
funcReturnErr = errors.New("function return")
)
func RunCommand(expr string) int {
cmd := cmdNew()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := EvalString(ctx, cmd, expr); err != nil {
fmt.Println(err.Error())
return exitCodeErr
}
return exitCodeOK
}
func RunScript(script io.Reader) int {
cmd := cmdNew()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s := bufio.NewScanner(script)
for s.Scan() {
if err := EvalString(ctx, cmd, s.Text()); err != nil {
fmt.Println(err.Error())
return exitCodeErr
}
}
return exitCodeOK
}
func RunScriptFile(filename string) int {
f, err := os.Open(filename)
if err != nil {
fmt.Println(err)
return exitCodeErr
}
return RunScript(f)
}
func RunREPL() int {
cmd := cmdNew()
line := liner.NewLiner()
defer line.Close()
line.SetCompleter(func(line string) (c []string) {
if len(strings.TrimSpace(line)) <= 0 {
return nil
}
for _, v := range cmd.Internal.GetCmdsAll() {
if strings.HasPrefix(v, line) {
c = append(c, v)
}
}
for _, v := range cmd.Internal.GetAliasAll() {
if strings.HasPrefix(v, line) {
c = append(c, v)
}
}
return
})
line.SetCtrlCAborts(false)
history := history.New(historyFileName)
history.ReadHistory(line)
defer history.WriteHistory(line)
for {
if err := func() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
expr, err := line.Prompt("$ ")
if err != nil {
return fmt.Errorf("[read line error] %v", err.Error())
}
line.AppendHistory(expr)
return EvalString(ctx, cmd, expr)
}(); err != nil {
switch err {
case shellExitErr:
return exitCodeOK
case funcReturnErr:
log.Println("[func return error] here is the main routine")
continue
}
log.Println(err.Error())
}
}
}