-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRun.hx
630 lines (551 loc) · 17.8 KB
/
Run.hx
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
// ==================================================================
// * Reflaxe Run.hx
//
// This is the script run when using `haxelib run reflaxe`
//
// It's main feature is generating a new project by copying the contents
// of the "newproject" folder into wherever the user prefers.
// ==================================================================
package;
using StringTools;
import haxe.io.Eof;
import haxe.io.Path;
import sys.FileSystem;
import sys.io.File;
/**
The commands that can be used with this script.
**/
final commands = {
help: {
desc: "Shows this message",
args: [],
act: (args) -> Sys.println(helpContent()),
example: "help",
order: 0
},
"new": {
desc: "Create a new Reflaxe project",
args: [],
act: (args: Array<String>) -> createNewProject(args),
example: "new Rust rs",
order: 1
},
test: {
desc: "Test your target on .hxml project",
args: ["hxml_path"],
act: (args: Array<String>) -> testProject(args),
example: "test test/Test.hxml",
order: 2
},
build: {
desc: "Build your project for distribution",
args: ["build_folder"],
act: (args: Array<String>) -> buildProject(args),
example: "build _Build",
order: 3
}
}
/**
The directory this command was run in.
**/
var commandRunDir: String = "";
/**
Main function.
**/
function main() {
final args = Sys.args();
commandRunDir = args.splice(args.length - 1, 1)[0];
final mainCommand = args.length < 1 ? "help" : args[0];
if(Reflect.hasField(commands, mainCommand)) {
Reflect.callMethod(commands, Reflect.getProperty(commands, mainCommand).act, [args.slice(1)]);
} else {
printlnRed("Could not find command: " + mainCommand + "\n");
commands.help.act(args);
}
}
/**
Get path relative to directory this command was run in.
**/
function getPath(p: String) {
return FileSystem.absolutePath(haxe.io.Path.join([commandRunDir, p]));
}
/**
Make the directory of path `p` if it doesn't exist.
**/
function makeDirIfNonExist(p: String) {
if(!FileSystem.exists(p)) {
FileSystem.createDirectory(p);
}
}
/**
Print in red or green.
**/
function printlnRed(msg: String) { Sys.println('\033[1;31m${msg}\033[0m'); }
function printlnGreen(msg: String) { Sys.println('\033[1;32m${msg}\033[0m'); }
function printlnGray(msg: String) { Sys.println('\033[1;30m${msg}\033[0m'); }
/**
Generate the content shown for the help command.
**/
function helpContent(): String {
var maxFieldSize = -1;
final commandNames = Reflect.fields(commands);
commandNames.sort((a, b) -> {
final i = Reflect.getProperty(commands, a)?.order ?? 9999;
final j = Reflect.getProperty(commands, b)?.order ?? 9999;
return i - j;
});
// Convert "commands" into an array
final data = [];
for(field in commandNames) {
final c = Reflect.getProperty(commands, field);
final args = c.args.map(c -> "<" + c + ">").join(" ");
final helpName = field + (args.length > 0 ? (" " + args) : "");
if(helpName.length > maxFieldSize) {
maxFieldSize = helpName.length;
}
data.push({ name: field, helpName: helpName, command: c });
}
// Load haxelib.json
final haxelibJson: { version: String, description: String } = haxe.Json.parse(sys.io.File.getContent("./haxelib.json"));
final picture = "/ ( ˘▽˘)っ♨ \\";
final title = '/ Reflaxe v${haxelibJson.version} \\';
// Ensure "credits" is longer than "title"
var credits = "by SomeRanDev (Robert Borghese)";
if(title.length > credits.length) {
final half = Math.floor((title.length - credits.length) / 2);
credits = StringTools.rpad(StringTools.lpad(credits, " ", half), " " , half);
}
credits = "/ " + credits + " \\";
// Helper
function space(count: Int, char: String = " ")
return StringTools.lpad("", char, count);
final spacing = space(Math.floor((credits.length - title.length) / 2) - 1);
final pictureSpacing = spacing + space(Math.floor((title.length - picture.length) / 2) - 1);
final lines = [
space(5) + pictureSpacing + "/\\/\\/\\/\\/\\",
space(4) + pictureSpacing + space(picture.length - 1, "="),
space(3) + pictureSpacing + picture,
space(3) + spacing + space(title.length - 2, "-"),
space(2) + spacing + title,
space(2) + space(credits.length - 2, "-"),
space(1) + credits,
space(credits.length + 2, "=")
];
// Make help content
return (
'${lines.join("\n")}
[ ~ Description ~ ]
${haxelibJson.description}
[ ~ Commands ~ ]
${
data
.map((d) -> " " + StringTools.rpad(d.helpName, " ", maxFieldSize + 5) + " " + d.command.desc)
.join("\n")
}
'
);
}
/**
Generate the new project.
**/
function createNewProject(args: Array<String>) {
// Intro message
printlnGreen("Let's get some info about the target we're generating code for!
Can you tell me...\n");
// Full Name
final fullName = args.length >= 1 ? args[0] : readName("Full name? (i.e: Rust, Kotlin, JavaScript)");
if(fullName == null) return;
// Ensure folder is available based on Full Name
final folderName = "reflaxe_" + fullName;
final folderPath = getPath(folderName);
if(sys.FileSystem.exists(folderPath)) {
printlnRed("Unfortunately this name cannot be used since there is already a directory named `" + folderName + "`. Please delete this folder or run this command somewhere else!
\n" + folderPath);
return;
}
// Abbreviated Name
final abbrevName = args.length >= 2 ? args[1] : readName("Abbreviated name? (i.e: rust, kt, js)");
if(abbrevName == null) return;
// File Extension
final extension = args.length >= 3 ? args[2] : readName("File extension for the files to generate?\nDo not include the dot! (i.e: rs, kt, js)");
if(extension == null) return;
// Project Type
final type = args.length >= 4 ? convertStringToProjectType(args[3]) : readProjectType();
if(type == null) return;
// ---
// Verify Info
Sys.println("---\n");
Sys.println('Full Name\n ${fullName}\n
Abbreviated Name\n ${abbrevName}\n
File Extension\n .${extension}\n
Transpile Type\n ${Std.string(type)}');
final isCorrect = if(args.length < 4) {
Sys.print("\nIs this OK? (yes)\n>");
try { Sys.stdin().readLine().toLowerCase(); } catch(e: Eof) { return; }
} else {
"";
}
if(isCorrect == "" || isCorrect == "y" || isCorrect == "yes") {
Sys.println("");
printlnGreen("Perfect! Generating project in subfolder: " + folderName);
copyProjectFiles(folderPath, fullName, abbrevName, extension, type);
} else {
printlnRed("\nOkay! Cancelling....");
}
}
/**
Read the user input and ensure its valid.
If canceled using CTRL+C, returns null.
**/
function readName(msg: String): Null<String> {
final regex = ~/^[a-zA-Z][a-zA-Z0-9_]*$/;
Sys.println(msg);
var result = "";
while(true) {
Sys.print("> ");
try {
result = Sys.stdin().readLine().trim();
} catch(e: Eof) {
return null;
}
if(regex.match(result)) {
Sys.println("");
break;
} else {
printlnRed('`${result}` is invalid! It name must only contain alphanumeric characters or underscores. Please try again:');
}
}
return result;
}
/**
Used as the result for `readProjectType`.
**/
enum ProjectType {
Direct;
Intermediate;
}
/**
Ask the user their desired project type.
**/
function readProjectType(): Null<ProjectType> {
// Print the message
Sys.println("What type of compiler would you like to make? (d)irect or (i)ntermediate?
If you're not sure, I recommend using \"direct\"!");
// Find the result
final regex = ~/^(?:d|i|direct|intermediate)$/;
var input = "";
var result = null;
while(true) {
Sys.print("> ");
try {
input = Sys.stdin().readLine().trim();
} catch(e: Eof) {
return null;
}
if(regex.match(input)) {
result = convertStringToProjectType(input);
Sys.println("");
break;
} else {
printlnRed('`${input}` is invalid! Please input either \"d\" or \"i\".');
}
}
return result;
}
/**
Converts a given user-input `String` to its correlating `ProjectType` value.
**/
function convertStringToProjectType(input: String) {
return switch(input) {
case "direct" | "d": Direct;
case "intermediate" | "i": Intermediate;
case _: {
printlnRed('`${input}` is an invalid project type.');
null;
}
}
}
/**
Actually copies the project files.
**/
function copyProjectFiles(folderPath: String, fullName: String, abbrName: String, ext: String, type: ProjectType) {
if(!FileSystem.exists("newproject")) {
printlnRed("Could not find `newproject` directory in Reflaxe installation folder.");
return;
}
copyDir("newproject", folderPath, { fullName: fullName, abbrName: abbrName, ext: ext, type: type });
}
/**
Recursive function for copying files.
Handles special cases.
**/
function copyDir(src: String, dest: String, data: { fullName: String, abbrName: String, ext: String, type: ProjectType }) {
// Check if directory is exclusive to a project type.
final dirRegex = ~/\.(direct|intermediate)$/i;
if(dirRegex.match(src)) {
if(dirRegex.matched(1).toLowerCase() != Std.string(data.type).toLowerCase()) {
return;
} else {
// Remove the .direct|intermediate from the destination.
dest = dirRegex.replace(dest, "");
}
}
// Make directory
makeDirIfNonExist(dest);
// Copy files
for(file in FileSystem.readDirectory(src)) {
final filePath = Path.join([src, file]);
var destFile = Path.join([dest, file]);
if(FileSystem.isDirectory(filePath)) {
switch(file) {
// rename src/langcompiler
case "langcompiler":
destFile = Path.join([dest, data.abbrName.toLowerCase() + "compiler"]);
case "LANG":
destFile = Path.join([dest, data.abbrName.toLowerCase()]);
// ignore test/out and _Build
case "out" | "_Build":
continue;
case _:
}
copyDir(filePath, destFile, data);
} else {
final content = File.getContent(filePath);
File.saveContent(destFile, replaceFileContent(content, data));
}
}
}
/**
Replaces content from the "newproject/" files
to match with the user config.
**/
function replaceFileContent(content: String, data: { fullName: String, abbrName: String, ext: String }): String {
final lowerAbbrName = data.abbrName.toLowerCase();
return content.replace("langcompiler", lowerAbbrName + "compiler")
.replace("package lang", "package " + lowerAbbrName)
.replace("__lang__", "__" + lowerAbbrName + "__")
.replace("lang-output", lowerAbbrName + "-output")
.replace("LANGUAGE", data.fullName)
.replace("LANG", data.abbrName)
.replace("EXTENSION", data.ext);
}
/**
Checks if the directory the command was ran in is a Reflaxe project.
If it is, a JSON object of the haxelib.json is returned.
Otherwise, `null` is returned.
**/
function ensureIsReflaxeProject(): Null<Dynamic> {
var haxelibJson: Dynamic = null;
final haxelibJsonPath = Path.join([commandRunDir, "haxelib.json"]);
if(!FileSystem.exists(haxelibJsonPath)) {
printlnRed("haxelib.json file not found!\nThis command must be run in a Reflaxe project.");
} else {
final haxelibJsonContent = File.getContent(haxelibJsonPath);
haxelibJson = haxe.Json.parse(haxelibJsonContent);
if(haxelibJson.reflaxe == null) {
printlnRed("haxelib.json expected to contain Reflaxe project information.");
printlnRed("Please add the following to your haxelib.json to use this command:");
Sys.println('"reflaxe": {
"name": "<Your Language Name>",
"abbr": "<Your Abbreviated Language Name>",
"stdPaths": []
}');
return null;
}
return haxelibJson;
}
return null;
}
/**
The function for running the `test` command.
**/
function testProject(args: Array<String>) {
final path = if(args.length == 0) {
Sys.println("No .hxml path provided, using test/Test.hxml\n");
"test/Test.hxml";
} else if(args.length == 1) {
args[0];
} else {
printlnRed("Too many arguments provided.");
return;
}
final haxelibJson = ensureIsReflaxeProject();
if(haxelibJson == null) return;
// Update "cwd" to ACTUAL path that ran command before validating path
Sys.setCwd(commandRunDir);
// Validate the path
if(!FileSystem.exists(path)) {
return printlnRed("`" + path + "` does not exist!");
} else if(Path.extension(path) != "hxml") {
return printlnRed("`" + path + "` must be a .hxml file!");
}
// Get current cwd
// Remember, the command directory is stored in `commandRunDir`, not `Sys.getCwd()`!!
var cwd = commandRunDir;
final hxmlDir = Path.directory(path);
// Convert cwd to relative path if possible
if(!Path.isAbsolute(hxmlDir)) {
final folders = ~/\/\\/g.split(hxmlDir);
cwd = Path.join(folders.map(f -> ".."));
}
// Change cwd
Sys.setCwd(Path.join([commandRunDir, hxmlDir]));
printlnGray("cd " + hxmlDir);
// Generate arguments
final getProjPath = (p: ...String) -> Path.normalize(Path.join([cwd].concat(p.toArray())));
final haxeArgs = [
Path.withoutDirectory(path),
"-lib reflaxe",
"-D reflaxe_measure",
getProjPath("extraParams.hxml"),
"-p " + getProjPath(haxelibJson.classPath)
];
for(stdPath in (haxelibJson.reflaxe?.stdPaths ?? [])) {
haxeArgs.push("-p " + getProjPath(stdPath));
}
// Run Haxe project
printlnGray("haxe " + haxeArgs.join(" "));
final exitCode = Sys.command("haxe", haxeArgs.join(" ").split(" "));
// Print exit code
final msg = "Haxe compiler returned exit code " + exitCode;
if(exitCode == 0) printlnGreen(msg);
else printlnRed(msg);
}
/**
The function for running the `build` command.
**/
function buildProject(args: Array<String>) {
// Validate project, get haxelib.json
final haxelibJson = ensureIsReflaxeProject();
if(haxelibJson == null) return;
final autoConfirmDelete = args.remove("--deleteOldFolder");
// Get destination folder
final destFolder = if(args.length == 0) {
Sys.println("No build folder path provided, using _Build/\n");
"_Build";
} else if(args.length == 1) {
args[0];
} else {
printlnRed("Too many argument provided.");
return;
}
// Ensure destination folder name valid
if(!~/^[A-Za-z0-9_]+$/.match(destFolder)) {
printlnRed("`" + destFolder + "` is not a valid folder name!\nPlease only use alphanumeric characters and underscores!");
return;
}
// Ensure destination folder relative to cwd
final destFolder = Path.join([commandRunDir, destFolder]);
// Check if destination folder already exists
if(FileSystem.exists(destFolder)) {
if(!FileSystem.isDirectory(destFolder)) {
printlnRed("There is already a file named `" + destFolder + "`.\nPlease input a different path for the build folder.");
return;
} else {
final response = if(autoConfirmDelete) {
"y";
} else {
// If a folder already exists, ask to delete
Sys.println("There is already a folder named `" + destFolder + "`.\nWould you like to delete it? (yes/no)");
Sys.print("> ");
try { Sys.stdin().readLine().toLowerCase(); } catch(e: Eof) { return; }
}
if(response == "yes" || response == "y") {
Sys.println("Deleting...\n");
deleteDir(destFolder);
} else {
Sys.println("Okay! Cancelling build!");
return;
}
}
}
// Make destination folder
makeDirIfNonExist(destFolder);
// Copy source files if possible
final classPath = haxelibJson.classPath;
if(classPath.length != null && classPath.length > 0) {
// Copy class path
final dirNormalized = Path.addTrailingSlash(Path.normalize(commandRunDir));
final classPathSrc = Path.join([commandRunDir, classPath]);
final classPathDest = Path.join([destFolder, classPath]);
copyDirContent(classPathSrc, classPathDest, dirNormalized);
Sys.println("Copying class path: " + Path.addTrailingSlash(classPath));
// Copy std paths
final stdPaths: Array<String> = cast (haxelibJson.reflaxe?.stdPaths ?? []);
for(stdPath in stdPaths) {
final stdPathSrc = Path.join([commandRunDir, stdPath]);
final ext = StringTools.endsWith(Path.removeTrailingSlashes(stdPath), "_std") ? ".cross.hx" : null;
copyDirContent(stdPathSrc, classPathDest, dirNormalized, stdPaths, ext);
Sys.println("Copying std path: " + Path.addTrailingSlash(stdPath));
}
// Copy extra files
function copyExtraFile(file: String, printError: Bool) {
final filePath = Path.join([commandRunDir, file]);
if(FileSystem.exists(filePath)) {
File.copy(filePath, Path.join([destFolder, file]));
Sys.println("Copying file: " + file);
} else if(printError) {
printlnRed("Could not find file: " + file + "; ignoring...");
}
}
// Files that should exist
for(file in ["haxelib.json", "LICENSE", "README.md"]) {
copyExtraFile(file, true);
}
// Files that are okay to not exist
for(file in ["extraParams.hxml", "Run.hx", "run.n"]) {
copyExtraFile(file, false);
}
// Print success
Sys.println("");
printlnGreen("Build successful:\n" + destFolder);
} else {
// Print failure
printlnRed("\"classPath\" must be defined in haxelib.json to build the project.");
}
}
/**
Util function for recursively copying directories containing source files.
`ignore` is a list of directories that should not be copied.
`replaceExt` replaces the extension for all copied source files if provided.
**/
function copyDirContent(from: String, to: String, basePath: String, ignore: Null<Array<String>> = null, replaceExt: Null<String> = null) {
if(FileSystem.exists(from)) {
for(file in FileSystem.readDirectory(from)) {
final path = Path.join([from, file]);
var dest = Path.join([to, file]);
if(!FileSystem.isDirectory(path)) {
if(replaceExt != null) {
dest = Path.withoutExtension(dest) + replaceExt;
}
File.copy(path, dest);
} else {
if(ignore != null && ignore.contains(Path.removeTrailingSlashes(path.replace(basePath, "")))) {
continue;
}
final d = Path.addTrailingSlash(path);
final d2 = Path.addTrailingSlash(dest);
makeDirIfNonExist(d2);
copyDirContent(d, d2, basePath, ignore, replaceExt);
}
}
}
}
/**
Deletes directory even if it has content within it.
Based on:
https://ashes999.github.io/learnhaxe/recursively-delete-a-directory-in-haxe.html
**/
function deleteDir(path: String) {
if(FileSystem.exists(path) && FileSystem.isDirectory(path)) {
final entries = FileSystem.readDirectory(path);
for(entry in entries) {
if (FileSystem.isDirectory(path + "/" + entry)) {
deleteDir(path + "/" + entry);
FileSystem.deleteDirectory(path + "/" + entry);
} else {
FileSystem.deleteFile(path + "/" + entry);
}
}
}
}