-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboop.ts
1331 lines (1093 loc) · 34.3 KB
/
boop.ts
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as fs from 'https://deno.land/std@0.135.0/fs/mod.ts';
import * as path from "https://deno.land/std@0.136.0/path/mod.ts";
// import * as shellQuote from "https://raw.githubusercontent.com/shopstic/ts-shell-quote/master/index.ts";
import * as shellQuote from "https://raw.githubusercontent.com/ProPuke/ts-shell-quote/fix/invalid-parse-return-type/index.ts";
import * as color from "https://deno.land/std@0.136.0/fmt/colors.ts";
enum Verbosity {
none,
tasks,
tasksAndCommands,
debug
}
const programName = import.meta.url.match(/(?:^|\/)([^\\\/\.]+)(\.[^\\\/\.]*)?$/)?.[1]||'boop';
const programVersion = `1.2.0`;
const scriptName = 'tasks.boop';
let taskName = '';
let dryRun = false;
let jobs = 0;
let watch = false;
let verbosity = Verbosity.tasks;
const flags:string[] = [];
function print_help() {
console.log(`Usage: ${programName} [OPTION]... [TASK] [FLAGS]...`);
console.log(`Run the TASK in the ${scriptName} script, passing it specified FLAGS`);
console.log();
console.log(` -d, --dry-run do not actually execute commands (useful with --verbose)`);
console.log(` -h, --help display this help and exit`);
console.log(` -j [N], --jobs=[N] set how many tasks may be executed in parallel at once (defaults to 0)`);
console.log(` N=0 - run no more than the number of cpu cores + 1`);
console.log(` N=X - run no more than x`);
console.log(` -v [N], --verbose[=N] set verbosity (defaults to 1)`);
console.log(` N=0 - print no additional information`);
console.log(` N=1 - print which tasks are being executed`);
console.log(` N=2 - ...also print the commands which are being executed`);
console.log(` N=3 - ...also print debug info about script lines being executed`);
console.log(` -w, --watch watch all files for changes and restart task whenever they change`);
console.log(` --version display version information and exit`);
}
function print_version() {
console.log(`Boop! v${programVersion}`);
}
let _log_verbose_last = '';
function log_verbose(allowRepeat:boolean, line:string) {
if(!allowRepeat&&_log_verbose_last==line) return;
console.log(line);
_log_verbose_last = line;
}
let _log_status_last = '';
function log_status_action(line:string) {
if(_log_status_last==line) return;
console.error(color.brightYellow(`» ${line}`));
_log_status_last = line;
}
function log_status_failure(line:string) {
console.error(color.red(`✖ ${line}`));
}
function log_status_success(line:string) {
console.log(color.green(`✓ ${line}`));
}
const _file_search_cache = new Map<string, Promise<fs.WalkEntry[]>>();
function clear_file_search_cache() {
_file_search_cache.clear();
}
async function file_search(glob:string) {
const existing = _file_search_cache.get(glob);
if(existing){
return existing;
}
const items = (async() => {
const items:fs.WalkEntry[] = [];
for await(const item of fs.expandGlob(glob, { extended:false, globstar:true })){
items.push(item);
}
return items;
})();
_file_search_cache.set(glob, items);
return items;
}
const _file_date_cache = new Map<string, number|null>();
function clear_file_date_cache() {
_file_date_cache.clear();
}
async function file_date(path:string, useCache = true) {
if(useCache){
const existing = _file_date_cache.get(path);
if(existing){
return existing;
}
}
let date:number|null = null;
try{
const stat = await Deno.stat(path);
if(stat.isFile&&stat.mtime){
date = stat.mtime.valueOf();
}
}catch(error){}
_file_date_cache.set(path, date);
return date;
}
function get_glob_dir(glob:string):string {
return path.resolve(path.dirname(glob.replace(/(^|\/)\*\*\/.*/g, '$1*.*')));
}
function get_basedirs_of_dirs(dirs:string[]):string[] {
// remove dir entries nested within others (relative paths without ../ or /)
for(let i=0;i<dirs.length;i++){
const dirA = dirs[i];
for(let i2=0;i2<dirs.length;i2++){
if(i==i2) continue;
const dirB = dirs[i2];
const relative = path.relative(dirA, dirB);
if(relative&&!relative.startsWith('..')&&!path.isAbsolute(relative)){
dirs.splice(i2, 1);
if(i2<i) i--;
i2--;
continue;
}
}
}
return dirs;
}
class JobPool {
readonly limit:number;
#queue:{tags:Symbol[], fulfill:(run:boolean)=>void}[] = [];
#activeJobs = 0;
#jobsRan = 0;
#cancelledTags:Symbol[] = [];
constructor(limit:number) {
this.limit = limit;
}
get activeJobs() { return this.#activeJobs; }
get jobsRan() { return this.#jobsRan; }
async begin_job(tags:Symbol[] = []) {
//check to make sure the tags aren't cancelled
for(const cancelled of this.#cancelledTags){
if(tags.includes(cancelled)){
return false;
}
}
if(this.#activeJobs>=this.limit){
let fulfill!:(run:boolean)=>void;
const promise = new Promise<boolean>(function(resolve){ fulfill=resolve; });
this.#queue.push({tags:[], fulfill});
const next = await promise;
// check in case the tags were cancelled while waiting
for(const cancelled of this.#cancelledTags){
if(tags.includes(cancelled)){
return false;
}
}
return next;
}
this.#activeJobs++;
return true;
}
async end_job() {
this.#activeJobs--;
this.#jobsRan++;
const queued = this.#queue.shift();
if(queued){
queued.fulfill(true);
}
}
cancel_remaining() {
let queued:{tags:any[], fulfill:(run:boolean)=>void}|undefined;
while(queued = this.#queue.shift()){
queued.fulfill(false);
}
}
cancel_tag(tag:Symbol, blacklist = true) {
if(blacklist){
this.#cancelledTags.push(tag);
}
for(let i=0;i<this.#queue.length;i++){
const queued = this.#queue[i];
if(queued.tags.includes(tag)){
this.#queue.splice(i--, 1);
queued.fulfill(false);
}
}
let queued:{tags:any[], fulfill:(run:boolean)=>void}|undefined;
while(queued = this.#queue.shift()){
queued.fulfill(false);
}
}
}
for(let i=0;i<Deno.args.length;i++){
const arg = Deno.args[i];
if(arg[0]=='-'){
switch(arg){
case '-h':
case '--help':
print_help();
Deno.exit(0);
break;
case '-d':
case '--dry-run':
dryRun = true;
break;
case '-j': {
const next = i+1<Deno.args.length?Deno.args[i+1]:null;
const value = next!==null?parseInt(next, 10):NaN;
if(isNaN(value)){
jobs = 0;
}else if(value>=0){
jobs = value;
i++;
}else{
console.error(`Invalid job limit: ${value}`);
}
} break;
case '-v': {
const next = i+1<Deno.args.length?Deno.args[i+1]:null;
const value = next!==null?parseInt(next, 10):NaN;
if(isNaN(value)){
verbosity = Verbosity.tasks;
}else{
i++;
switch(value){
case 0:
verbosity = Verbosity.none;
break;
case 1:
verbosity = Verbosity.tasks;
break;
case 2:
verbosity = Verbosity.tasksAndCommands;
break;
case 3:
verbosity = Verbosity.debug;
break;
default:
console.error(`Invalid verbosity level: ${value}`)
console.log();
print_help();
Deno.exit(1);
}
}
} break;
case '--verbose=0':
verbosity = Verbosity.none;
break;
case '--verbose':
case '--verbose=1':
verbosity = Verbosity.tasks;
break;
case '--verbose=2':
verbosity = Verbosity.tasksAndCommands;
break;
case '--verbose=3':
verbosity = Verbosity.debug;
break;
case '-w':
case '--watch':
watch = true;
break;
case '--version':
print_version();
Deno.exit(0);
break;
default: {
let match;
if(match=arg.match(/^--jobs=(\S+)/)){
const value = parseInt(match[1], 10);
if(value>=0){
jobs = value;
}else{
console.error(`Invalid job limit: ${value}`);
console.log();
print_help();
Deno.exit(1);
}
}
console.error(`Invalid option: ${arg}`);
console.log();
print_help();
Deno.exit(1);
}
}
}else{
if(!taskName){
taskName = arg;
}else{
flags.push(arg);
}
}
}
if(!taskName){
print_help();
Deno.exit(0);
}
if(jobs<1){
jobs = navigator.hardwareConcurrency+1;
}
const runQueue = new JobPool(jobs);
function params_parse(params:string):string[] {
const parsed = shellQuote.parse(params, Deno.env.toObject());
const args:string[] = [];
for(const term of parsed){
if(typeof term == 'string'){
args.push(term);
}else if('op' in term && term.pattern){
args.push(term.pattern);
}
}
return args;
}
function params_quote(params:string[]):string {
return shellQuote.quote(params);
}
async function run_process(tags:any[], args:string[], cwd?:string):Promise<true|false|'aborted'> {
if(!await runQueue.begin_job(tags)) return 'aborted';
let success = false;
try{
const process = Deno.run({
cmd: args,
cwd
});
success = (await process.status()).success;
}catch(error){
console.error(error.message);
}
await runQueue.end_job();
return success;
}
async function evaluate_process(args:string[]):Promise<string|false> {
try{
const process = Deno.run({
cmd: args,
stdout: 'piped',
stderr: 'piped',
stdin: 'null'
});
const success = (await process.status()).success;
if(!success){
log_status_failure(`${color.bold('Failure')} executing: ${params_quote(args)}`);
return false;
}
const output = (new TextDecoder).decode(await process.output());
return output;
}catch(error){
console.error(error.message);
return false;
}
}
type ScriptLine = {
lineNumber:number;
indent:number;
source:string;
};
type ParsedLine = {
type: 'run',
optional: boolean,
command: string,
source: string,
debugVars: string
} | {
type: 'cd',
path: string,
source: string,
}
class ParseError extends Error {
constructor(public lineNumber:number, error:string){
super(error);
}
}
type Task = {
name: string,
providedFiles: string[],
taskDependenciesByName: { optional: boolean, name: string }[],
taskDependencies: { optional: boolean, task: Task }[],
fileDependencies: string[],
netProvidedFiles: string[],
netFileDependencies: string[],
parsedLines: ParsedLine[]
};
type ScriptExecution = {cancel:()=>void, promise:Promise<true|false|'aborted'>};
class Script {
readonly lines:ScriptLine[] = [];
readonly tasks:Task[] = [];
readonly globs:string[] = [];
readonly modifiedFiles:string[] = [];
currentJobs = new WeakMap<Task, Promise<boolean|'aborted'>>();
constructor(source:string= '') {
let i = 0;
for(const line of source.split('\n')){
if(!line){
i++;
continue;
}
const indent = (line.match(/^([ \t]*)/)?.[1]||'').replaceAll(' ', '\t').length;
this.lines.push({lineNumber:i+1, indent, source:line.trimStart()});
i++;
}
}
clear_current_jobs() {
this.currentJobs = new WeakMap<Task, Promise<boolean|'aborted'>>();
}
async compile(flags:string[] = []) {
await this.compileRegion(undefined, 0, this.lines.length, new Map<string,string>(), flags);
const compiledTasks = new Set<Task>();
const finalTaskPass = (task:Task, parentNames:string[]) => {
if(compiledTasks.has(task)) return;
const childNames = [...parentNames, task.name];
task.netFileDependencies = [...task.fileDependencies];
task.netProvidedFiles = [...task.providedFiles];
for(const dependency of task.taskDependenciesByName){
if(childNames.includes(dependency.name)){
console.error(`Circular task dependency detected: `, childNames.join(' -> ')+` -> ${dependency.name}`);
continue;
}
for(const childTask of this.tasks){
if(childTask.name==dependency.name){
task.taskDependencies.push({optional: dependency.optional, task:childTask});
finalTaskPass(childTask, childNames);
for(const file of childTask.fileDependencies){
if(!task.netFileDependencies.includes(file)){
task.netFileDependencies.push(file);
}
}
for(const file of childTask.providedFiles){
if(!task.netProvidedFiles.includes(file)){
task.netProvidedFiles.push(file);
}
}
}
}
}
// file dependencies that are self-provided needn't propagate outward to parents as they've been fulfilled internally (but provided files still propagate)
for(let i=0;i<task.netFileDependencies.length;i++){
if(task.netProvidedFiles.includes(task.netFileDependencies[i])){
task.netFileDependencies.splice(i--, 1);
}
}
compiledTasks.add(task);
}
for(const task of this.tasks){
finalTaskPass(task, []);
}
}
execute(tags:Symbol[], taskName:string):ScriptExecution {
const tasks = this.tasks.filter((x) => x.name==taskName);
if(tasks.length<1){
console.error(`Nothing to do for task "${taskName}"`);
return {cancel:()=>{}, promise:Promise.resolve(false)};
}
return this.execute_tasks(tags, `running task "${taskName}"`, tasks);
}
execute_tasks(tags:Symbol[], description:string, tasks:Task[]):ScriptExecution {
const currentRunTag = Symbol();
tags = [...tags, currentRunTag];
const jobs:Promise<true|false|'aborted'>[] = [];
const childExecutions:ScriptExecution[] = [];
let isCancelled = false;
const cancel = () => {
isCancelled = true
runQueue.cancel_tag(currentRunTag);
for(const child of childExecutions){
child.cancel();
}
};
return { cancel, promise: (async () => {
{
const taskJobs:Promise<true|false|'aborted'>[] = [];
for(const task of tasks){
let promise = this.currentJobs.get(task);
if(!promise){
promise = (async() => {
// check all task dependencies first...
{
const dependencyJobs:Promise<true|false|'aborted'>[] = [];
let isFinished = false;
for(const [i, dependency] of task.taskDependencies.entries()){
// const job = jobs[i];
dependencyJobs.push((async () => {
const childTask = this.execute_tasks(tags, `running task "${dependency.task.name}"`, [dependency.task]);
childExecutions.push(childTask)
const result = await childTask.promise;
switch(result){
case true:
break;
case false:
if(!dependency.optional){
// await Promise.allSettled(dependencyJobs);
if(!isFinished) {
isFinished = true;
log_status_failure(`Could not run "${taskName}" task, as "${dependency.task.name}" task failed`);
runQueue.cancel_tag(currentRunTag);
return 'aborted';
}
return false;
}
break;
case 'aborted':
// await Promise.allSettled(dependencyJobs);
isFinished = true;
runQueue.cancel_tag(currentRunTag);
return 'aborted';
break;
}
return true;
})());
}
const completed = await Promise.allSettled(dependencyJobs);
if(isCancelled) return 'aborted';
// if any solid failures, fail
for(const result of completed){
if(result.status!='fulfilled'||result.value===false){
return false;
}
}
// otherwise, if there were silent aborts, silently abort
for(const result of completed){
if(result.status=='fulfilled'&&result.value=='aborted'){
return 'aborted';
}
}
}
let newestDate:number|null = null;
// check for all dependent files second.. (so that tasks can create them)
{
const dependencyJobs:Promise<boolean>[] = [];
let isFinished = false;
for(const dependency of task.fileDependencies){
dependencyJobs.push((async () => {
const date = await file_date(dependency);
if(!date){
if(!isFinished) {
isFinished = true;
log_status_failure(`Error attempting to run "${taskName}" task: Required file "${dependency}" was not found.`);
runQueue.cancel_tag(currentRunTag);
}
return false;
}
if(newestDate===null||date>newestDate){
newestDate = date;
}
return true;
})());
}
const completed = await Promise.allSettled(dependencyJobs);
if(isCancelled) return 'aborted';
for(const result of completed){
if(result.status!='fulfilled'||!result.value){
return false;
}
}
}
let outOfDate = false;
// check if task is out of date
if(!task.providedFiles.length){
outOfDate = true;
}else{
for(const provide of task.providedFiles){
const date = await file_date(provide);
if(date===null||newestDate&&date<newestDate){
outOfDate = true;
break;
}
}
}
// execute actions
if(outOfDate){
if(verbosity>=Verbosity.tasks) {
log_status_action(`${color.bold('Executing')} "${task.name}" task...`);
}
// mark all files we're about to change
for(const file of task.providedFiles){
if(!this.modifiedFiles.includes(file)){
this.modifiedFiles.push(file);
}
}
let succeeded = true;
let cwd = Deno.cwd();
const cwdHistory:string[] = [];
for(const line of task.parsedLines){
switch(line.type){
case 'run':
if(verbosity>=Verbosity.debug) {
log_verbose(true, `>> ${line.source}`);
if(line.debugVars){
log_verbose(true, ` (${line.debugVars})`);
}
}
if(verbosity>=Verbosity.tasksAndCommands) {
log_verbose(true, `> ${line.command}`);
}
if(!dryRun) {
const result = await run_process(tags, params_parse(line.command), cwd);
if(isCancelled) return 'aborted';
if(line.optional&&result===false) return true;
if(result!==true){
runQueue.cancel_tag(currentRunTag);
succeeded = false;
break;
}
}
break;
case 'cd':
if(verbosity>=Verbosity.debug) {
log_verbose(true, `>> ${line.source}`);
}
if(verbosity>=Verbosity.tasksAndCommands) {
log_verbose(true, `> cd ${line.path}`);
}
if(!dryRun) {
if(line.path=='-'){
const old = cwdHistory.pop();
if(!old){
log_status_failure(`Unable to change to previous directory - no previous path existed`);
runQueue.cancel_tag(currentRunTag);
succeeded = false;
break;
}
cwd = old;
}else{
cwdHistory.push(cwd);
if(line.path.length>0&&line.path[0]=='/'){
cwd = path.normalize(line.path);
}else{
cwd = path.join(cwd, line.path);
}
try{
const info = await Deno.stat(cwd);
if(!info.isDirectory){
log_status_failure(`Path is not a directory: ${cwd}`);
runQueue.cancel_tag(currentRunTag);
succeeded = false;
break;
}
}catch(error){
if(error instanceof Deno.errors.NotFound){
log_status_failure(`Path not found: ${cwd}`);
runQueue.cancel_tag(currentRunTag);
succeeded = false;
break;
}
throw error;
}
}
}
break;
}
if(!succeeded) break;
}
//update cached data on all provided files, as they may have been updated
for(const provides of task.providedFiles){
const date = await file_date(provides, false);
}
if(!succeeded){
return false;
}
}
return true;
})();
this.currentJobs.set(task, promise);
}
taskJobs.push(promise);
jobs.push(promise);
}
await Promise.allSettled(taskJobs);
}
const completed = await Promise.allSettled(jobs);
if(isCancelled){
return 'aborted';
}
// if any solid failures, fail
for(const result of completed){
if(result.status!='fulfilled'||result.value===false){
log_status_failure(`${color.bold('Failure')} ${description}`);
return false;
}
}
// otherwise, if there were silent aborts, silently abort
for(const result of completed){
if(result.status=='fulfilled'&&result.value=='aborted'){
return 'aborted';
}
}
return true;
})()};
}
async compileRegion(currentTask:Task|undefined, start:number, end:number, vars:Map<string,string>, flags:string[] = []) {
const parse = async(line:ScriptLine, value:string):Promise<string> => {
const replaceTasks:Promise<string>[] = [];
const matchExpression = /(?<!{){([^{}]*)}(?!})/g;
const cwd = Deno.cwd();
value.replaceAll(matchExpression, (fullstring:string, expression:string) => {
replaceTasks.push((async() => {
let match:RegExpMatchArray|null;
if(match = expression.match(/^eval\s+(.+)/)){
const commandline = match[1];
if(verbosity>=Verbosity.tasksAndCommands) {
log_verbose(true, `> ${commandline}`);
}
const result = await evaluate_process(params_parse(commandline));
if(result===false){
if(verbosity>=Verbosity.tasksAndCommands) {
log_verbose(true, `< FAILED`);
}
return '';
}else{
if(verbosity>=Verbosity.tasksAndCommands) {
log_verbose(true, `< ${result}`);
}
return result;
}
}else if(match = expression.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)(?:\s+as (\S+))?\s*$/)){
const varName = match[1];
const rename = match[2] as string|undefined;
let value = vars.get(varName)||'';
if(rename){
let filenames:string[] = [];
match = rename.match(/^([^*]*)(\*)([^*]*)(?:\.)(\*|[^*]*)$/);
if(!match){
throw new ParseError(line.lineNumber, `Invalid rename glob: ${rename}`);
}
const renamePrefix = match[1];
const renameKeep = match[2]=='*';
const renamePostfix = match[3];
const renameExtension = match[4]=='*'?false:match[4];
for(let filename of params_parse(value)){
const dirname = path.dirname(filename);
const extensionEnding = renameExtension?`.${renameExtension}`:'';
const basename = renameExtension==undefined?path.basename(filename):path.basename(filename, path.extname(filename));
filename = (dirname?`${dirname}/`:'')+renamePrefix+(renameKeep?basename:'')+renamePostfix+extensionEnding;
filenames.push(filename);
}
value = params_quote(filenames);
}
return value;
}else if(match = expression.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)(?:\s*\.\s*([a-zA-Z_][a-zA-Z0-9_-]*))?$/)){
const varName = match[1];
const property = match[2] as string|undefined;
const value = vars.get(varName)||'';
const results = params_parse(value).map(value => {
if(property!==undefined){
switch(property){
case 'dir':
return path.dirname(value);
case 'file':
return path.basename(value);
case 'ext':
return path.extname(value);
case 'name':
return path.basename(value, path.extname(value));
default:
throw new ParseError(line.lineNumber, `No such property: ${property}`);
}
}else{
return value;
}
});
return params_quote(results);
}else if(match = expression.match(/^\s*(\S*\*\S*)(?:\s+as (\S+))?\s*$/)){
const glob = match[1];
const rename = match[2];
let renamePrefix = '';
let renameKeep = true;
let renamePostfix = '';
let renameExtension:string|false = false;
if(!this.globs.includes(glob)){
this.globs.push(glob);
}
if(rename){
match = rename.match(/^([^*]*)(\*)([^*]*)(?:\.)(\*|[^*]*)$/);
if(!match){
throw new ParseError(line.lineNumber, `Invalid rename glob: ${rename}`);
}
renamePrefix = match[1];
renameKeep = match[2]=='*';
renamePostfix = match[3];
renameExtension = match[4]=='*'?false:match[4];
}
const filenames:string[] = [];
for(const file of await file_search(glob)){
if(file.isFile){
let filename = path.relative(cwd, file.path);
if(rename){
const dirname = path.dirname(filename);
const extensionEnding = renameExtension?`.${renameExtension}`:'';
const basename = renameExtension==undefined?path.basename(filename):path.basename(filename, path.extname(filename));
filename = (dirname?`${dirname}/`:'')+renamePrefix+(renameKeep?basename:'')+renamePostfix+extensionEnding;
}
filenames.push(filename);
}
}
return params_quote(filenames);
}else{
throw new ParseError(line.lineNumber, `Invalid expression: ${expression}`);
}
})());
return fullstring;
});
const replacements = await Promise.all(replaceTasks);
return value
.replaceAll(matchExpression, () => replacements.shift() as string )
.replaceAll(/([{}])\1/g, '$1')
;
}
for(let i=start;i<end;i++){
const line = this.lines[i];
let match:RegExpMatchArray|null;
if(!line.source){
continue;
}else if(match = line.source.match(/^#/)){
continue;
}else if(match = line.source.match(/^provides\s+(.+)$/)){
const items = params_parse(await parse(line, match[1]));
if(!currentTask) throw new ParseError(line.lineNumber, "Cannot use 'provides` outside of a task");
if(items){
for(let item of items){
currentTask.providedFiles.push(item);
}
}
}else if(match = line.source.match(/^requires\s+(?:(?:(optional)\s+)?(task)\s+)?(.+)$/)){
const isTask = !!match[2];
const isOptional = !!match[1];
const items = params_parse(await parse(line, match[3]));
if(!currentTask) throw new ParseError(line.lineNumber, "Cannot use 'requires` outside of a task");
if(items) {
for(let item of items){
if(isTask){
currentTask.taskDependenciesByName.push({ optional:isOptional, name:item });
}else{