-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
1496 lines (1245 loc) · 37.5 KB
/
index.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
const TaskRunner = require('shortbus')
const path = require('path')
const fs = require('fs-extra')
const glob = require('glob')
const minimatch = require('minimatch')
const chalk = require('chalk')
const CLITable = require('cliui')
const localpackage = require('./package.json')
const Monitor = require('./Monitor')
const EventEmitter = require('events').EventEmitter
class FileManager {
constructor (filepath) {
Object.defineProperties(this, {
PRIVATE: {
enumerable: false,
configurable: false,
writable: true,
value: {
filepath,
content: null,
lines: null,
linecount: null,
lineindex: new Map(),
indexline: new Map(),
stats: new fs.Dirent()
}
}
})
// Make sure the file is readable
fs.accessSync(filepath, fs.constants.R_OK)
}
set content (value) {
this.PRIVATE.content = value
this.lines = null
this.linecount = null
}
get content () {
if (this.PRIVATE.content === null) {
this.PRIVATE.content = this.readSync()
}
return this.PRIVATE.content
}
get lines () {
if (this.PRIVATE.lines === null) {
this.processLines()
}
return this.PRIVATE.lines
}
get lineCount () {
if (this.PRIVATE.linecount === null) {
let lines = this.lines // eslint-disable-line
}
return this.PRIVATE.linecount || 0
}
get filename () {
return path.basename(this.PRIVATE.filepath)
}
processLines () {
this.PRIVATE.lines = {}
let lines = this.content.split(require('os').EOL)
let currentPosition = -1
lines.forEach((content, line) => {
currentPosition++
let lineEnd = currentPosition + content.length - (currentPosition === 0 ? 1 : 0)
if (lineEnd <= currentPosition) {
lineEnd = currentPosition + 1
}
this.PRIVATE.lines[line + 1] = content
let start = this.content.indexOf(content, currentPosition)
let end = start + content.length - (currentPosition === 0 ? 1 : 0)
this.PRIVATE.lineindex.set([start, end], line + 1)
this.PRIVATE.indexline.set(line + 1, [start, end])
currentPosition = end
})
this.PRIVATE.linecount = lines.length
}
readSync () {
return fs.readFileSync(this.PRIVATE.filepath).toString()
}
read () {
fs.readFile(this.PRIVATE.filepath, ...arguments)
}
getLine (number) {
return this.lines[number]
}
// Accepts any number of indexes as arguments
getLineByIndex () {
let indice = {}
// Forcibly calculate lines if they don't exist.
if (this.PRIVATE.lines === null) {
this.processLines()
}
// Sort index values, then get the line numbers
Array.from(arguments).sort().reverse().forEach(index => {
let line = null
let ranges = this.PRIVATE.lineindex.entries()
let range
while (line === null && !(range = ranges.next()).done) {
if (index >= range.value[0][0] && index <= range.value[0][1]) {
line = range.value[1]
indice[index] = line
}
}
})
return indice
}
// Accepts any number of lines as arguments
getLineIndexRange () {
let indice = {}
// Forcibly calculate lines if they don't exist.
if (this.PRIVATE.lines === null) {
this.processLines()
}
// Sort index values, then get the line numbers
Array.from(arguments).sort().reverse().forEach(line => {
indice[line] = this.PRIVATE.indexline.get(line)
})
return indice
}
getSnippet (start, end) {
let snippet = []
for (let i = start; i <= end; i++) {
snippet.push(this.lines[i])
}
return snippet.join('\n')
}
/**
* Similar to Array#forEach, except it passes the line content, line number, and full line object.
* @param {Function} fn
*/
forEachLine (fn) {
for (let line = 1; line <= this.lineCount; line++) {
fn(this.PRIVATE.lines[line], line, this.PRIVATE.lines)
}
}
}
/**
* @class ProductionLine.Builder
* A queueing and execution system.
* @extends EventEmitter
*/
class Builder extends EventEmitter {
constructor (cfg = {}) {
super()
/**
* @cfg {boolean} [checkForUpdates=true]
* Check for updates to the module.
*/
this.CHECKFORUPDATES = typeof cfg.checkForUpdates === 'boolean' ? cfg.checkForUpdates : true
this.tasks = new TaskRunner()
this.PKG = require(path.join(process.cwd(), 'package.json'))
// Metadata
this.APPVERSION = this.PKG.version
/**
* @cfg {string} [header]
* A standard header to be applied to files.
* Defaults to
* ```sh
* Copyright (c) <DATE> <AUTHOR> and contributors. All Rights Reserved.
* Version X.X.X built on <DATE>.
* ```
* If a project name is available in the local package.json, this will default to:
*
* ```
* <PROJECT NAME> vX.X.X generated on <DATE>.
* Copyright (c) <DATE> <AUTHOR> and contributors. All Rights Reserved.
* [LICENSE: <LICENSE TEXT>]
* ```
* _Notice the optional license._ If a license is supplied in the package.json,
* the it will be applied to the header. This only applies the name of the license
* (as i.e. license attribute of package.json). It does not read a license file
* into the header.
*/
this.HEADER = cfg.header || `Copyright (c) ${(new Date()).getFullYear()} ${this.author} and contributors. All Rights Reserved.${this.package.hasOwnProperty('license') ? '\nLICENSE: ' + this.package.license : ''}`
if (this.name !== 'Untitled') {
this.HEADER = `${this.name} v${this.version} generated on ${(new Date().toDateString())}.\n` + this.HEADER
} else {
this.HEADER = `${this.HEADER}\nVersion ${this.version} built on ${(new Date().toDateString())}.`
}
/**
* @cfg {string} [footer]
* A standard footer to be applied to files. Defaults to blank.
*/
this.FOOTER = null
this.COLORS = {
failure: chalk.bold.rgb(214, 48, 49),
warn: chalk.bold.rgb(225, 112, 85),
info: chalk.rgb(116, 185, 255),
log: chalk.rgb(223, 230, 233),
highlight: chalk.bold.rgb(232, 67, 147),
success: chalk.bold.rgb(85, 239, 196),
subtle: chalk.rgb(99, 110, 114),
verysubtle: chalk.rgb(45, 52, 54)
}
// Filepaths
/**
* @cfg {string} [source=./src]
* The root directory containing source files.
*/
this.SOURCE = path.resolve(cfg.source || './src')
/**
* @cfg {string} [output=./dist]
* The root directory where output files will be stored.
* This will be created if it does not already exist.
*/
this.OUTPUT = path.resolve(cfg.output || './dist')
/**
* @cfg {string} [assets=./assets]
* The root directory containing non-buildable assets such as multimedia.
*/
this.ASSETS = cfg.assets || [
'./assets'
]
if (typeof this.ASSETS === 'string') {
this.ASSETS = [this.ASSETS]
}
/**
* @cfg {string} [ignoredList=node_modules]
* A list of directories to ignore.
*/
this.IGNOREDLIST = cfg.ignoredList || [
'node_modules/**/*'
]
// Find .gitignore and .buildignore. Add them to the ignored list.
this.ignoreFile(path.join(process.cwd(), '.gitignore'))
this.ignoreFile(path.join(process.cwd(), '.buildignore'))
try {
if (cfg.ignore) {
if (!Array.isArray(cfg.ignore)) {
cfg.ignore = [cfg.ignore]
}
this.IGNOREDLIST = this.IGNOREDLIST.concat(cfg.ignore)
}
} catch (e) {}
// Helper tool for custom logging.
this.joinArguments = args => {
let out = []
for (let i = 0; i < args.length; i++) {
out.push(args[i])
}
return out.join(' ')
}
let width = 15
// Initialize tasks.
Object.defineProperties(this, {
prepareBuild: {
enumerable: false,
writable: true,
configurable: true,
value: () => {
this.tasks.add('Preparing Build', next => {
let ui = new CLITable()
ui.div({
text: this.COLORS.info(`Running ${localpackage.name} v${localpackage.version} for ${this.PKG.name}`),
border: false,
padding: [1, 0, 1, 5]
})
ui.div({
text: chalk.bold('Source:'),
width,
padding: [0, 0, 0, 5]
}, {
text: this.SOURCE
})
ui.div({
text: chalk.bold('Assets:'),
width,
padding: [0, 0, 0, 5]
}, {
text: this.ASSETS.map(asset => {
return asset.indexOf(path.join(this.SOURCE, '..')) < 0
? path.join(this.SOURCE, asset)
: asset
}).join('--')
})
ui.div({
text: chalk.bold('Output:'),
width,
padding: [0, 0, 0, 5]
}, {
text: this.OUTPUT
})
ui.div({
text: this.COLORS.subtle('Ignored:'),
width,
padding: [1, 0, 1, 5]
}, {
text: this.COLORS.subtle(this.IGNOREDLIST.join(', ')),
padding: [1, 0, 1, 0]
})
this.checkForUpdate(() => {
console.log(ui.toString())
next()
})
})
}
},
LOCAL_MONITOR: {
enumerable: false,
configurable: false,
writable: true,
value: null
},
COMMANDS: {
enumerable: false,
configurable: false,
writable: true,
value: cfg.commands || null
},
CLI_ARGUMENTS: {
enumerable: false,
configurable: false,
writable: true,
value: null
},
CURRENT_STEP: {
enumerable: false,
configurable: false,
writable: true,
value: 0
},
TIMER: {
enumerable: false,
configurable: false,
writable: true,
value: {
total: null,
markers: new Map()
}
},
REPORT: {
enumerable: false,
configurable: false,
writable: true,
value: []
},
NOTIFIED_OF_UPDATE: {
enumerable: false,
configurable: false,
writable: true,
value: false
},
MODULE_NAME: {
enumerable: false,
configurable: false,
writable: true,
value: path.basename(__dirname)
},
/**
* @property {Class} TaskRunner
* A [Shortbus](https://github.com/coreybutler/shortbus) task runner.
*/
TaskRunner: {
enumerable: true,
configurable: false,
writable: false,
value: TaskRunner
},
minimatch: {
enumerable: false,
configurable: false,
writable: false,
value: minimatch
}
})
}
get package () {
return this.PKG
}
get author () {
// No author?
if (!this.PKG.hasOwnProperty('author')) {
return require('os').userInfo().username
}
// Author specified as a string
if (typeof this.PKG.author === 'string') {
return this.PKG.author
}
// No name?
if (!this.PKG.author.hasOwnProperty('name')) {
return require('os').userInfo().username
}
// Has a name
return this.PKG.author.name
}
get name () {
if (this.PKG.hasOwnProperty('name')) {
return this.PKG.name
}
return 'Untitled'
}
get version () {
return this.APPVERSION
}
set header (value) {
if (value === null || value === undefined) {
delete this.HEADER
return
}
this.HEADER = value
}
set footer (value) {
if (value === null || value === undefined) {
delete this.FOOTER
return
}
this.FOOTER = value
}
get source () {
return this.SOURCE
}
set source (value) {
let oldpath = this.SOURCE
let newpath = path.resolve(value)
if (oldpath === newpath) {
return
}
try {
fs.accessSync(newpath, fs.constants.R_OK)
} catch (e) {
this.warn(`SOURCE DIRECTORY NOT FOUND: "${newpath}"`)
}
this.SOURCE = newpath
this.emit('source.updated', {
old: oldpath,
new: newpath
})
}
get output () {
return this.OUTPUT
}
set output (value) {
let oldpath = this.OUTPUT
let newpath = path.resolve(value)
if (oldpath === newpath) {
return
}
try {
fs.accessSync(newpath, fs.constants.R_OK)
} catch (e) {
this.warn(`OUTPUT DIRECTORY NOT FOUND: "${newpath}"`)
}
this.OUTPUT = newpath
this.emit('output.updated', {
old: oldpath,
new: newpath
})
}
set destination (value) {
this.output = path.resolve(value)
}
get destination () {
return this.OUTPUT
}
set assets (value) {
this.ASSETS = typeof value === 'string' ? [value] : value
}
get assets () {
return this.ASSETS
}
get Table () {
return CLITable
}
/**
* Set the list of paths to ignore (supports glob patterns).
* If you only want to add to the list, use #ignorePath instead.
* By default, `node_modules` is ignored, as well as anything
* in the ``.gitignore` file (if it exists) or a `.buildignore`
* file (if it exists).
* @param {Array} paths
* An array of paths to ignore in the build process.
*/
set ignore (value) {
this.IGNOREDLIST = value
}
/**
* Provides a reference to the watcher.
*/
get monitor () {
return this.LOCAL_MONITOR
}
/**
* @property {Boolean}
* @readonly
* Indicates the builder is in "watch" mode (monitoring the file system)
*/
get monitoring () {
return this.LOCAL_MONITOR !== null
}
/**
* @property {array}
* @readonly
* Returns the CLI arguments passed to the builder.
*/
get cliarguments () {
return this.CLI_ARGUMENTS
}
get File () {
return FileManager
}
get SemanticVersion () {
return require('semver')
}
// Retrieves the latest version number for the specified module.
checkModuleVersion (moduleName, callback) {
require('child_process').exec(`npm info ${moduleName} --json`, (err, data) => {
if (err) {
return callback(err)
}
try {
callback(null, JSON.parse(data).version)
} catch (e) {
callback(e)
}
})
}
checkForUpdate (callback) {
if (this.CHECKFORUPDATES && !this.NOTIFIED_OF_UPDATE) {
this.NOTIFIED_OF_UPDATE = true
this.checkModuleVersion(this.MODULE_NAME, (err, latestVersion) => {
if (!err) {
let currentVersion = this.version
if (this.MODULE_NAME !== this.name) {
currentVersion = require(path.join(process.cwd(), 'node_modules', this.MODULE_NAME, 'package.json')).version
}
if (this.SemanticVersion.lt(currentVersion, latestVersion)) {
console.log(this.COLORS.warn(`\n ** An update for ${this.MODULE_NAME} is available (${currentVersion} ==> `) + this.COLORS.success(latestVersion) + this.COLORS.warn(') **\n'))
}
}
callback && callback()
})
} else {
callback && callback()
}
}
identifyOutdatedModules (type = 'all', callback) {
if (this.CHECKFORUPDATES && this.PKG) {
let pkgModules = {}
let updateTasks = new TaskRunner()
let list = []
if ((type === 'all' || type === 'production') && this.PKG.hasOwnProperty('dependencies')) {
list = Object.keys(this.PKG.dependencies)
}
if ((type === 'all' || type === 'development') && this.PKG.hasOwnProperty('devDependencies')) {
list = list.concat(Object.keys(this.PKG.devDependencies))
}
list.forEach(mod => {
updateTasks.add(cont => {
this.checkModuleVersion(mod, (err, version) => {
let currentVersion = require(path.join(process.cwd(), 'node_modules', mod, 'package.json')).version
if (!err && this.SemanticVersion.lt(currentVersion, version)) {
pkgModules[mod] = {
current: currentVersion,
latest: version
}
}
cont()
})
})
})
updateTasks.on('complete', () => {
let mods = Object.keys(pkgModules)
if (mods.length > 0) {
let ui = new this.Table()
ui.div({
text: chalk.bold('Outdated Module'),
width: 20,
padding: [0, 0, 0, 3]
}, {
text: chalk.bold('Current'),
width: 10,
padding: [0, 0, 0, 0],
align: 'right'
}, {
text: '',
width: 5,
padding: [0, 1, 0, 1]
}, {
text: chalk.bold('Latest'),
width: 10,
padding: [0, 0, 0, 0],
align: 'left'
})
mods.forEach(mod => {
ui.div({
text: chalk.bold(this.COLORS.warn(mod)),
width: 20,
padding: [0, 0, 0, 3]
}, {
text: chalk.bold(this.COLORS.warn(pkgModules[mod].current)),
width: 10,
padding: [0, 0, 0, 0],
align: 'right'
}, {
text: this.COLORS.verysubtle('==>'),
width: 5,
padding: [0, 1, 0, 1]
}, {
text: chalk.bold(this.COLORS.success(pkgModules[mod].latest)),
width: 10,
padding: [0, 0, 0, 0],
align: 'left'
})
})
console.log(ui.toString())
}
})
updateTasks.run()
}
}
/**
* Ignore the contents of the specified file.
* This is automatically done for `.buildignore` and `.gitignore`.
* @param {[type]} file [description]
* @return {[type]} [description]
*/
ignoreFile (file) {
try {
this.IGNOREDLIST = this.IGNOREDLIST.concat(fs.readFileSync(path.resolve(file)).toString()
.replace(/#.*/gi, '')
.split(require('os').EOL)
.filter(glob => {
if (glob.trim().charAt(0) === '!') {
return false
}
return glob.trim().length > 0
}))
} catch (e) {}
}
/**
* A rounding method (like Math.round) that rounds to
* a specific number of decimal points.
* @param {number} number
* A float (decimal) number.
* @param {number} precision
* The number of decimal places.
* @return {number}
*/
round (number, precision) {
const factor = Math.pow(10, precision)
return Math.round(number * factor) / factor
}
// Returns the minimum number decimal places required to
// show a non-zero result.
minSignificantFigures () {
let min = 0
for (let i = 0; i < arguments.length; i++) {
let value = Math.abs(arguments[i]).toString().split('.').pop()
for (let x = 0; x < value.length; x++) {
if (value.charAt(x) !== '0') {
min = x > min ? x : min
break
}
}
}
return min + 1
}
/**
* Empty the output directory.
*/
clean () {
fs.emptyDir(this.OUTPUT)
}
/**
* This adds directories and/or files to the list of ignored files,
* where as setting the ignore property overrides the whole list.
* @param {String|Array} paths
* The path(s) to add to the list of ignored paths.
*/
ignorePath (dir) {
if (typeof dir === 'string') {
this.IGNOREDLIST.push(dir)
} else if (dir.length > 0) {
this.IGNOREDLIST = this.IGNOREDLIST.concat(dir)
}
}
/**
* Retrieves all files (recursively) within a directory.
* Supports glob patterns.
* @param {string} directory
* The directory to walk.
* @return {Array}
* An array containing the absolute path of each file in the directory.
*/
walk (directory, ignore = []) {
if (!directory) {
return []
}
let ignored = this.IGNOREDLIST.concat(ignore)
// Support globbing
if (glob.hasMagic(directory)) {
let root = './'
if (directory.startsWith(this.SOURCE)) {
root = this.SOURCE
directory = directory.replace(this.SOURCE, '')
} else if (directory.startsWith(this.OUTPUT)) {
root = this.OUTPUT
directory = directory.replace(this.OUTPUT, '')
}
return glob.sync(directory, {
cwd: root,
root,
ignore: ignored
})
}
// Walk the directory without globbing
let files = []
fs.readdirSync(directory).forEach(dir => {
let process = true
for (let i = 0; i < ignored.length; i++) {
if (minimatch(path.join(directory, dir), `/**/${ignored[i]}`)) {
process = false
break
}
}
if (process) {
if (fs.statSync(path.join(directory, dir)).isDirectory()) {
files = files.concat(this.walk(path.join(directory, dir)))
} else {
files.push(path.join(directory, dir))
}
}
})
return files
}
/**
* Read a file and autoconvert bytecode to a string.
* @param {String} filepath
* Absolute path of the input file.
* @param {Function} callback
* The content of the file is passed as the only attribute to the callback.
* If an error occurs, it is thrown.
*/
readFile (filepath, callback) {
fs.readFile(filepath, (err, content) => {
if (err) {
throw err
}
callback(content.toString().trim())
})
}
/**
* Read a file and autoconvert bytecode to a string.
* @param {String} filepath
* Absolute path of the input file.
* @return {String}
* The content of the file.
*/
readFileSync (filepath) {
return fs.readFileSync(filepath).toString().trim()
}
/**
* Write a file to disk.
* Almost the same as fs.writeFileSync (i.e. it overwrites),
* except if the parent directory does not exist, it's created.
* Accepts the same parameters as fs.writeFileSync.
*/
writeFileSync () {
fs.outputFileSync(...arguments)
}
/**
* Create the same path in the output directory as the input directory.
* @param {string} inputFilepath
* The path to mimic in the output directory.
* @return {string}
* The corresponding output path.
*/
outputDirectory (inputFilepath) {
let p = path.parse(inputFilepath)
inputFilepath = path.join(p.root, p.dir, p.base)
if (path.normalize(path.resolve(inputFilepath)) !== path.normalize(inputFilepath)) {
inputFilepath = path.join(this.OUTPUT, inputFilepath)
}
return inputFilepath.replace(this.SOURCE, this.OUTPUT)
}
/**
* Opposite of the output() method.
* @param {string} outputFilepath
* The output path to mimic in the source/input directory.
* @return {string}
* The corresponding input path.
*/
localDirectory (outFilepath) {
return outFilepath.replace(this.SOURCE, '').replace(this.OUTPUT, '')
}
/**
* The path, stripped of the preceding source/destination path.
* This is promarily used to create a _relative_ path.
* @param {String} path
* Abosulute/full path of the file.
* @return {String}
* The relative path from either the source or destination.
*/
relativePath (filepath) {
return ('./' + filepath.replace(this.SOURCE, '').replace(this.OUTPUT, '').trim()).replace(/\/{2,100}/, '/')
}
/**
* Apply text as a header to a file. This injects a comment at the top of
* the file, based on the content supplied to #header.
* @param {String} code
* The code/content to inject the header above.
* @param {String} [type='sh']
* The type of file. Supported values include `sh`, `sql`, `js`, `css`, and `html`.
* @return {String}
* Returns the code with the header content applied.
*/
applyHeader (code, type = 'js') {
if (!this.HEADER) {
return code
}
let msg = this.HEADER.split('\n')
switch (type.trim().toLowerCase()) {
case 'htm':
case 'html':
return '<!--\n' + msg.join('\n') + '\n-->\n' + code
case 'css':
case 'js':
if (msg.length === 1) {
return `// ${msg[0]}\n${code}`
}
return '/**\n' + msg.map(line => ` * ${line}`).join('\n') + '\n */\n' + code
case 'sql':
if (msg.length === 1) {
return `-- ${msg[0]}\n${code}`
}
return '/*\n' + msg.join('\n') + '\n*/\n' + code
case 'sh':
return msg.map(line => `# ${line}`).join('\n')
}
}
/**
* Apply text as a header to a file. This injects a comment at the top of
* the file, based on the content supplied to #footer.
* @param {String} code
* The code/content to inject the footer below.
* @param {String} [type='sh']
* The type of file. Supported values include `sh`, `sql`, `js`, `css`, and `html`.