/
helpers.js
1501 lines (1280 loc) · 42.4 KB
/
helpers.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
// Lint with JS Standard
// Import Node modules
const fs = require('fs-extra') // beyond normal fs, for working with the file-system
const fsPath = require('path') // Node's path tool, e.g. for normalizing paths cross-platform
const fsPromises = require('fs/promises') // Promise-based Node fs
const spawn = require('cross-spawn') // for spawning child processes like Jekyll across platforms
const open = require('open') // opens files in user's preferred app
const prince = require('prince') // installs and runs PrinceXML
const yaml = require('js-yaml') // reads YAML files into JS objects
const concatenate = require('concatenate') // concatenates files
const epubchecker = require('epubchecker') // checks epubs for validity
const pandoc = require('node-pandoc') // for converting files, e.g. html to word
const which = require('which') // finds installed executables
const childProcess = require('child_process') // creates child processes
const JSZip = require('jszip') // epub-friendly zip utility
const buildReferenceIndex = require('./reindex/build-reference-index.js')
const buildSearchIndex = require('./reindex/build-search-index.js')
const options = require('./options.js').options
// Output spawned-process data to console
function logProcess (process, processName) {
'use strict'
return new Promise(function (resolve, reject) {
processName = processName || 'Process: '
// Listen to stdout
process.stdout.on('data', function (data) {
console.log(processName + ': ' + data)
})
// Listen to stderr
process.stderr.on('data', function (data) {
console.log(processName + ': ' + data)
})
// Listen for an error event:
process.on('error', function (error) {
// console.log(processName + ' errored with: ' + error.message)
reject(error.message)
})
// Listen for an exit event:
process.on('close', function (exitCode) {
// console.log(processName + ' exited with: ' + exitCode)
if (exitCode !== 0) {
resolve(false)
} else {
resolve(true)
}
})
})
}
// Returns a filename for the output file
function outputFilename (argv) {
'use strict'
let filename
let fileExtension = '.pdf'
if (argv.format === 'epub') {
fileExtension = '.epub'
}
if (argv.language) {
filename = argv.book + '-' + argv.language + '-' + argv.format + fileExtension
} else {
filename = argv.book + '-' + argv.format + fileExtension
}
return filename
}
// Check if a user passed an explicit option in argv
// (i.e. yargs is not just using the default in options.js)
function explicitOption (option) {
'use strict'
// Default is that option was not passed explicitly
let optionWasExplicit = false
// Get all the aliases for this option
const aliases = options[option].alias
// Add the default option to that array
aliases.push(option)
// Check if any of those aliases were in the args
aliases.forEach(function (alias) {
// process.argv includes various strings in an array,
// including the options we want to examine.
// Those options have the original leading hyphens
// as they were passed at the command line.
// So we create a new array containing only the strings
// in process.argv that start with hyphens,
// and then we strip those hyphens.
const optionsInProcessArgv = []
process.argv.forEach(function (argument) {
if (argument.match(/^-+/)) {
const argumentWithoutHyphens = argument.replace(/^-+/, '')
optionsInProcessArgv.push(argumentWithoutHyphens)
}
})
// Now, is this alias among the options
// that were explicitly passed at the command line?
if (optionsInProcessArgv.includes(alias)) {
optionWasExplicit = true
}
})
return optionWasExplicit
}
// Checks if a file or folder exists
function pathExists (path) {
'use strict'
try {
if (fs.existsSync(fsPath.normalize(path))) {
return true
}
} catch (err) {
console.error(err)
return false
}
}
// Opens the output file. Accepts argv or a filepath.
function openOutputFile (argvOrFilePath) {
'use strict'
// If no filepath is provided, assume we're opening
// the book file we've just generated.
let filePath
if (argvOrFilePath.book) {
filePath = fsPath.normalize(process.cwd() +
'/_output/' +
outputFilename(argvOrFilePath))
console.log('Your ' + argvOrFilePath.format + ' is at ' + filePath)
} else {
filePath = argvOrFilePath
}
console.log('Opening ' + filePath)
open(fsPath.normalize(filePath))
}
// Return a string of Jekyll config files.
// The filenames passed must be of files
// already saved in the _configs directory.
// They will be added after the default _config.yml.
function configString (argv) {
'use strict'
// Start with default config
let string = '_config.yml'
// Add format config, if any
if (argv.format) {
string += ',_configs/_config.' + argv.format + '.yml'
}
// Add any configs passed as argv's
if (argv.configs) {
console.log('Adding ' + argv.configs + ' to configs...')
// Strip quotes that might have been added around arguments by user
string += ',_configs/' + argv.configs.replace(/'/g, '').replace(/"/g, '')
}
// Add MathJax config if --mathjax=true
if (argv.mathjax) {
string += ',_configs/_config.mathjax-enabled.yml'
}
// Turn Mathjax off if we're exporting to Word.
// We want raw editable TeX in Word docs.
if (argv._[0] === 'export' && argv['export-format'] === 'word') {
string += ',_configs/_config.math-disabled.yml'
}
// Add docx config if we're exporting to Word.
if (argv._[0] === 'export' && argv['export-format'] === 'word') {
string += ',_configs/_config.docx.yml'
}
return string
}
// Return array of switches for Jekyll
function jekyllSwitches (argv) {
'use strict'
const switchesArray = []
// Add incremental switch if --incremental=true
if (argv.incremental) {
switchesArray.push('--incremental')
}
// Add switches passed as a --switches="" argv
if (argv.switches) {
let switchesString = ''
// Strip quotes that might have been added around arguments by user
switchesString = argv.switches.replace(/'/g, '').replace(/"/g, '')
// Replace spaces with commans, then split the string into an array,
// and loop through the array adding each string to switchesArray.
const switchesStringAsArray = switchesString.replace(/\s/g, ',').split(',')
switchesStringAsArray.forEach(function (switchString) {
switchesArray.push(switchString)
})
}
return switchesArray
}
// Run Jekyll
async function jekyll (argv) {
'use strict'
// Use 'build' unless we're starting a webserver
let command = 'build'
if (argv.format === 'web' && argv._[0] === 'output') {
command = 'serve'
}
// Get the baseurl from Jekyll config, unless
// it's been overridden by one set in
// a --baseurl command-line argument
let baseurl = ''
if (configsObject(argv).baseurl) {
baseurl = configsObject(argv).baseurl
}
if (argv.baseurl) {
baseurl = argv.baseurl
}
// Ensure baseurl string starts with a slash
if (baseurl !== '' && baseurl.indexOf('/') !== 0) {
baseurl = '/' + baseurl
}
// Build the string of config files.
// We need the configs string passed to argv
// plus any auto-generated excludes config
let configs = configString(argv)
const extraConfigs = await extraExcludesConfig(argv)
if (extraConfigs) {
configs += ',' + extraConfigs
}
try {
console.log('Running Jekyll with command: ' +
'bundle exec jekyll ' + command +
' --config="' + configString(argv) + '"' +
' --baseurl="' + baseurl + '"' +
' ' + jekyllSwitches(argv).join(' '))
// Create an array of arguments to pass to spawn()
const jekyllSpawnArgs = ['exec', 'jekyll', command,
'--config', configs,
'--baseurl', baseurl]
// Add each of the switches to the args array
jekyllSwitches(argv).forEach(function (switchString) {
jekyllSpawnArgs.push(switchString)
})
// Create a child process
const jekyllProcess = spawn('bundle', jekyllSpawnArgs)
const result = await logProcess(jekyllProcess, 'Jekyll')
// If Jekyll fails (i.e. exit code 1), kill this process.
// We don't want to try to render a PDF if Jekyll didn't build.
if (result === 1) {
console.log('Jekyll could not complete its build. Exiting.')
process.exit()
}
return result
} catch (error) {
console.log(error)
}
}
// Jekyll configs as JS object. Note:
// This includes duplicate keys where concatenated
// config files have the same keys. That's not
// valid YAML, but it's okay in JSON, where
// the last value overrides earlier ones.
function configsObject (argv) {
'use strict'
// Create an array of paths to the config files
const configFiles = configString(argv).split(',')
configFiles.map(function (file) {
return fsPath.normalize(file)
})
// Combine them and load them as a JSON array
const concatenated = concatenate.sync(configFiles)
const json = yaml.loadAll(concatenated, { json: true })
// Return the first object of the first object of the array
return json[0]
}
// Config to exclude unnecessary books from Jekyll build
async function extraExcludesConfig (argv) {
'use strict'
// Default is an empty config file, for no excludes.
// Create it and/or make it an empty file.
const pathToTempExcludesConfig = '_output/.temp/_config.excludes.yml'
await fsPromises.mkdir('_output/.temp', { recursive: true })
await fsPromises.writeFile(pathToTempExcludesConfig, '')
// If we're outputting a particular book/work,
// and the user explicitly asked for that book
// (as opposed to omitting --book and using defaults),
// exclude any other works in this project
// by adding them to a Jekyll `exclude` config.
if (argv.book && explicitOption('book')) {
// Get all the works but leave out the argv.book we want
const worksToExclude = works().filter(function (work) {
return work !== argv.book
})
// Get the current excludes list
const excludes = configsObject(argv).exclude
// Add the works we're not outputting to it
const newExcludes = excludes.concat(worksToExclude)
// That's only the list of values. To create a valid
// key:value property, we need the `excludes:` key.
const excludesProperty = {
exclude: newExcludes
}
// Write the new excludes config as a YAML file
const excludesYAML = yaml.dump(excludesProperty)
await fsPromises.writeFile(pathToTempExcludesConfig, excludesYAML)
}
// Return the path to the new excludes config
return pathToTempExcludesConfig
}
// Run Cordova with args.
// - args is an array of arguments
// - cordovaWorkingDirectory is the directory in which
// cordova must run, e.g. _site/app
async function cordova (args, cordovaWorkingDirectory) {
'use strict'
// Create a default/fallback working directory
if (!cordovaWorkingDirectory) {
cordovaWorkingDirectory = fsPath.normalize(process.cwd() + '/_site/app')
}
try {
console.log('Running Cordova with ' + JSON.stringify(args) +
' from\n' + cordovaWorkingDirectory)
const cordovaProcess = spawn('cordova', args, { cwd: cordovaWorkingDirectory })
const result = await logProcess(cordovaProcess, 'Cordova')
return result
} catch (error) {
console.log(error)
}
}
// Assemble app files
async function assembleApp () {
'use strict'
// Move everything in the _site folder to _site/app
// except, of course, _site/app itself.
const source = fsPath.normalize(process.cwd() + '/_site')
const destination = fsPath.normalize(process.cwd() + '/_site/app/www')
const pathsInSource = await fsPromises.readdir(source, { withFileTypes: true })
pathsInSource.forEach(function (entry) {
if (entry.name !== 'app') {
fs.moveSync(source + fsPath.sep + entry.name, destination + fsPath.sep + entry.name)
}
})
}
// Check if MathJax is enabled in config or CLI arguments
function mathjaxEnabled (argv) {
'use strict'
// Check if Mathjax is enabled in Jekyll config
const mathjaxConfig = configsObject(argv)['mathjax-enabled']
// Is mathjax on either in config
// or activated by argv option?
let mathJaxOn = false
if (argv.mathjax || mathjaxConfig === true) {
mathJaxOn = true
}
return mathJaxOn
}
// Processes mathjax in output HTML
async function renderMathjax (argv) {
'use strict'
try {
if (mathjaxEnabled(argv) || argv.mathjax) {
console.log('Rendering MathJax...')
// Get the HTML file(s) to render. If we are merging
// input files, we only pass the merged file,
// Unless `--merged false` was passed at the command line.
let inputFiles = [fsPath.dirname(htmlFilePaths(argv)[0]) + '/merged.html']
if (argv.merged === false || ['web', 'epub', 'app'].includes(argv.format)) {
inputFiles = htmlFilePaths(argv)
}
// Get the MathJax script
const mathJaxScript = process.cwd() +
'/_tools/run/helpers/mathjax/tex2mml-page.js'
// Process MathJax
let mathJaxProcess
inputFiles.forEach(function (path) {
mathJaxProcess = spawn(
'node',
['-r', 'esm', mathJaxScript, path, path, argv.format]
)
})
await logProcess(mathJaxProcess, 'Rendering MathJax')
return true
} else {
return true
}
} catch (error) {
console.log(error)
}
}
// Processes index comments as targets in output HTML
async function renderIndexComments (argv) {
'use strict'
if (projectSettings()['dynamic-indexing'] !== false) {
console.log('Processing indexing comments ...')
try {
let indexCommentsProcess
if (argv.language) {
indexCommentsProcess = spawn(
'gulp',
['renderIndexCommentsAsTargets',
'--book', argv.book,
'--language', argv.language]
)
} else {
indexCommentsProcess = spawn(
'gulp',
['renderIndexCommentsAsTargets', '--book', argv.book]
)
}
await logProcess(indexCommentsProcess, 'Index comments')
return true
} catch (error) {
console.log(error)
}
}
}
// Processes index-list items as linked references in output HTML
async function renderIndexLinks (argv) {
'use strict'
if (projectSettings()['dynamic-indexing'] !== false) {
console.log('Adding links to reference indexes ...')
try {
let indexLinksProcess
if (argv.language) {
indexLinksProcess = spawn(
'gulp',
['renderIndexListReferences',
'--book', argv.book,
'--language', argv.language,
'--format', argv.format]
)
} else {
indexLinksProcess = spawn(
'gulp',
['renderIndexListReferences',
'--book', argv.book,
'--format', argv.format]
)
}
await logProcess(indexLinksProcess, 'Index links')
return true
} catch (error) {
console.log(error)
}
}
}
// Converts paths in links from *.html to *.xhtml
async function convertXHTMLLinks (argv) {
'use strict'
console.log('Converting links from .html to .xhtml ...')
try {
let convertXHTMLLinksProcess
if (argv.language) {
convertXHTMLLinksProcess = spawn(
'gulp',
['epubXhtmlLinks',
'--book', argv.book,
'--language', argv.language]
)
} else {
convertXHTMLLinksProcess = spawn(
'gulp',
['epubXhtmlLinks', '--book', argv.book]
)
}
await logProcess(convertXHTMLLinksProcess, 'XHTML links')
return true
} catch (error) {
console.log(error)
}
}
// Converts .html files to .xhtml, e.g. for epub output
async function convertXHTMLFiles (argv) {
'use strict'
console.log('Renaming files from .html to .xhtml ...')
try {
let convertXHTMLFilesProcess
if (argv.language) {
convertXHTMLFilesProcess = spawn(
'gulp',
['epubXhtmlFiles',
'--book', argv.book,
'--language', argv.language]
)
} else {
convertXHTMLFilesProcess = spawn(
'gulp',
['epubXhtmlFiles', '--book', argv.book]
)
}
await logProcess(convertXHTMLFilesProcess, 'XHTML files')
return true
} catch (error) {
console.log(error)
}
}
// Get project settings from settings.yml
function projectSettings () {
'use strict'
let settings
try {
settings = yaml.load(fs.readFileSync('./_data/settings.yml', 'utf8'))
} catch (error) {
console.log(error)
}
return settings
}
// Get the filelist for a format
function fileList (argv) {
'use strict'
let format
if (argv.format) {
format = argv.format
} else {
format = 'print-pdf' // fallback
}
// Check for variant-edition output
let variant = false
if (projectSettings()['active-variant'] &&
projectSettings()['active-variant'] !== '') {
variant = projectSettings()['active-variant']
}
let book = 'book' // default
if (argv.book) {
book = argv.book
}
// Build path to YAML data for this book
const pathToYAMLFolder = process.cwd() +
'/_data/works/' +
book + '/'
// Build path to default-edition YAML
const pathToDefaultYAML = fsPath.normalize(pathToYAMLFolder + 'default.yml')
// Get the files list
const metadata = yaml.load(fs.readFileSync(pathToDefaultYAML, 'utf8'))
let files = metadata.products[format].files
// If there was no files list, oops!
if (!files) {
console.log('No files list in book data. Using raw files in ' + book + '.')
// Let's just use all the markdown files for this book
const bookDirectory = fsPath.normalize(process.cwd() + '/' + book + '/')
files = []
// Read the contents of the book directory.
// For each file in there, if it ends with .md,
// add its name, without the .md, to the files array.
if (fs.lstatSync(bookDirectory).isDirectory()) {
fs.readdirSync(bookDirectory)
.forEach(function (file) {
if (file.match(/\.md$/g)) {
const fileBasename = file.replace(/\.md$/g, '')
files.push(fileBasename)
}
})
// If there is an index.md, move it to the front
// (https://stackoverflow.com/a/48456512/1781075),
// unless there is a cover file, in which case omit index.md.
// Determine if there is a cover file.
// This depends on the only word in the filename being 'cover',
// e.g. 0-0-cover.html, cover.html. But not 'my-cover.html',
// 'cover-page.html' or 'cover-versions-of-songs.html'.
let coverFile = false
files.forEach(function (filename) {
console.log(filename);
// Remove all non-alphabetical-characters
const filenameWordsOnly = filename.replace(/[^a-zA-Z]/g, '')
// Is what remains the word 'cover'?
if (filenameWordsOnly === 'cover') {
coverFile = filename
const indexOfCoverFile = files.findIndex(function (filename) {
return filename === coverFile
})
// Move it to the front of the array:
// remove it first...
files.splice(indexOfCoverFile, 1)
// ... then insert it unless this is a print PDF
if (argv.format !== 'print-pdf') {
files.unshift(coverFile)
}
}
})
if (files.includes('index')) {
const indexOfIndexFile = files.findIndex(function (filename) {
return filename === 'index'
})
// Remove 'index' from array
files.splice(indexOfIndexFile, 1)
// If no cover file, insert 'index' at start of array
// unless this is a print PDF
if (coverFile === false && argv.format !== 'print-pdf') {
files.unshift('index')
}
}
} else {
// Otherwise, return an empty array
console.log('Sorry, couldn\'t find files or a files list in book data.')
return []
}
}
// Build path to translation's default YAML,
// if a language has been specified.
let pathToTranslationYAMLFolder,
pathToDefaultTranslationYAML
if (argv.language) {
pathToTranslationYAMLFolder = pathToYAMLFolder + argv.language + '/'
pathToDefaultTranslationYAML = pathToTranslationYAMLFolder + 'default.yml'
// If the translation has this format among its products,
// and that format has a files list, use that list.
if (pathToDefaultTranslationYAML &&
pathExists(pathToDefaultTranslationYAML)) {
const translationMetadata = yaml.load(fs.readFileSync(pathToDefaultTranslationYAML, 'utf8'))
if (translationMetadata &&
translationMetadata.products &&
translationMetadata.products[format] &&
translationMetadata.products[format].files) {
files = translationMetadata.products[format].files
}
}
}
// Build path to variant-edition YAML,
// if there is an active variant in settings.
let pathToVariantYAML = false
// If there's a variant and this is a translation ...
if (argv.language && variant) {
pathToVariantYAML = pathToTranslationYAMLFolder + variant + '.yml'
// ... otherwise just get the parent language variant path
} else if (variant) {
pathToVariantYAML = pathToYAMLFolder + variant + '.yml'
}
// If we have a path, and there's a files list there,
// use that as the files list.
if (pathToVariantYAML &&
pathExists(pathToVariantYAML)) {
const variantMetadata = yaml.load(fs.readFileSync(pathToVariantYAML, 'utf8'))
if (variantMetadata &&
variantMetadata.products &&
variantMetadata.products[format] &&
variantMetadata.products[format].files) {
files = variantMetadata.products[format].files
}
}
// Note that files may be objects, not strings,
// e.g. { "01": "Chapter 1"}
return files
}
// Get array of HTML-file paths for this output
function htmlFilePaths (argv, extension) {
'use strict'
const fileNames = fileList(argv)
if (!extension) {
extension = '.html'
}
// Provide fallback book
let book
if (argv.book) {
book = argv.book
} else {
book = 'book'
}
let pathToFiles
if (argv.language) {
pathToFiles = process.cwd() + '/' +
'_site/' +
book + '/' +
argv.language
} else {
pathToFiles = process.cwd() + '/' +
'_site/' +
book
}
pathToFiles = fsPath.normalize(pathToFiles)
console.log('Using files in ' + pathToFiles)
// Extract filenames from file objects,
// and prepend path to each filename.
const paths = fileNames.map(function (filename) {
if (typeof filename === 'object') {
return fsPath.normalize(pathToFiles + '/' +
Object.keys(filename)[0] + extension)
} else {
return fsPath.normalize(pathToFiles + '/' +
filename + extension)
}
})
return paths
}
// Cleans out old .html files after .xhtml conversions
async function cleanHTMLFiles (argv) {
'use strict'
console.log('Cleaning out old .html files ...')
try {
let cleanHTMLFilesProcess
if (argv.language) {
cleanHTMLFilesProcess = spawn(
'gulp',
['epubCleanHtmlFiles',
'--book', argv.book,
'--language', argv.language]
)
} else {
cleanHTMLFilesProcess = spawn(
'gulp',
['epubCleanHtmlFiles', '--book', argv.book]
)
}
await logProcess(cleanHTMLFilesProcess, 'Clean HTML files')
return true
} catch (error) {
console.log(error)
}
}
// Check Prince version
function checkPrinceVersion () {
'use strict'
// Get globally installed Prince version, if any
const installedPrince = function () {
return new Promise(function (resolve, reject) {
// Check local node_modules for Prince binary ...
if (prince().config.binary.includes('node_modules')) {
childProcess.execFile(prince().config.binary, ['--version'], function (error, stdout, stderr) {
if (error !== null) {
console.log('Could not get Prince version:\n')
reject(error)
return
}
const m = stdout.match(/^Prince\s+(\d+(?:\.\d+)?)/)
if (!(m !== null && typeof m[1] !== 'undefined')) {
error = 'Prince version check returned unexpected output:\n' + stdout + stderr
reject(error)
return
}
resolve(m[1])
})
} else {
// ... or else check the global PATH
which('prince', function (error, filename) {
if (error) {
console.log('Prince not found in PATH:\n')
reject(error)
return
}
childProcess.execFile(filename, ['--version'], function (error, stdout, stderr) {
if (error !== null) {
console.log('Could not get Prince version:\n')
reject(error)
return
}
const m = stdout.match(/^Prince\s+(\d+(?:\.\d+)?)/)
if (!(m !== null && typeof m[1] !== 'undefined')) {
error = 'Prince version check returned unexpected output:\n' + stdout + stderr
reject(error)
return
}
resolve(m[1])
})
})
}
})
}
// Check global Prince version vs version defined in package.json
installedPrince().then(function (installedVersion) {
const packageJSON = require(process.cwd() + '/package.json')
let preferredPrinceVersion
if (packageJSON.prince && packageJSON.prince.version) {
preferredPrinceVersion = packageJSON.prince.version
if (installedVersion !== preferredPrinceVersion) {
console.log('\nWARNING: your installed Prince version is ' + installedVersion +
' but your project requires ' + preferredPrinceVersion + '\n' +
'You should delete node_modules/prince and run: npm install\n')
} else {
console.log('Prince version matches preferred version in package.json.')
}
}
}, function (error) {
console.log(error)
})
}
// Run Prince
async function runPrince (argv) {
'use strict'
return new Promise(function (resolve, reject) {
console.log('Rendering HTML to PDF with PrinceXML...')
// Get Prince license file, if any
// (and allow for 'correct' spelling, licence).
let princeLicenseFile = ''
let princeLicensePath
const princeConfig = require(process.cwd() + '/package.json').prince
if (princeConfig && princeConfig.license) {
princeLicensePath = princeConfig.license
} else if (princeConfig && princeConfig.licence) {
princeLicensePath = fsPath.normalize(princeConfig.licence)
}
if (fs.existsSync(princeLicensePath)) {
princeLicenseFile = princeLicensePath
console.log('Using PrinceXML licence found at ' + princeLicenseFile)
}
// Check if we're using the correct Prince version
checkPrinceVersion()
// Get the HTML file to render. If we are merging
// input files, we only pass the merged file to Prince.
// Unless `--merged false` was passed at the command line.
let inputFiles = [fsPath.dirname(htmlFilePaths(argv)[0]) + '/merged.html']
if (argv.merged === false) {
inputFiles = htmlFilePaths(argv)
}
// Currently, node-prince does not seem to
// log its progress to stdout. Possible WIP:
// https://github.com/rse/node-prince/pull/7
prince()
.license('./' + princeLicenseFile)
.inputs(inputFiles)
.output(process.cwd() + '/_output/' + outputFilename(argv))
.option('javascript')
.option('verbose')
.timeout(100 * 1000) // required for larger books
.on('stderr', function (line) { console.log(line) })
.on('stdout', function (line) { console.log(line) })
.execute()
.then(function (executionResult) {
resolve()
}, function (error) {
console.log(error)
reject(error)
})
})
}
// Zip an epub folder
async function epubZip () {
'use strict'
return new Promise(function (resolve, reject) {
// Check if the directory exists
const uncompressedEpubDirectory = fsPath.normalize(process.cwd() +
'/_site/epub')
if (!pathExists(uncompressedEpubDirectory)) {
throw new Error('Sorry, could not find ' + uncompressedEpubDirectory + '.')
}
// Thanks https://github.com/lostandfound/epub-zip
// for the initial idea for this.
// Note that we use path.posix (not just path) because
// EPUBCheck needs forward slashes in paths, otherwise
// it cannot find META-INF/container.xml in epubs
// generated on Windows machines.
function getFiles (root, files, base) {
'use strict'
base = base || ''
files = files || []
const directory = fsPath.posix.join(root, base)
// Files and folders to skip. For instance,
// don't add the mimetype file, we'll create that
// when we zip, so that we can add it specially.
const skipFiles = /^(mimetype)$/
if (fs.lstatSync(directory).isDirectory()) {
fs.readdirSync(directory)
.forEach(function (file) {
if (!file.match(skipFiles)) {
getFiles(root, files, fsPath.posix.join(base, file))
}
})
} else {
files.push(base)
}
return files
}
try {
// Get the files to zip
const files = getFiles(uncompressedEpubDirectory)
// Create a new instance of JSZip
const zip = new JSZip()
// Add an uncompressed mimetype file first
zip.file('mimetype', 'application/epub+zip', { compression: 'STORE' })
// Add all the files
files.forEach(function (file) {
console.log('Adding ' + file + ' to zip.')
zip.file(file,
fs.readFileSync(fsPath.posix.join(uncompressedEpubDirectory, file)), { compression: 'DEFLATE' })
})
// Write the zip file to disk