-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcode.go
342 lines (300 loc) · 8.7 KB
/
code.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"fmt"
"os"
"github.com/wxnacy/wgo/file"
"github.com/wxnacy/wgo/color"
"github.com/wxnacy/wgo/arrays"
"github.com/wxnacy/wgo/codes"
"os/exec"
"bytes"
"strings"
"errors"
"time"
)
var tempfile string
var code *Code
type CodeMode uint8
const (
CodeImport CodeMode = iota
CodeFunc
CodeMain
)
type Import struct {
Name string
Aliasname string
}
func newImport(input string) Import {
var name string
var aliasname string
if strings.HasPrefix(input, "import") {
ipt := input[6:]
ipt = strings.Trim(ipt, " ")
ipt = strings.Trim(ipt, "\"")
if strings.Contains(ipt, "\"") {
na := strings.Split(ipt, "\"")
aliasname = strings.Trim(na[0], " ")
name = strings.Trim(na[1], " ")
} else {
name = ipt
aliasname = name
if strings.Contains(name, "/") {
names := strings.Split(name, "/")
aliasname = names[len(names) - 1]
}
}
} else {
name = input
aliasname = name
if strings.Contains(input, "/") {
names := strings.Split(input, "/")
aliasname = names[len(names) - 1]
}
}
i := Import{Name:name, Aliasname: aliasname}
return i
}
type Code struct {
importMap map[string]Import
mainFunc []string
variables []string
lastInput string
lastInputUse bool
lastInputMode CodeMode
funcs map[string][]string
codes []string
}
func Coder() *Code {
if code == nil {
code = &Code{
importMap: make(map[string]Import),
mainFunc: make([]string, 0),
codes: make([]string, 0),
funcs: make(map[string][]string),
}
code.importMap["fmt"] = newImport("fmt")
code.importMap["os"] = newImport("os")
code.importMap["time"] = newImport("time")
code.importMap["runtime"] = newImport("runtime")
code.importMap["strings"] = newImport("strings")
code.importMap["sort"] = newImport("sort")
}
return code
}
func (this *Code) resetInput() {
this.lastInput = ""
this.lastInputUse = false
}
func (this *Code) clear() {
this.codes = make([]string, 0)
}
func (this *Code) GetImportMap() map[string]Import {
return this.importMap
}
func (this *Code) GetImports() []string {
res := make([]string, 0)
for k, _ := range this.importMap {
res = append(res, k)
}
return res
}
// 获取导入包的别名列表
func (this *Code) GetImportNames() []string {
res := make([]string, 0)
for _, v := range this.importMap {
res = append(res, v.Aliasname)
}
return res
}
func (this *Code) GetVariables() []string {
return this.variables
}
func (this *Code) GetMains() []string {
return this.mainFunc
}
func (this *Code) Input(line string) {
this.lastInput = line
this.lastInputUse = false
if strings.HasPrefix(line, "import") {
this.lastInputMode = CodeImport
} else {
this.lastInputMode = CodeMain
}
}
// 处理输入命令
func (this *Code) input() {
switch this.lastInputMode {
case CodeMain: {
if arrays.ContainsString(this.mainFunc, this.lastInput) == -1 {
this.mainFunc = append(this.mainFunc, this.lastInput)
}
}
case CodeImport: {
this.inputImport(this.lastInput)
}
}
this.variables = codes.ParseVarnamesFromArray(this.mainFunc)
this.resetInput()
}
// 输入 import
func (this *Code) inputImport(input string) {
impot := newImport(input)
this.importMap[impot.Name] = impot
}
// 拼接打印语句
func (this *Code) makePrintCode(input string) string {
return fmt.Sprintf(
"%s.Println(%s)", this.importMap["fmt"].Aliasname, input,
)
}
// 格式化代码
func (this *Code) mainFormat() []string {
var mains = make([]string, 0)
var res = make([]string, 0)
if arrays.ContainsString(this.variables, this.lastInput) > -1 {
this.lastInput = this.makePrintCode(this.lastInput)
}
// if strings.Count(this.lastInput, ".") >= 1 {
if index := strings.Index(this.lastInput, "."); index > -1 {
// index := strings.Index(this.lastInput, ".")
imptName := this.lastInput[0:index]
// Logger().Debugf("import %s", imptName)
I, ok := this.importMap[imptName]
// Logger().Debug(GetPrompts())
if (ok && I.Name != "fmt") {
i := strings.Index(this.lastInput, "(")
funcName := this.lastInput
if i > -1 {
funcName = this.lastInput[index+1:i]
}
// Logger().Debugf("func %s", funcName)
canPrint := true
// 判断当前输入的命令行是否有返回值
for _, d := range GetPrompts() {
// Logger().Debug(d)
if d.Package == I.Name && d.Name == funcName {
// Logger().Debug(d.Type)
isReturnIndex := strings.Index(d.Type, ")")
if len(d.Type) - 1 <= isReturnIndex {
canPrint = false
}
}
}
if canPrint {
this.lastInput = this.makePrintCode(this.lastInput)
}
}
}
mains = this.mainFunc
has := arrays.ContainsString(this.mainFunc, this.lastInput)
if !strings.HasPrefix(this.lastInput, "import") && has == -1{
mains = append(mains, this.lastInput)
}
if len(mains) == 0 {
return res
}
for _, m := range mains {
res = append(res, m)
}
varList := codes.ParseVarnamesFromArray(mains)
for _, v := range varList {
res = append(res, "_ = " + v)
}
clearPrintPrompts()
return res
}
// 格式化全部代码
func (this *Code) Format() string {
b := time.Now()
this.clear()
var isLastInput bool
mains := this.mainFormat()
var mainString = strings.Join(mains, "\n")
mainString = "\n" + mainString
mainString += this.lastInput
// Logger().Debug(mainString)
this.codes = append(this.codes, "package main")
if !isLastInput && strings.HasPrefix(this.lastInput, "import") {
im := newImport(this.lastInput)
impt := fmt.Sprintf("import _ \"%s\"", im.Name)
this.codes = append(this.codes, impt)
isLastInput = true
this.lastInputUse = true
}
this.codes = append(this.codes, "import (")
if len(this.importMap) > 0 {
for k, v := range this.importMap {
// Logger().Debugf("import %v", v)
ifmt := ""
importName := v.Aliasname
if strings.Contains(mainString, "(" + importName + ".") ||
strings.Contains(mainString, ")" + importName + ".") ||
strings.Contains(mainString, " " + importName + ".") ||
strings.Contains(mainString, "\n" + importName + ".") {
ifmt = "\t%s \"%s\""
ifmt = fmt.Sprintf(ifmt, v.Aliasname, k)
} else {
ifmt = "\t_ \"%s\""
ifmt = fmt.Sprintf(ifmt, k)
}
this.codes = append(this.codes, ifmt)
}
}
this.codes = append(this.codes, ")")
this.codes = append(this.codes, "func main() {")
this.codes = append(this.codes, mains...)
this.codes = append(this.codes, "}")
res := strings.Join(this.codes, "\n")
// Logger().Debugf("run code\n%s", res)
Logger().Debugf("Format time used: %v", time.Since(b))
return res
}
func (this *Code) Print() {
fmt.Println(this.Format())
}
func (this *Code) Run() (string, error){
os.Remove(tempFile())
writeCode(this.Format())
cmd := exec.Command("go", "run", tempFile())
var out bytes.Buffer
var outErr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &outErr
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
if out.String() != "" {
fmt.Println(out.String())
return out.String(), nil
}
errStr := outErr.String()
if errStr != "" {
errStr = strings.Replace(errStr, tempFile() + ":", "", 2)
fmt.Println(color.Red(errStr))
this.resetInput()
return "", errors.New(outErr.String())
} else {
this.input()
return "", nil
}
}
func tempFile() string {
if tempfile == "" {
tempfile = fmt.Sprintf("%swgo_temp.go", tempDir())
}
return tempfile
}
func initTempDir() {
if !file.Exists(tempDir()) {
err := os.Mkdir(tempDir(), 0700)
handlerErr(err)
}
}
func writeCode(code string) {
initTempDir()
f, err := os.OpenFile(tempFile(), os.O_CREATE|os.O_WRONLY, 0600)
handlerErr(err)
f.WriteString(code)
f.Close()
}