-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.go
139 lines (115 loc) · 2.41 KB
/
eval.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
128
129
130
131
132
133
134
135
136
137
138
139
package lalash
import (
"bufio"
"bytes"
"context"
"os"
"os/exec"
"os/signal"
"strings"
"github.com/w-haibara/lalash/parser"
)
func EvalString(ctx context.Context, cmd Command, expr string) error {
tokens, err := parser.Parse(expr)
if err != nil {
return err
}
start := 0
for i := 1; i <= len(tokens); i++ {
if tokens[i-1].Kind == parser.SeparateToken {
if err := eval(ctx, cmd, tokens[start:i-1]); err != nil {
return err
}
start = i
if start >= len(tokens) {
break
}
continue
}
if i == len(tokens) {
if err := eval(ctx, cmd, tokens[start:i]); err != nil {
return err
}
}
}
return nil
}
func eval(ctx context.Context, cmd Command, tokens []parser.Token) error {
if tokens == nil || len(tokens) == 0 || tokens[0].Val == "" {
return nil
}
argv := []string{}
for i, v := range tokens {
if v.Kind == parser.SubstitutionToken {
res, err := func() (string, error) {
var b bytes.Buffer
w := bufio.NewWriter(&b)
cmd := cmd
cmd.Stdout = w
tokens, err := parser.Parse(v.Val)
if err != nil {
return "", err
}
if tokens == nil || len(tokens) == 0 || tokens[0].Val == "" {
return "", nil
}
if err := eval(ctx, cmd, tokens); err != nil {
return "", err
}
w.Flush()
return strings.TrimSpace(strings.ReplaceAll(b.String(), "\n", " ")), nil
}()
if err != nil {
return err
}
tokens[i].Val = res
tokens[i].Kind = parser.CommandToken
}
argv = append(argv, tokens[i].Val)
}
if err := Exec(ctx, cmd, argv); err != nil {
return err
}
return nil
}
func Exec(ctx context.Context, cmd Command, argv []string) error {
if alias := cmd.Internal.GetAlias(argv[0]); alias != argv[0] {
str := ""
for i, v := range argv {
if i == 0 {
str += alias + " "
continue
}
str += v + " "
}
EvalString(ctx, cmd, str)
return nil
}
if c, err := cmd.Internal.Get(argv[0]); err == nil {
if err := c.Fn(ctx, cmd, argv[0], argv[1:]...); err != nil {
return err
}
return nil
}
if err := func() error {
c := exec.CommandContext(ctx, argv[0], argv[1:]...)
c.Stdin = cmd.Stdin
c.Stdout = cmd.Stdout
c.Stderr = cmd.Stderr
sigc := make(chan os.Signal, 1024)
defer signal.Stop(sigc)
signal.Notify(sigc)
go func() {
for {
c.Process.Signal(<-sigc)
}
}()
if err := c.Run(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
return nil
}