-
Notifications
You must be signed in to change notification settings - Fork 0
/
yabs.js
1658 lines (1568 loc) · 52.8 KB
/
yabs.js
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
/*
* __ __ _____ _____ _____ _
* | | | _ | _ | __| |_|___
* \_ | | _ -|__ |_ | |_ -|
* /__/|__|__|_____|_____|_|_| |___|
* |___|
*
* Yet-Another-Build-System.js
* https://github.com/metayeti/YABS.js
* ---
* (c) 2024 Danijel Durakovic
* Licensed under the terms of the MIT license
*
*/
/*jshint esversion:9*/
/**
* @file yabs.js
* @author Danijel Durakovic
* @version 1.2.0
* @license MIT
*/
const path = require('path');
const fs = require('fs');
const { fork, exec } = require('child_process');
/**
* yabs.js namespace
* @namespace
*/
const yabs = {};
////////////////////////////////////////////////////////////////////////////////
//
// Constants
//
////////////////////////////////////////////////////////////////////////////////
yabs.VERSION = '1.2.0'; // YABS.js version
yabs.DEFAULT_BUILD_ALL_FILE = 'build_all.json';
yabs.DEFAULT_BUILD_FILE = 'build.json';
yabs.DEFAULT_COMPILE_OPTIONS = '--compress --mangle';
yabs.NEWLINE_SYMBOL = '\n'; // LF, use \r\n for CRLF
yabs.GLUE_FILE_EXTENSION = '.glw';
yabs.PREPROCESS_FILE_EXTENSION = '.pre';
yabs.COMPILE_FILE_EXTENSION = '.cmp';
yabs.COMPILED_SOURCE_EXTENSION = '.min.js';
yabs.URL_YABS_MANUAL = 'https://github.com/metayeti/YABS.js/blob/main/HOWTO.md';
////////////////////////////////////////////////////////////////////////////////
//
// Utility
//
////////////////////////////////////////////////////////////////////////////////
yabs.util = {};
/**
* Checks whether a given file or path exists.
*
* @function exists
* @memberof yabs.util
* @instance
*
* @param {string} source_path
*
* @returns {bool}
*/
yabs.util.exists = function(source_path) {
return fs.existsSync(source_path);
};
/**
* Checks whether a given path represents a directory.
*
* @function isDirectory
* @memberof yabs.util
* @instance
*
* @param {string} source_path
*
* @returns {bool}
*/
yabs.util.isDirectory = function(source_path) {
return fs.lstatSync(source_path).isDirectory();
};
/**
* Get modified-time of given path.
*
* @function getModifiedTime
* @memberof yabs.util
* @instance
*
* @param {string} source_path
*
* @returns {number}
*/
yabs.util.getModifiedTime = function(source_path) {
return fs.statSync(source_path).mtime;
};
/**
* Determines whether or not source filename is newer than destination filename.
*
* @function isSourceNewer
* @memberof yabs.util
* @instance
*
* @param {string} source_path
* @param {string} destination_path
*
* @returns {bool}
*/
yabs.util.isSourceNewer = function(source_path, destination_path) {
const dtime_modified_source = (Date.now() - yabs.util.getModifiedTime(source_path));
const dtime_modified_destination = (Date.now() - yabs.util.getModifiedTime(destination_path));
return (dtime_modified_destination - dtime_modified_source) >= 1000;
};
/**
* Recursively generates a list of files based on given source and destination directories.
* Skip source files that are both older than, and have a correlating existing destination file.
* (This makes it so that repeated builds don't keep cloning already existing files for which
* there is no need to be repeatedly updated.)
*
* @function getFilesWithRecursiveDescent
* @memberof yabs.util
* @instance
*
* @param {string} source_dir - Source relative directory.
* @param {string} destination_dir - Destination relative directory.
* @param {array} mask - Can be one of three states:
* ["*", null] - fetch everything and descent recursively
* ["*", "*"] - fetch everything, but don't descent recursively
* ["*", ".ext"] - fetch everything, don't descent recursively, and it has to match extension
*
* @returns {array} Array of {source, destination} pairs.
*/
yabs.util.getFilesWithRecursiveDescent = function(source_dir, destination_dir, mask, depth = 0) {
let list = [];
if (!yabs.util.exists(source_dir)) {
throw `Could not locate path: ${source_dir}`;
}
const source_dir_listing = fs.readdirSync(source_dir);
source_dir_listing.forEach(listing_entry => {
const nested_source_path = path.join(source_dir, listing_entry);
const nested_destination_path = path.join(destination_dir, listing_entry);
const is_source_directory = yabs.util.isDirectory(nested_source_path);
if (is_source_directory) { // this is a directory
if (mask[0] === '*' && mask[1] === null) { // only allow recursive descent with correct mask
list = list.concat(yabs.util.getFilesWithRecursiveDescent(
nested_source_path, nested_destination_path, mask, depth + 1
));
}
}
else { // this is a file
// validate against mask
if (mask[0] === '*' && mask[1] !== '*' && mask[1] !== null) {
// validate against extension type
const parsed_nested_source_path = path.parse(nested_source_path);
if (mask[1] !== parsed_nested_source_path.ext) {
return;
}
}
if (yabs.util.exists(nested_destination_path)) { // destination file already exists
// check file timestamps
if (!yabs.util.isSourceNewer(nested_source_path, nested_destination_path)) {
// source file is not newer than destination, skip this file
return;
}
}
list.push({
source: nested_source_path,
destination: nested_destination_path
});
}
});
// return the compiled list
return list;
};
/**
* Parses JSDoc-style tags from a source file.
*
* @function parseJSDocTagsFromFile
* @memberof yabs.util
* @instance
*
* @param {string} source_file - Source filename.
* @param {object} output - Reference to output object.
*/
yabs.util.parseJSDocTagsFromFile = function(source_file, output) {
const jsdoc_regex = /\/\*\*(.*?)\*\//gs;
const tag_regex = /\*\s*@(\w+)\s+(.+)/g;
const file_content = fs.readFileSync(source_file, { encoding: 'utf8', flag: 'r' });
const jsdoc_regex_matches = file_content.match(jsdoc_regex);
if (jsdoc_regex_matches) {
jsdoc_regex_matches.forEach(regex_match => {
let tag_match;
while ((tag_match = tag_regex.exec(regex_match)) !== null) {
const tag_key = tag_match[1];
const tag_value = tag_match[2];
output[tag_key] = tag_value;
}
});
}
};
/**
* Attempts to resolve the given URL in a native browser.
*
* @function openURLWithBrowser
* @memberof yabs.util
* @instance
*
* @param {string} url - URL to resolve.
*/
yabs.util.openURLWithBrowser = function(url) {
const start_cmd = (function() {
switch (process.platform) {
case 'darwin': return 'open';
case 'win32': return 'start';
default: return 'xdg-open';
}
}());
exec(`${start_cmd} ${url}`);
};
/**
* Runs an external script as defined by the user.
*
* @function runUserScript
* @memberof yabs.util
* @instance
*
* @param {string} path - Path to script.
* @param {array} params - List of parameters.
*/
yabs.util.runUserScript = async function(path, params) {
return new Promise((resolve, reject) => {
const proc = fork(path, params);
proc.on('error', (err) => {
process.stdout.write('\n');
reject(err);
});
proc.on('exit', () => {
resolve();
});
proc.on('message', (msg) => {
resolve(msg);
});
});
};
////////////////////////////////////////////////////////////////////////////////
//
// Logger
//
////////////////////////////////////////////////////////////////////////////////
yabs.Logger = class {
/**
* Constructs a Logger object.
*
* @class yabs.Logger
* @classdesc Deals with output.
*/
constructor() {
// detect if output is a terminal or not
// (so we can strip color codes if output is redirected)
const is_tty = process.stdout.isTTY;
// output constants and color codes
this._OUTPUT_RESET = (is_tty) ? '\x1b[0m' : '';
this._OUTPUT_BRIGHT = (is_tty) ? '\x1b[1m' : '';
this._OUTPUT_FG_RED = (is_tty) ? '\x1b[31m' : '';
this._OUTPUT_FG_GREEN = (is_tty) ? '\x1b[32m' : '';
this._OUTPUT_FG_YELLOW = (is_tty) ? '\x1b[33m' : '';
}
/**
* Prints a message, followed by newline.
*
* @param {string} message
*/
out(message) {
process.stdout.write(`${message}\n`);
}
/**
* Prints a raw message.
*
* @param {string} message
*/
out_raw(message) {
process.stdout.write(message);
}
/**
* Ends output with 'ok'.
*/
ok() {
process.stdout.write(
` ${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_GREEN}` +
`ok${this._OUTPUT_RESET}\n`
);
}
/**
* Prints an info message.
*
* @param {string} message
*/
info(message) {
process.stdout.write(
`${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW}>` +
`${this._OUTPUT_RESET} ${message}\n\n`
);
}
/**
* Prints a newline.
*/
endl() {
process.stdout.write('\n');
}
/**
* Prints an error message.
*
* @param {string} message
*/
error(message) {
process.stdout.write(
`${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_RED}Error: ` +
`${this._OUTPUT_RESET}${message}\n`
);
}
/**
* Prints a success message.
*
* @param {string} message
*/
success(message) {
process.stdout.write(
`${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_GREEN}Success: ` +
`${this._OUTPUT_RESET}${message}\n`
);
}
/**
* Prints the YABS.js header.
*/
header() {
this.out_raw(`${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW}`);
this.out(' __ __ _____ _____ _____ _');
this.out(' | | | _ | _ | __| |_|___');
this.out(' \\_ | | _ -|__ |_ | |_ -|');
this.out(' /__/|__|__|_____|_____|_|_| |___|');
this.out(' |___|' + `${this._OUTPUT_RESET}` + ' '.repeat(13 - yabs.VERSION.length) + 'v' + yabs.VERSION);
this.out(` ${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW}Y${this._OUTPUT_RESET}et`);
this.out(
` ${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW}A${this._OUTPUT_RESET}nother` +
' https://github.com/metayeti/YABS.js'
);
this.out(
` ${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW}B${this._OUTPUT_RESET}uild` +
` ${this._OUTPUT_RESET} (c) 2024 Danijel Durakovic`
);
this.out(
` ${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW}S${this._OUTPUT_RESET}ystem${this._OUTPUT_BRIGHT}${this._OUTPUT_FG_YELLOW} .js` +
`${this._OUTPUT_RESET} MIT licence`
);
this.endl();
}
/**
* Prints a long line.
*/
line() {
this.out('----------------------------------------------');
}
};
////////////////////////////////////////////////////////////////////////////////
//
// Build configuration
//
////////////////////////////////////////////////////////////////////////////////
yabs.BuildConfig = class {
/**
* Constructs a BuildConfig object.
*
* @class yabs.BuildConfig
* @classdesc Configures a build based on input.
*
* @param {string} source_file - Build instructions JSON file.
*/
constructor(source_file) {
const parsed_source_file = path.parse(source_file);
this._source_file = parsed_source_file.base;
this._base_dir = parsed_source_file.dir;
// parse source JSON
const file_data = fs.readFileSync(source_file, { encoding: 'utf8', flag: 'r' });
const json_data = JSON.parse(file_data);
// check if this is a batch build
if (json_data.hasOwnProperty('batch_build')) {
this._is_batch = true;
this._batch_listing = [];
if (json_data.batch_build instanceof Array) {
json_data.batch_build.forEach(batch_entry => {
if (typeof batch_entry === 'string') {
this._batch_listing.push({
target: batch_entry
});
}
else if (typeof batch_entry === 'object' && batch_entry !== null) {
const batch_entry_object = {};
if (batch_entry.hasOwnProperty('target')) {
if (typeof batch_entry.target === 'string') {
batch_entry_object.target = batch_entry.target;
}
}
if (batch_entry.hasOwnProperty('options')) {
if (typeof batch_entry.options === 'string') {
batch_entry_object.options = batch_entry.options;
}
}
if (batch_entry_object.target) {
this._batch_listing.push(batch_entry_object);
}
}
});
}
else {
throw 'The "batch_build" entry has to be an Array type!';
}
return; // this is a batch build, we are all done here
}
// extract source_dir
if (!json_data.hasOwnProperty('source_dir')) {
throw 'Missing "source_dir" entry!';
}
this._source_dir = json_data.source_dir;
// extract destination_dir
if (!json_data.hasOwnProperty('destination_dir')) {
throw 'Missing "destination_dir" entry!';
}
this._destination_dir = json_data.destination_dir;
// extract html listing
if (json_data.hasOwnProperty('html')) {
if (json_data.html instanceof Array) {
if (!json_data.html.every(element => typeof element === 'string')) {
throw 'Every element in "html" entry has to be a String type!';
}
this._html_listing = json_data.html;
}
else if (typeof json_data.html === 'string') {
this._html_listing = [ json_data.html ];
}
}
if (!this._html_listing) {
this._html_listing = [];
}
// extract sources listing
if (json_data.hasOwnProperty('sources')) {
if (json_data.sources instanceof Array) {
this._sources_listing = [];
json_data.sources.forEach(source_entry => {
if (typeof source_entry === 'string') {
this._sources_listing.push({
file: source_entry
});
}
else if (typeof source_entry === 'object' && source_entry !== null) {
const source_entry_object = {};
if (source_entry.hasOwnProperty('output_file')) {
if (typeof source_entry.output_file === 'string') {
source_entry_object.output_file = source_entry.output_file;
}
}
if (source_entry.hasOwnProperty('compile_options')) {
if (typeof source_entry.compile_options === 'string') {
source_entry_object.compile_options = source_entry.compile_options;
}
}
if (source_entry.hasOwnProperty('bundle')) {
if (source_entry_object.output_file === undefined) {
// we are missing output_file
throw 'Bundled scripts require an "output_file" entry!';
}
if (!(source_entry.bundle instanceof Array)) {
throw 'The "bundle" entry has to be an Array type!';
}
if (!source_entry.bundle.every(element => typeof element === 'string')) {
throw 'Every element in "bundle" entry has to be a String type!';
}
source_entry_object.is_bundle = true;
source_entry_object.bundle_files = source_entry.bundle;
}
else if (source_entry.hasOwnProperty('file')) {
if (typeof source_entry.file === 'string') {
source_entry_object.file = source_entry.file;
}
}
if (source_entry.hasOwnProperty('header')) {
if (source_entry.header instanceof Array) {
if (!source_entry.header.every(element => typeof element === 'string')) {
throw 'Every item of "header" entry listing has to be a String type!';
}
source_entry_object.header = source_entry.header;
}
else if (typeof source_entry.header === 'string') {
source_entry_object.header = [ source_entry.header ];
}
}
else if (source_entry.hasOwnProperty('use_header')) {
// using header from reference
if (json_data.headers && typeof source_entry.use_header === 'string') {
if (json_data.headers.hasOwnProperty(source_entry.use_header)) {
const header_ref = json_data.headers[source_entry.use_header];
if (header_ref instanceof Array) {
if (!header_ref.every(element => typeof element === 'string')) {
throw 'Every item in "headers" entry listing has to be a String type!';
}
source_entry_object.header = header_ref;
}
else if (typeof header_ref === 'string') {
source_entry_object.header = [ header_ref ];
}
}
}
}
if (source_entry.hasOwnProperty('variables')) {
if (typeof source_entry.variables === 'object' &&
!(source_entry.variables instanceof Array) &&
source_entry.variables !== null) {
source_entry_object.variables = {};
for (const variable_key in source_entry.variables) {
const variable_data = source_entry.variables[variable_key];
if (variable_data instanceof Array) {
if (!variable_data.every(element => typeof element === 'string')) {
throw 'Every item in "variables" entry listing has to be a String type!';
}
source_entry_object.variables[variable_key] = variable_data;
}
}
}
}
else if (source_entry.hasOwnProperty('use_variables')) {
// using variables from reference
if (json_data.variables && typeof source_entry.use_variables === 'string') {
if (json_data.variables.hasOwnProperty(source_entry.use_variables)) {
const variables_ref = json_data.variables[source_entry.use_variables];
if (typeof variables_ref === 'object' &&
!(variables_ref instanceof Array) &&
variables_ref !== null) {
source_entry_object.variables = {};
for (const variable_key in variables_ref) {
const variable_data = variables_ref[variable_key];
if (variable_data instanceof Array) {
if (!variable_data.every(element => typeof element === 'string')) {
throw 'Every item in "variables" entry listing has to be a String type!';
}
source_entry_object.variables[variable_key] = variable_data;
}
}
}
}
}
}
if (source_entry.hasOwnProperty('preprocess')) {
if (source_entry.preprocess === true) {
source_entry_object.preprocess = true;
}
}
if (source_entry_object.file || source_entry_object.is_bundle) {
this._sources_listing.push(source_entry_object);
}
}
});
}
else {
throw 'The "sources" entry has to be an Array type!';
}
}
if (!this._sources_listing) {
this._sources_listing = [];
}
// extract files listing
if (json_data.hasOwnProperty('files')) {
if (json_data.files instanceof Array) {
if (!json_data.files.every(element => typeof element === 'string')) {
throw 'Every element in "files" entry has to be a String type!';
}
this._files_listing = json_data.files;
}
else if (typeof json_data.files === 'string') {
this._files_listing = [ json_data.files ];
}
}
if (!this._files_listing) {
this._files_listing = [];
}
// extract events listing
if (json_data.hasOwnProperty('events')) {
this._events_listing = {
prebuild: [],
postbuild: []
};
const events_entry = json_data.events;
if (typeof events_entry === 'object' && events_entry !== null) {
const prebuild_entry = events_entry.prebuild;
const postbuild_entry = events_entry.postbuild;
if (prebuild_entry instanceof Array) {
if (!prebuild_entry.every(element => typeof element === 'string')) {
throw 'Every element in "prebuild" entry has to be a String type!';
}
this._events_listing.prebuild = prebuild_entry;
}
if (postbuild_entry instanceof Array) {
if (!postbuild_entry.every(element => typeof element === 'string')) {
throw 'Every element in "postbuild" entry has to be a String type!';
}
this._events_listing.postbuild = postbuild_entry;
}
}
}
else {
this._events_listing = null;
}
}
/**
* Returns the input build instructions filename.
*/
getSourceFile() {
return this._source_file;
}
/**
* Returns the base directory of the build instructions filename.
*/
getBaseDir() {
return this._base_dir;
}
/**
* Returns whether or not this is a batch build.
*
* @returns {bool}
*/
isBatchBuild() {
return this._is_batch;
}
/**
* Returns batch listing.
*
* @returns {array}
*/
getBatchListing() {
return this._batch_listing;
}
/**
* Returns source directory.
*
* @returns {string}
*/
getSourceDir() {
return this._source_dir;
}
/**
* Returns destination directory.
*
* @returns {string}
*/
getDestinationDir() {
return this._destination_dir;
}
/**
* Returns HTML listing.
*
* @returns {array}
*/
getHTMLListing() {
return this._html_listing;
}
/**
* Returns sources listing.
*
* @returns {array}
*/
getSourcesListing() {
return this._sources_listing;
}
/**
* Returns files listing.
*
* @returns {array}
*/
getFilesListing() {
return this._files_listing;
}
/**
* Returns events listing.
*
* @returns {array}
*/
getEventsListing() {
return this._events_listing;
}
};
////////////////////////////////////////////////////////////////////////////////
//
// Builder
//
////////////////////////////////////////////////////////////////////////////////
yabs.Builder = class {
/**
* Constructs a Builder object.
*
* @class yabs.Builder
* @classdesc Implements building.
*
* @param {object} logger
* @param {object} build_config
* @param {object} build_params
*/
constructor(logger, build_config, build_params) {
this._logger = logger;
this._build_config = build_config; // build configuration
this._build_params = build_params; // build parameters
this._base_dir = this._build_config.getBaseDir(); // base directory
// source and destination directories
this._source_dir = path.normalize(this._build_config.getSourceDir());
this._destination_dir = path.normalize(this._build_config.getDestinationDir());
// prebuilt manifest lists
this._files_manifest = null;
this._sources_manifest = null;
this._html_manifest = null;
// build statistics
this._n_files_updated = 0;
this._build_start_time = Date.now();
}
/**
* Creates manifest lists for current build.
*/
_buildManifests() {
function buildFilesManifest() {
const files_listing = this._build_config.getFilesListing();
files_listing.forEach(listing_entry => {
if (listing_entry.includes('*')) { // path includes mask
// use recursive descent to capture all files
const full_source_path = path.join(this._base_dir, this._source_dir, listing_entry);
const parsed_source_path = path.parse(full_source_path);
const full_destination_path = path.join(this._destination_dir, listing_entry);
const parsed_destination_path = path.parse(full_destination_path);
if (!parsed_source_path.dir.includes('*') && parsed_source_path.name === '*') {
// only allow masks when they are the last part of path
// (disallow masks in dirname because they make no sense)
const split_base = parsed_source_path.base.split('.');
let mask = null;
if (parsed_source_path.base === '*') {
mask = ['*', null]; // ["*", null]
}
else if (parsed_source_path.base === '*.*') {
mask = ['*', '*']; // ["*", "*"]
}
else if (split_base[0] === '*' && split_base[1] !== '*' && split_base[1] !== '') {
mask = ['*', parsed_source_path.ext]; // ["*", ".ext"]
}
if (mask !== null) {
this._files_manifest = this._files_manifest.concat(
yabs.util.getFilesWithRecursiveDescent(parsed_source_path.dir, parsed_destination_path.dir, mask)
);
}
}
}
else { // plain path
const plain_file_source = path.join(this._base_dir, this._source_dir, listing_entry);
const plain_file_destination = path.join(this._destination_dir, listing_entry);
if (yabs.util.isDirectory(plain_file_source)) {
// this is a directory
return;
}
let include_plain_file = false;
if (!yabs.util.exists(plain_file_destination)) {
// destination file does not exist yet
include_plain_file = true;
}
else {
// check if source is newer than destination
if (yabs.util.isSourceNewer(plain_file_source, plain_file_destination)) {
include_plain_file = true;
}
}
if (include_plain_file) {
// make sure source is not the same as destination
if (plain_file_source === plain_file_destination) {
throw `Source file: "${plain_file_source}" cannot be the same as the destination!`;
}
// add to manifest
this._files_manifest.push({
source: plain_file_source,
destination: plain_file_destination
});
}
}
});
}
function buildSourcesManifest() {
const sources_listing = this._build_config.getSourcesListing();
sources_listing.forEach(listing_entry => {
// configure source filename (or filenames if bundle)
let sources_list = [];
if (listing_entry.is_bundle) {
sources_list = listing_entry.bundle_files;
}
else {
sources_list = [ listing_entry.file ];
}
if (sources_list.some(element => element.includes('*'))) {
throw 'Sources may not have masks!';
}
// process sources list into full source paths
const source_full_path_list = [];
sources_list.forEach((source_path) => {
const source_full_path = path.join(this._base_dir, this._source_dir, source_path);
source_full_path_list.push(source_full_path);
});
// configure the output filename
let output_filename, has_output_file_field;
if (listing_entry.output_file) {
output_filename = path.normalize(listing_entry.output_file);
has_output_file_field = true;
}
else {
const parsed_file_entry = path.parse(sources_list[0]);
output_filename = path.join(parsed_file_entry.dir, parsed_file_entry.name + yabs.COMPILED_SOURCE_EXTENSION);
has_output_file_field = false;
}
// configure full destination path
const destination_full_path = path.join(this._destination_dir, output_filename);
// process header
const has_header = listing_entry.hasOwnProperty('header');
const header_data = { has_header: has_header };
if (has_header) {
// make sure to clone the array and not use a reference
// (because we may need to search/replace variables later on)
header_data.header = [...listing_entry.header];
}
// process variables
const has_variables = listing_entry.hasOwnProperty('variables');
const variables_data = { has_variables: has_variables };
if (has_variables) {
variables_data.variables = listing_entry.variables;
}
// process compile options
const compile_options = (listing_entry.hasOwnProperty('compile_options'))
? listing_entry.compile_options
: yabs.DEFAULT_COMPILE_OPTIONS;
// process additional flags
const force_preprocessor = listing_entry.preprocess === true;
// add to manifest
this._sources_manifest.push({
sources: source_full_path_list,
destination: destination_full_path,
output_filename: output_filename,
has_output_file_field: has_output_file_field,
compile_options: compile_options,
header_data: header_data,
variables_data: variables_data,
force_preprocessor: force_preprocessor
});
});
}
function buildHTMLManifest() {
const html_listing = this._build_config.getHTMLListing();
html_listing.forEach(listing_entry => {
if (listing_entry.includes('*')) {
// disallow any masks
return;
}
const html_file_source = path.join(this._base_dir, this._source_dir, listing_entry);
const html_file_destination = path.join(this._destination_dir, listing_entry);
// make sure source is not the same as destination
if (html_file_source === html_file_destination) {
throw `Source file: "${html_file_source}" cannot be the same as the destination!`;
}
// add to manifest
this._html_manifest.push({
source: html_file_source,
destination: html_file_destination
});
});
}
this._files_manifest = [];
this._sources_manifest = [];
this._html_manifest = [];
buildFilesManifest.call(this);
buildSourcesManifest.call(this);
buildHTMLManifest.call(this);
}
/**
* Verifies that source files in the manifest lists exist.
*/
_verifySourceFiles() {
function verifyManifest(manifest_list) {
function verifyOne(path_source) {
const path_resolved = path.resolve(path_source);
if (!yabs.util.exists(path_resolved)) {
throw `Could not find file: ${path_source}`;
}
}
manifest_list.forEach(manifest_entry => {
if (manifest_entry.sources instanceof Array) { // we have a list of sources
manifest_entry.sources.forEach(verifyOne);
}
else if (typeof manifest_entry.source === 'string') { // we have a single source
verifyOne(manifest_entry.source);
}
});
}
verifyManifest.call(this, this._files_manifest);
verifyManifest.call(this, this._sources_manifest);
verifyManifest.call(this, this._html_manifest);
}
/**
* Process source files headers, substituting variables with data where applicable.
*/
_processSourceHeaders() {
this._sources_manifest.forEach(manifest_entry => {
const header_data = manifest_entry.header_data;
if (!header_data.has_header) { // this entry has no header, it's safe to skip it
return;
}
let has_variables = false;
// determine if the header contains variables
header_data.header.every(header_str => {
if (/%\S+%/.test(header_str) || /\$YEAR\$/.test(header_str)) {
has_variables = true;
return false;
}
return true;
});
if (!has_variables) { // this entry has a header but no variables, so it's safe to skip
return;
}
// extract JSDoc tags from sourcefile
const parsed_variables = {};
manifest_entry.sources.forEach(source_file => {
yabs.util.parseJSDocTagsFromFile(source_file, parsed_variables);
});
// update header variables
for (let i = 0; i < header_data.header.length; ++i) {
// from JSDoc tags
for (let variable_key in parsed_variables) {
const variable_value = parsed_variables[variable_key];
if (Object.prototype.hasOwnProperty.call(parsed_variables, variable_key)) {
header_data.header[i] = header_data.header[i].replace(new RegExp(`%${variable_key}%`, 'g'), variable_value);
}
}
// special variable
header_data.header[i] = header_data.header[i].replace(/\$YEAR\$/g, new Date().getFullYear());
}
});
}
_buildStep_I_UpdateFiles() {
this._files_manifest.forEach(manifest_entry => {
this._logger.out_raw(`${manifest_entry.destination} ...`);
// check if destination directory exists
const dir = path.dirname(manifest_entry.destination);
if (!yabs.util.exists(dir)) {
// directory doesn't exist yet, create it
fs.mkdirSync(dir, { recursive: true });
}
// copy file
fs.copyFileSync(manifest_entry.source, manifest_entry.destination);
this._logger.ok();
this._n_files_updated += 1;
});