-
Notifications
You must be signed in to change notification settings - Fork 1
/
shell.go
236 lines (206 loc) · 4.85 KB
/
shell.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package gshellos
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/godevsig/glib/sys/lined"
"github.com/godevsig/gshellos/extension"
"github.com/godevsig/gshellos/stdlib"
"github.com/godevsig/gshellos/stdlib/unsafe"
"github.com/traefik/yaegi/interp"
)
type gshell struct {
src *sourceCode
interpreter *interp.Interpreter
}
func mainPkgToGshellPkg(path string) error {
modifyGoFile := func(file string, perm fs.FileMode) error {
buf, err := os.ReadFile(file)
if err != nil {
return err
}
before, after, found := bytes.Cut(buf, []byte("package main"))
if found && len(before) == 0 {
return os.WriteFile(file, append([]byte("package gshellmain"), after...), perm)
}
return nil
}
fi, err := os.Stat(path)
if err != nil {
return err
}
if fi.Mode().IsRegular() {
if !strings.HasSuffix(fi.Name(), ".go") {
return errors.New("wrong file suffix, .go expected")
}
return modifyGoFile(path, fi.Mode().Perm())
}
entires, err := os.ReadDir(path)
if err != nil {
return err
}
for _, entry := range entires {
if entry.Type().IsRegular() && strings.HasSuffix(entry.Name(), ".go") {
if err := modifyGoFile(filepath.Join(path, entry.Name()), entry.Type().Perm()); err != nil {
return err
}
}
}
return nil
}
type sourceCode struct {
codeDir string
idFile string
}
// unzip source code in required source code layout
func newSharedSourceCode(codeZip []byte) (*sourceCode, error) {
hash := md5.Sum(codeZip)
hashstr := hex.EncodeToString(hash[:])
codeDir := filepath.Join(gshellTempDir, hashstr)
idDir := filepath.Join(codeDir, ".IDHOLDER")
idFile := filepath.Join(idDir, genID(4))
src := &sourceCode{codeDir, idFile}
if err := os.MkdirAll(idDir, 0755); err != nil {
return nil, err
}
lockFile := filepath.Join(codeDir, ".lock")
flock, err := os.OpenFile(lockFile, os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
defer flock.Close()
if err := syscall.Flock(int(flock.Fd()), syscall.LOCK_EX); err != nil {
return nil, err
}
defer syscall.Flock(int(flock.Fd()), syscall.LOCK_UN)
pkgDir := filepath.Join(codeDir, "src", "gshellmain")
if _, err := os.Stat(pkgDir); err != nil {
if err := os.MkdirAll(pkgDir, 0755); err != nil {
return src, err
}
if err := unzipBufferToPath(codeZip, pkgDir); err != nil {
return src, err
}
if err := mainPkgToGshellPkg(pkgDir); err != nil {
return src, err
}
}
// place an empty file inside to prevent early removal of codeDir
if file, err := os.Create(idFile); err == nil {
file.Close()
}
return src, nil
}
func (src *sourceCode) close() {
os.Remove(src.idFile)
entries, _ := os.ReadDir(filepath.Dir(src.idFile))
if len(entries) == 0 {
os.RemoveAll(src.codeDir)
}
}
func newShellWithCodeZip(codeZip []byte) (*gshell, error) {
gsh := &gshell{}
if codeZip != nil {
src, err := newSharedSourceCode(codeZip)
if err != nil {
return nil, err
}
gsh.src = src
}
return gsh, nil
}
func newShell() (*gshell, error) {
return newShellWithCodeZip(nil)
}
func (gsh *gshell) close() {
if gsh.src != nil {
gsh.src.close()
}
gsh.interpreter = nil
}
func (gsh *gshell) init(opt interp.Options) error {
if gsh.src != nil {
opt.GoPath = gsh.src.codeDir
}
i := interp.New(opt)
if err := i.Use(stdlib.Symbols); err != nil {
return err
}
if err := i.Use(unsafe.Symbols); err != nil {
return err
}
if err := i.Use(extension.BuiltinSymbols); err != nil {
return err
}
if err := i.Use(extension.PluginSymbols); err != nil {
return err
}
i.ImportUsed()
os.Args = opt.Args //reset os.Args for interpreter
gsh.interpreter = i
if gsh.src != nil {
if _, err := i.Eval(`import "gshellmain"`); err != nil {
return err
}
}
return nil
}
func (gsh *gshell) start(ctx context.Context) error {
_, err := gsh.interpreter.EvalWithContext(ctx, "gshellmain.main()")
return err
}
func (gsh *gshell) stop() error {
_, err := gsh.interpreter.Eval("gshellmain.Stop()")
return err
}
func (gsh *gshell) abort(cancel context.CancelFunc) {
cancel()
}
func (gsh *gshell) runREPL() {
ctx, cancel := context.WithCancel(context.Background())
end := make(chan struct{}) // channel to terminate the REPL
defer close(end)
sig := make(chan os.Signal, 1) // channel to trap interrupt signal (Ctrl-C)
signal.Notify(sig, os.Interrupt)
defer signal.Stop(sig)
go func() {
for {
select {
case <-sig:
cancel()
ctx, cancel = context.WithCancel(context.Background())
case <-end:
return
}
}
}()
led := lined.NewEditor(lined.Cfg{
Prompt: ">> ",
})
defer led.Close()
for {
line, err := led.Readline()
if errors.Is(err, io.EOF) {
break
}
if len(line) != 0 {
_, err := gsh.interpreter.EvalWithContext(ctx, line)
if err != nil {
fmt.Println(err)
}
}
}
}
func init() {
os.Setenv("YAEGI_SPECIAL_STDIO", "1")
}