-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
547 lines (540 loc) · 16.7 KB
/
main.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//go:build !wasm && !js
package main
import (
"bufio"
"fmt"
"github.com/Bedrock-OSS/go-burrito/burrito"
"github.com/MCDevKit/jsonte/jsonte"
"github.com/MCDevKit/jsonte/jsonte/functions"
"github.com/MCDevKit/jsonte/jsonte/json"
"github.com/MCDevKit/jsonte/jsonte/types"
"github.com/MCDevKit/jsonte/jsonte/utils"
"github.com/gammazero/deque"
"github.com/gobwas/glob"
"go.uber.org/zap"
"math/rand"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
var (
commit string
version = "0.0.0"
date string
buildSource = "DEV"
)
func main() {
types.Init()
functions.Init()
env, b := os.LookupEnv("DEBUG")
debug := false
if b && (env == "true" || env == "1") {
debug = true
}
silent := false
removeSrc := false
minify := false
scope := make([]string, 0)
out := ""
include := make([]string, 0)
exclude := make([]string, 0)
ipcName := "jsonte"
seed := time.Now().UnixNano()
cacheAll := false
app := NewApp()
app.BoolFlag(Flag{
Name: "debug",
Usage: "Enable debug mode",
}, &debug)
app.BoolFlag(Flag{
Name: "safe-mode",
Usage: "Enable safe mode",
}, &functions.SafeMode)
app.BoolFlag(Flag{
Name: "server-mode",
Usage: "Enable server mode",
}, &functions.ServerMode)
app.BoolFlag(Flag{
Name: "silent",
Usage: "Enable silent mode",
}, &silent)
app.BoolFlag(Flag{
Name: "remove-src",
Usage: "Remove source files after compilation",
}, &removeSrc)
app.BoolFlag(Flag{
Name: "minify",
Usage: "Minify the output",
}, &minify)
app.StringSliceFlag(Flag{
Name: "scope",
Usage: "Scope of the output",
}, &scope)
app.StringFlag(Flag{
Name: "out",
Usage: "Output file",
}, &out)
app.StringSliceFlag(Flag{
Name: "include",
Usage: "Include files",
}, &include)
app.StringSliceFlag(Flag{
Name: "exclude",
Usage: "Exclude files",
}, &exclude)
app.StringFlag(Flag{
Name: "cache-dir",
Usage: "Directory for the cache",
}, &json.CacheDir)
app.StringFlag(Flag{
Name: "ipc-name",
Usage: "Name for the IPC named pipe",
}, &ipcName)
app.IntFlag(Flag{
Name: "seed",
Usage: "Seed for the random number generator",
}, &seed)
app.BoolFlag(Flag{
Name: "cache-all",
Usage: "Cache all function calls",
}, &cacheAll)
app.Action(Action{
Name: "compile",
Function: func(args []string) error {
functions.SetCacheAll(cacheAll)
outFile := ""
if out != "" {
stat, err := os.Stat(out)
if err != nil {
if os.IsNotExist(err) {
err := os.MkdirAll(out, 0755)
if err != nil {
return burrito.WrapError(err, "An error occurred while creating the output directory")
}
} else {
return burrito.WrapError(err, "An error occurred while reading the output file")
}
} else if !stat.IsDir() {
return burrito.WrappedErrorf("The output file '%s' is not a directory", out)
}
outFile, err = filepath.Abs(out)
}
object, err := getScope(scope, -1)
if err != nil {
return burrito.WrapError(err, "An error occurred while reading the scope")
}
fileSets, err := getFileList(args, include, exclude)
if err != nil {
return err
}
// Process modules
modules := map[string]jsonte.JsonModule{}
for base, files := range fileSets {
for _, file := range files {
if strings.HasSuffix(file, ".modl") {
bytes, err := os.ReadFile(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the module file %s", file)
}
module, err := jsonte.LoadModule(string(bytes), object, -1)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while loading the module file %s", file)
}
modules[module.Name.StringValue()] = module
rel, err := filepath.Rel(base, file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while relativizing the output file name")
}
utils.Logger.Infof("Loaded module %s", rel)
if removeSrc {
err = os.Remove(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while removing the module file %s", file)
}
}
}
}
}
// Process templates
for base, files := range fileSets {
for _, file := range files {
if strings.HasSuffix(file, ".templ") {
utils.Logger.Infof("Templating file %s", file)
bytes, err := os.ReadFile(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the template file %s", file)
}
template, err := jsonte.Process(strings.TrimSuffix(filepath.Base(file), filepath.Ext(file)), string(bytes), object, modules, -1)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while processing the template file %s", file)
}
toString := types.ToPrettyString
if minify {
toString = types.ToString
}
for _, fileName := range template.Keys() {
content := template.Get(fileName)
filename := filepath.Dir(file) + "/" + fileName + ".json"
if outFile != "" {
filename, err = filepath.Rel(base, filename)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while creating the output file name")
}
filename = filepath.Join(outFile, base, filename)
rel, err := filepath.Rel(outFile, filename)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while relativizing the output file name")
}
utils.Logger.Infof("Writing file %s", filepath.Clean(rel))
} else {
utils.Logger.Infof("Writing file %s", filepath.Clean(filename))
}
err = os.MkdirAll(filepath.Dir(filename), 0755)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while creating the output directory %s", filepath.Dir(filename))
}
err = os.WriteFile(filename, []byte(toString(content)), 0644)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while writing the output file %s", filename)
}
}
if removeSrc {
err = os.Remove(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while removing the template file %s", file)
}
}
}
}
}
//Process functions
for base, files := range fileSets {
for _, file := range files {
if strings.HasSuffix(file, ".mcfunction") {
bytes, err := os.ReadFile(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the mcfunction file %s", file)
}
fileName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
output, err := jsonte.ProcessMCFunction(string(bytes), object)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while processing the mcfunction file %s", file)
}
filename := filepath.Dir(file) + "/" + fileName + ".mcfunction"
if outFile != "" {
filename, err = filepath.Rel(base, filename)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while creating the output file name")
}
filename = filepath.Join(outFile, base, filename)
rel, err := filepath.Rel(outFile, filename)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while relativizing the output file name")
}
utils.Logger.Infof("Writing file %s", filepath.Clean(rel))
} else {
utils.Logger.Infof("Writing file %s", filepath.Clean(filename))
}
err = os.MkdirAll(filepath.Dir(filename), 0755)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while creating the output directory %s", filepath.Dir(filename))
}
err = os.WriteFile(filename, []byte(output), 0644)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while writing the output file %s", filename)
}
}
}
}
//Process lang files
for base, files := range fileSets {
for _, file := range files {
if strings.HasSuffix(file, ".lang") {
bytes, err := os.ReadFile(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the mcfunction file %s", file)
}
fileName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
output, err := jsonte.ProcessLangFile(string(bytes), object)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while processing the mcfunction file %s", file)
}
filename := filepath.Dir(file) + "/" + fileName + ".lang"
if outFile != "" {
filename, err = filepath.Rel(base, filename)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while creating the output file name")
}
filename = filepath.Join(outFile, base, filename)
rel, err := filepath.Rel(outFile, filename)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while relativizing the output file name")
}
utils.Logger.Infof("Writing file %s", filepath.Clean(rel))
} else {
utils.Logger.Infof("Writing file %s", filepath.Clean(filename))
}
err = os.MkdirAll(filepath.Dir(filename), 0755)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while creating the output directory %s", filepath.Dir(filename))
}
err = os.WriteFile(filename, []byte(output), 0644)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while writing the output file %s", filename)
}
}
}
}
return nil
},
})
app.Action(Action{
Name: "eval",
Usage: "Evaluate a JSON expression or run a REPL",
Function: func(args []string) error {
functions.SetCacheAll(cacheAll)
object, err := getScope(scope, -1)
if err != nil {
return burrito.WrapError(err, "An error occurred while reading the scope")
}
if len(args) == 0 {
repl(object)
} else {
expression := strings.Join(args, " ")
s := deque.Deque[*types.JsonObject]{}
s.PushBack(object)
value, err := jsonte.Eval(expression, s, "#")
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while evaluating the expression")
}
fmt.Println(types.ToPrettyString(value.Value))
}
return nil
},
})
app.Action(Action{
Name: "script",
Usage: "Evaluate a JSON expression or run a REPL",
Function: func(args []string) error {
functions.SetCacheAll(cacheAll)
object, err := getScope(scope, -1)
if err != nil {
return burrito.WrapError(err, "An error occurred while reading the scope")
}
if len(args) == 0 {
return burrito.WrapErrorf(err, "No script file specified")
} else {
file, err := os.ReadFile(args[0])
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the script file")
}
file, err = json.ConvertToUTF8(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the script file")
}
s := deque.Deque[*types.JsonObject]{}
s.PushBack(object)
value, err := jsonte.EvalScript(string(file), s, "#")
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while running the script")
}
fmt.Println(types.ToPrettyString(value.Value))
}
return nil
},
})
app.Action(Action{
Name: "version",
Usage: "Print the version info",
Function: func(args []string) error {
fmt.Println("jsonte version " + version)
if buildSource == "DEV" {
fmt.Println("Development build")
}
if commit != "" {
fmt.Println("Commit: " + commit)
}
if date != "" {
fmt.Println("Built at " + date)
}
return nil
},
})
app.Action(Action{
Name: "ipc",
Usage: "Start an IPC server",
Function: func(args []string) error {
functions.SetCacheAll(cacheAll)
object, err := getScope(scope, -1)
if err != nil {
return burrito.WrapError(err, "An error occurred while reading the scope")
}
return StartIPC(ipcName, object)
},
})
app.Action(Action{
Name: "docgen",
Hidden: true,
Usage: "Generate documentation",
Function: func(args []string) error {
return functions.GenerateDocs()
},
})
err := app.Run(os.Args, func() {
if debug && silent {
utils.InitLogging(zap.DebugLevel)
utils.Logger.Warn("--debug and --silent are mutually exclusive")
} else if debug {
utils.InitLogging(zap.DebugLevel)
} else if silent {
utils.InitLogging(zap.WarnLevel)
} else {
utils.InitLogging(zap.InfoLevel)
}
rand.Seed(seed)
})
if err != nil {
if utils.Logger == nil {
utils.InitLogging(zap.DebugLevel)
}
utils.Logger.Error(err)
os.Exit(1)
}
}
func getScope(scope []string, timeout int64) (*types.JsonObject, error) {
assertionFiles := map[string]string{}
result := types.NewJsonObject()
for _, path := range scope {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
utils.Logger.Warnf("Skipping non-existent scope file '%s'", path)
return nil
}
return burrito.WrapErrorf(err, "An error occurred while reading the scope file '%s'", path)
}
if !info.IsDir() {
if strings.HasSuffix(path, ".json") {
file, err := os.ReadFile(path)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the scope file '%s'", path)
}
json, err := types.ParseJsonObject(file)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while parsing the scope file '%s'", path)
}
err = jsonte.VerifyReservedNames(json, path+"#/")
result = types.MergeObject(result, json, false, "#")
} else if strings.HasSuffix(path, ".assert") {
file, err := os.ReadFile(path)
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the assertion file '%s'", path)
}
assertionFiles[path] = string(file)
} else {
utils.Logger.Debugf("Skipping non-scope file '%s'", path)
}
}
return nil
})
if err != nil {
return types.NewJsonObject(), burrito.WrapError(err, "An error occurred while reading the scope files")
}
}
for path, file := range assertionFiles {
err := jsonte.ProcessAssertionsFile(path, file, result, timeout)
if err != nil {
return types.NewJsonObject(), burrito.PassError(err)
}
}
return result, nil
}
func getFileList(paths, include, exclude []string) (map[string][]string, error) {
result := map[string][]string{}
includes := make([]glob.Glob, 0)
excludes := make([]glob.Glob, 0)
pathRegex, err := regexp.Compile("[/\\\\]")
if err != nil {
// Should never happen as it's constant
return nil, burrito.WrapError(err, "An error occurred while compiling the path separator regex")
}
for _, i := range include {
g, err := glob.Compile(pathRegex.ReplaceAllString(i, "/"))
if err != nil {
return nil, burrito.WrapErrorf(err, "An error occurred while compiling the include pattern %s", i)
}
includes = append(includes, g)
}
for _, e := range exclude {
g, err := glob.Compile(pathRegex.ReplaceAllString(e, "/"))
if err != nil {
return nil, burrito.WrapErrorf(err, "An error occurred while compiling the exclude pattern %s", e)
}
excludes = append(excludes, g)
}
for _, p := range paths {
files := make([]string, 0)
_, err := os.Stat(p)
if err != nil {
if os.IsNotExist(err) {
return nil, burrito.WrappedErrorf("The path '%s' does not exist", p)
}
return nil, burrito.WrapErrorf(err, "An error occurred while reading the path %s", p)
}
err = filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
if err != nil {
return burrito.WrapErrorf(err, "An error occurred while reading the path %s", p)
}
if !info.IsDir() {
if !strings.HasSuffix(path, ".templ") && !strings.HasSuffix(path, ".modl") && !strings.HasSuffix(path, ".mcfunction") && !strings.HasSuffix(path, ".lang") {
return nil
}
for _, g := range includes {
if g.Match(pathRegex.ReplaceAllString(path, "/")) {
files = append(files, path)
return nil
}
}
for _, g := range excludes {
if g.Match(pathRegex.ReplaceAllString(path, "/")) {
return nil
}
}
if len(include) == 0 {
files = append(files, path)
}
}
return nil
})
if err != nil {
return nil, burrito.WrapErrorf(err, "An error occurred while reading input files from %s", p)
}
result[p] = files
}
return result, nil
}
func repl(scope *types.JsonObject) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("> ")
s := deque.Deque[*types.JsonObject]{}
s.PushBack(scope)
for {
read, _ := reader.ReadString('\n')
text := strings.TrimRight(read, "\n\r")
if text == "exit" {
break
}
eval, err := jsonte.Eval(text, s, "#/")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(types.ToString(eval.Value))
}
if !eval.VariableScope.IsEmpty() {
s.PushBack(eval.VariableScope)
}
fmt.Print("> ")
}
}