-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathgosl.go
223 lines (196 loc) · 4.47 KB
/
gosl.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
/*
This is an application that can make you write script with Go languages.
It is NOT an interpreter but the pure Go. The preprocessor tranforms the script into a Go program,
instantly compile and run. So it is almost same as the standard Go with the same efficiency.
*/
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"math"
"math/rand"
"os"
"os/exec"
"strings"
"syscall"
"github.com/golangplus/fmt"
"github.com/daviddengcn/go-villa"
)
const (
STAGE_READY = iota // start
STAGE_IMPORT // import sentences
STAGE_MAIN // main part
)
func genFilename(suffix villa.Path) villa.Path {
if !strings.HasSuffix(suffix.S(), ".go") {
suffix += ".go"
}
dir := villa.Path(os.TempDir())
for {
base := villa.Path(fmt.Sprintf("gosl-%08x-%s", rand.Int63n(math.MaxInt64), suffix))
fn := dir.Join(base)
if !fn.Exists() {
return fn
}
}
}
func execCode(err error) int {
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
return status.ExitStatus()
}
}
return 0
}
var (
DEFAULT_IMPORT = []string{
"fmt", "Printf",
"os", "Exit",
"strings", "Contains",
"math", "Abs",
"strconv", "Atoi",
"time", "Sleep",
"github.com/daviddengcn/gosl/builtin", "Exec",
}
)
func appendInitAndMainHead(code *bytes.Buffer) {
code.WriteString(`func init() {`)
code.WriteString(` Args = Args[1:];`)
for i := 1; i < len(DEFAULT_IMPORT); i += 2 {
code.WriteString(` _ = `)
code.WriteString(DEFAULT_IMPORT[i])
code.WriteString(`;`)
}
code.WriteString(` }; `)
code.WriteString("func main() { ")
}
type Options struct {
ShowSource bool
NoClean bool
}
func Process(buf []byte, fn villa.Path, args []string, opts Options) error {
var code bytes.Buffer
code.WriteString(`package main;`)
for i := 0; i < len(DEFAULT_IMPORT); i += 2 {
code.WriteString(` import . "`)
code.WriteString(DEFAULT_IMPORT[i])
code.WriteString(`";`)
}
stage := STAGE_READY
for len(buf) > 0 {
p := bytes.IndexByte(buf, byte('\n'))
var line []byte
if p < 0 {
line = buf
buf = nil
} else {
line = buf[:p]
buf = buf[p+1:]
}
if len(line) == 0 {
code.WriteRune('\n')
continue
}
for {
switch stage {
case STAGE_READY:
if line[0] != '#' {
stage = STAGE_IMPORT
continue
}
line = nil
case STAGE_IMPORT:
trimmed := bytes.TrimSpace(line)
if len(trimmed) > 0 && !bytes.HasPrefix(trimmed, []byte("import ")) && !bytes.HasPrefix(trimmed, []byte("//")) {
stage = STAGE_MAIN
}
}
break
}
if stage == STAGE_MAIN {
appendInitAndMainHead(&code)
}
code.Write(line)
code.WriteRune('\n')
if stage == STAGE_MAIN {
break
}
}
if stage == STAGE_MAIN {
code.Write(buf)
} else {
appendInitAndMainHead(&code)
}
code.WriteString("\n}\n")
if opts.ShowSource {
fmt.Println(string(code.Bytes()))
}
// put the path of the script as Args[1] in the generated program
codeFn := genFilename(fn.Base())
if err := codeFn.WriteFile(code.Bytes(), 0644); err != nil {
return err
}
if !opts.NoClean {
defer codeFn.Remove()
}
exeFn := codeFn + ".exe" // to be compatible with Windows
cmd := villa.Path("go").Command("build", "-o", exeFn.S(), codeFn.S())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
return err
}
if !opts.NoClean {
defer exeFn.Remove()
}
if p, err := fn.Abs(); err == nil {
args = append([]string{p.S()}, args...)
} else {
args = append([]string{fn.S()}, args...)
}
cmd = exeFn.Command(args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err := cmd.Run()
ec := execCode(err)
if ec != 0 {
os.Exit(ec)
}
return err
}
func main() {
var opts Options
flag.BoolVar(&opts.ShowSource, "showsource", false, "Show generated source code")
flag.BoolVar(&opts.NoClean, "noclean", false, "No cleaning of generated files")
pSrcStr := flag.String("src", "", "Source code")
flag.Parse()
var src []byte
fn := villa.Path("noname")
args := flag.Args()
if *pSrcStr != "" {
src = []byte(*pSrcStr)
} else if len(flag.Args()) == 0 {
var err error
src, err = ioutil.ReadAll(os.Stdin)
if err != nil {
fmtp.Printfln("Failed: %v", err)
os.Exit(-1)
}
} else {
fn, args = villa.Path(flag.Args()[0]), flag.Args()[1:]
var err error
src, err = ioutil.ReadFile(fn.S())
if err != nil {
fmtp.Eprintfln("Failed: %v", err)
os.Exit(-1)
}
}
if err := Process(src, fn, args, opts); err != nil {
fmtp.Eprintfln("Failed: %v", err)
os.Exit(-1)
}
}