-
Notifications
You must be signed in to change notification settings - Fork 93
/
build.js
812 lines (722 loc) · 29.5 KB
/
build.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
#!/usr/bin/env node
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const fsextra = require('fs-extra');
let docsifyTemplate = require('./docsify.template.js');
const markdownpdf = require('md-to-pdf').mdToPdf;
const http = require('http');
const DIST_BACKUP_FOLDER_SUFFIX = '_bk';
const {
encodeURIPath,
makeDirectory,
readFile,
writeFile,
plantUmlServerUrl,
plantumlVersions
} = require('./utils.js');
const { date } = require('joi');
const getMime = (format) => {
if (format == 'svg') return `image/svg+xml`;
return `image/${format}`;
};
const httpGet = async (url) => {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page ' + url + ', status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(Buffer.concat(body).toString('base64')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err));
});
};
const getFolderName = (dir, root, homepage) => {
return dir === root ? homepage : path.parse(dir).base;
};
const generateTree = async (dir, options) => {
let tree = [];
const build = async (dir, parent) => {
let name = getFolderName(dir, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
let item = tree.find((x) => x.dir === dir);
if (!item) {
item = {
dir: dir,
name: name,
level: dir.split(path.sep).length,
parent: parent,
mdFiles: [],
pumlFiles: [],
descendants: []
};
tree.push(item);
}
let files = fs.readdirSync(dir).filter((x) => x.charAt(0) !== '_');
for (const file of files) {
//if folder
if (fs.statSync(path.join(dir, file)).isDirectory()) {
item.descendants.push(file);
//create corresponding dist folder
if (
options.GENERATE_WEBSITE ||
options.GENERATE_MD ||
options.GENERATE_PDF ||
options.GENERATE_LOCAL_IMAGES
)
await makeDirectory(
path.join(options.DIST_FOLDER, dir.replace(options.ROOT_FOLDER, ''), file)
);
await build(path.join(dir, file), dir);
}
}
const mdFiles = files.filter((x) => path.extname(x).toLowerCase() === '.md');
for (const mdFile of mdFiles) {
const fileContents = await readFile(path.join(dir, mdFile));
item.mdFiles.push(fileContents);
}
const pumlFiles = files.filter((x) => path.extname(x).toLowerCase() === '.puml');
for (const pumlFile of pumlFiles) {
const fileContents = await readFile(path.join(dir, pumlFile));
const isDitaa = !!(fileContents ? fileContents.toString() : '').match(/(@startditaa)/gi);
item.pumlFiles.push({ dir: pumlFile, content: fileContents, isDitaa });
}
item.pumlFiles.sort(function (a, b) {
return ('' + a.dir).localeCompare(b.dir);
});
//copy all other files
const otherFiles = options.EXCLUDE_OTHER_FILES
? []
: files.filter(
(x) => x.charAt(0) === '_' || ['.md', '.puml'].indexOf(path.extname(x).toLowerCase()) === -1
);
for (const otherFile of otherFiles) {
if (fs.statSync(path.join(dir, otherFile)).isDirectory()) continue;
if (options.GENERATE_MD || options.GENERATE_PDF || options.GENERATE_WEBSITE)
await fsextra.copy(
path.join(dir, otherFile),
path.join(options.DIST_FOLDER, dir.replace(options.ROOT_FOLDER, ''), otherFile)
);
if (options.GENERATE_COMPLETE_PDF_FILE || options.GENERATE_COMPLETE_MD_FILE)
await fsextra.copy(path.join(dir, otherFile), path.join(options.DIST_FOLDER, otherFile));
}
};
await build(dir);
return tree;
};
const generateImages = async (tree, options, onImageGenerated, conf) => {
// Get the old checksums (from last run) of all PUML-files
let oldChecksums = conf.get('checksums') || [];
let newChecksums = [];
const bkFolderName = options.DIST_FOLDER + DIST_BACKUP_FOLDER_SUFFIX;
let totalImages = 0;
let processedImages = 0;
let ver = plantumlVersions.find((v) => v.version === options.PLANTUML_VERSION);
if (options.PLANTUML_VERSION === 'latest') ver = plantumlVersions.find((v) => v.isLatest);
if (!ver) throw new Error(`PlantUML version ${options.PLANTUML_VERSION} not supported`);
const crypto = require('crypto');
for (const item of tree) {
totalImages += item.pumlFiles.length;
}
for (const item of tree) {
for (const pumlFile of item.pumlFiles) {
//There was a bug with this, that's why I require it inside the loop
process.env.PLANTUML_HOME = path.join(__dirname, 'vendor', ver.jar);
const plantuml = require('node-plantuml');
// Calculate hash of current puml content
let cksum = crypto
.createHash('sha256')
.update('' + pumlFile.content || '', 'utf-8')
.digest('hex');
// path to backup image file
let bkFilePath = path.join(
bkFolderName,
item.dir.replace(options.ROOT_FOLDER, ''),
`${path.parse(pumlFile.dir).name}.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
);
// path to image in dist folder
let filePath = path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${path.parse(pumlFile.dir).name}.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
);
// if checksum exists (PUML untouched) and file/image exists - copy image back from backup folder
if (oldChecksums.find((x) => x === cksum) && (await fs.existsSync(bkFilePath))) {
await fsextra.copyFileSync(bkFilePath, filePath);
} else {
//write diagram as image
let stream = fs.createWriteStream(filePath);
plantuml
.generate(path.join(item.dir, pumlFile.dir), {
format: pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT,
charset: options.CHARSET,
include: item.dir
})
.out.pipe(stream);
await new Promise((resolve) => stream.on('finish', resolve));
}
processedImages++;
if (onImageGenerated) onImageGenerated(processedImages, totalImages);
// Add puml checksum
newChecksums.push(cksum);
}
}
// store all puml checksums
conf.set('checksums', newChecksums);
};
const compileDocument = async (md, item, options, getDiagram) => {
let MD = md;
const alreadyIncludedPumls = [];
const texts = [];
const diagrams = [];
const regex = /(?:!\[.*?\]\()(.*\.puml)(\))/g;
for (const mdFile of item.mdFiles) {
let content = mdFile.toString();
let pumlRef;
while ((pumlRef = regex.exec(content)) !== null) {
if (pumlRef && pumlRef[1]) {
const pumlFile = item.pumlFiles.find((x) => x.dir === pumlRef[1]);
if (pumlFile) {
alreadyIncludedPumls.push(pumlRef[1]);
content = content.replace(pumlRef[0], await getDiagram(item, pumlFile, options));
}
}
}
texts.push(content);
}
for (const pumlFile of item.pumlFiles) {
if (alreadyIncludedPumls.find((x) => x === pumlFile.dir)) {
continue;
}
diagrams.push(await getDiagram(item, pumlFile, options));
}
let fullDoc = [];
if (options.DIAGRAMS_ON_TOP) {
fullDoc = [...diagrams, ...texts];
} else {
fullDoc = [...texts, ...diagrams];
}
for (const doc of fullDoc) {
MD += '\n\n';
MD += doc;
}
return MD;
};
const generateCompleteMD = async (tree, options) => {
let filePromises = [];
//title
let MD = `# ${options.PROJECT_NAME}`;
//table of contents
let tableOfContents = '';
for (const item of tree)
tableOfContents += `${' '.repeat(item.level - 1)}* [${item.name}](#${encodeURIPath(
item.name
).replace(/%20/g, '-')})\n`;
MD += `\n\n${tableOfContents}\n---`;
for (const item of tree) {
let name = getFolderName(item.dir, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
//title
MD += `\n\n## ${name}`;
if (name !== options.HOMEPAGE_NAME) {
if (options.INCLUDE_BREADCRUMBS) MD += `\n\n\`${item.dir.replace(options.ROOT_FOLDER, '')}\``;
MD += `\n\n[${options.HOMEPAGE_NAME}](#${encodeURIPath(options.PROJECT_NAME).replace(
/%20/g,
'-'
)})`;
}
//concatenate markdown files
MD = await compileDocument(MD, item, options, async (item, pumlFile, options) => {
let diagramUrl = encodeURIPath(
path.join(
path.dirname(pumlFile.dir),
path.parse(pumlFile.dir).name + `.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
)
);
if (!options.GENERATE_LOCAL_IMAGES)
diagramUrl = plantUmlServerUrl(
options.PLANTUML_SERVER_URL,
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT,
pumlFile.content
);
if (options.EMBED_DIAGRAM) {
let imgContent = '';
if (options.GENERATE_LOCAL_IMAGES)
imgContent = (
await readFile(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
diagramUrl
)
)
).toString('base64');
else imgContent = await httpGet(diagramUrl);
let diagramImage = `\n![${path.parse(pumlFile.dir).name}](data:${getMime(
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT
)};base64,${imgContent})\n`;
let diagramLink = `\n[Download ${path.parse(pumlFile.dir).name} diagram](${encodeURIPath(
path.join(item.dir.replace(options.ROOT_FOLDER, ''), diagramUrl)
)} ':ignore')`;
return diagramImage + diagramLink;
} else {
let diagramImage = `![diagram](${diagramUrl})`;
let diagramLink = `[Go to ${path.parse(pumlFile.dir).name} diagram](${encodeURIPath(
path.join(item.dir.replace(options.ROOT_FOLDER, ''), diagramUrl)
)})`;
if (!options.INCLUDE_LINK_TO_DIAGRAM)
//img
return diagramImage;
//link
else return diagramLink;
}
});
}
//write file to disk
filePromises.push(writeFile(path.join(options.DIST_FOLDER, `${options.PROJECT_NAME}.md`), MD));
return Promise.all(filePromises);
};
const generateCompletePDF = async (tree, options) => {
//title
let MD = `# ${options.PROJECT_NAME}`;
//table of contents
let tableOfContents = '';
for (const item of tree)
tableOfContents += `${' '.repeat(item.level - 1)}* [${item.name}](#${encodeURIPath(
item.name
).replace(/%20/g, '-')})\n`;
MD += `\n\n${tableOfContents}\n---`;
for (const item of tree) {
let name = getFolderName(item.dir, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
//title
MD += `\n\n## ${name}`;
//bradcrumbs
if (name !== options.HOMEPAGE_NAME) {
if (options.INCLUDE_BREADCRUMBS) MD += `\n\n\`${item.dir.replace(options.ROOT_FOLDER, '')}\``;
}
//concatenate markdown files
MD = await compileDocument(MD, item, options, async (item, pumlFile, options) => {
let diagramUrl = encodeURIPath(
path.join(
item.dir.replace(options.ROOT_FOLDER, ''),
path.parse(pumlFile.dir).name + `.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
)
);
if (!options.GENERATE_LOCAL_IMAGES)
diagramUrl = plantUmlServerUrl(
options.PLANTUML_SERVER_URL,
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT,
pumlFile.content
);
let diagramImage = `![diagram](${diagramUrl})`;
return diagramImage;
});
}
//write temp file
await writeFile(path.join(options.DIST_FOLDER, `${options.PROJECT_NAME}_TEMP.md`), MD);
//convert to pdf
await markdownpdf(
{
path: './' + path.join(options.DIST_FOLDER, `${options.PROJECT_NAME}_TEMP.md`)
},
{
stylesheet: [options.PDF_CSS],
pdf_options: {
scale: 1,
displayHeaderFooter: false,
printBackground: true,
landscape: false,
pageRanges: '',
format: 'A4',
width: '',
height: '',
margin: {
top: '1.5cm',
right: '1cm',
bottom: '1cm',
left: '1cm'
}
},
dest: path.join(options.DIST_FOLDER, `${options.PROJECT_NAME}.pdf`)
}
).catch(console.error);
// remove temp file
await fsextra.remove(path.join(options.DIST_FOLDER, `${options.PROJECT_NAME}_TEMP.md`));
};
const generateMD = async (tree, options, onProgress) => {
let processedCount = 0;
let totalCount = tree.length;
let filePromises = [];
for (const item of tree) {
let name = getFolderName(item.dir, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
//title
let MD = `# ${name}`;
//bradcrumbs
if (options.INCLUDE_BREADCRUMBS && name !== options.HOMEPAGE_NAME)
MD += `\n\n\`${item.dir.replace(options.ROOT_FOLDER, '')}\``;
//table of contents
if (options.INCLUDE_TABLE_OF_CONTENTS) {
let tableOfContents = '';
for (const _item of tree) {
let isDown = item.level < _item.level;
let label = `${item.dir === _item.dir ? '**' : ''}${_item.name}${
item.dir === _item.dir ? '**' : ''
}`;
tableOfContents += `${' '.repeat(_item.level - 1)}* [${label}](${encodeURIPath(
path.join(
// '/',
// options.DIST_FOLDER,
'./',
item.level - 1 > 0 ? '../'.repeat(item.level - 1) : '',
_item.dir.replace(options.ROOT_FOLDER, ''),
`${options.MD_FILE_NAME}.md`
)
)})\n`; //slice 1 if root and down
}
MD += `\n\n${tableOfContents}\n---`;
}
//parent menu
if (item.parent && options.INCLUDE_NAVIGATION) {
let parentName = getFolderName(item.parent, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
MD += `\n\n[${parentName} (up)](${encodeURIPath(
path.join(
// '/',
// options.DIST_FOLDER,
'./',
item.level - 1 > 0 ? '../'.repeat(item.level - 1) : '',
item.parent.replace(options.ROOT_FOLDER, ''),
`${options.MD_FILE_NAME}.md`
)
)})`;
}
//exclude files and folders prefixed with _
let descendantsMenu = '';
for (const file of item.descendants) {
descendantsMenu += `\n\n- [${file}](${encodeURIPath(
path.join(
// '/',
// options.DIST_FOLDER,
'./',
item.level - 1 > 0 ? '../'.repeat(item.level - 1) : '',
item.dir.replace(options.ROOT_FOLDER, ''),
file,
`${options.MD_FILE_NAME}.md`
)
)})`;
}
//descendants menu
if (descendantsMenu && options.INCLUDE_NAVIGATION) MD += `${descendantsMenu}`;
//separator
if (options.INCLUDE_NAVIGATION) MD += `\n\n---`;
//concatenate markdown files
MD = await compileDocument(MD, item, options, async (item, pumlFile, options) => {
let diagramUrl = encodeURIPath(
path.join(
path.dirname(pumlFile.dir),
path.parse(pumlFile.dir).name + `.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
)
);
if (!options.GENERATE_LOCAL_IMAGES)
diagramUrl = plantUmlServerUrl(
options.PLANTUML_SERVER_URL,
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT,
pumlFile.content
);
if (options.EMBED_DIAGRAM) {
let imgContent = '';
if (options.GENERATE_LOCAL_IMAGES)
imgContent = (
await readFile(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
diagramUrl
)
)
).toString('base64');
else imgContent = await httpGet(diagramUrl);
let diagramImage = `\n![${path.parse(pumlFile.dir).name}](data:${getMime(
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT
)};base64,${imgContent})\n`;
let diagramLink = `[Download ${
path.parse(pumlFile.dir).name
} diagram](${diagramUrl} ':ignore')`;
return diagramImage + diagramLink;
} else {
let diagramImage = `![diagram](${diagramUrl})`;
let diagramLink = `[Go to ${path.parse(pumlFile.dir).name} diagram](${diagramUrl})`;
if (!options.INCLUDE_LINK_TO_DIAGRAM)
//img
return diagramImage;
//link
else return diagramLink;
}
});
//write to disk
filePromises.push(
writeFile(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${options.MD_FILE_NAME}.md`
),
MD
).then(() => {
processedCount++;
if (onProgress) onProgress(processedCount, totalCount);
})
);
}
return Promise.all(filePromises);
};
const generatePDF = async (tree, options, onProgress) => {
let processedCount = 0;
let totalCount = tree.length;
let filePromises = [];
for (const item of tree) {
let name = getFolderName(item.dir, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
//title
let MD = `# ${name}`;
if (options.INCLUDE_BREADCRUMBS && name !== options.HOMEPAGE_NAME)
MD += `\n\n\`${item.dir.replace(options.ROOT_FOLDER, '')}\``;
//concatenate markdown files
MD = await compileDocument(MD, item, options, async (item, pumlFile, options) => {
let diagramUrl = encodeURIPath(
path.parse(pumlFile.dir).name + `.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
);
if (!options.GENERATE_LOCAL_IMAGES)
diagramUrl = plantUmlServerUrl(
options.PLANTUML_SERVER_URL,
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT,
pumlFile.content
);
let diagramImage = `![diagram](${diagramUrl})`;
return diagramImage;
});
//write temp file
filePromises.push(
writeFile(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${options.MD_FILE_NAME}_TEMP.md`
),
MD
)
.then(() => {
return markdownpdf(
{
path: path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${options.MD_FILE_NAME}_TEMP.md`
)
},
{
stylesheet: [options.PDF_CSS],
pdf_options: {
scale: 1,
displayHeaderFooter: false,
printBackground: true,
landscape: false,
pageRanges: '',
format: 'A4',
width: '',
height: '',
margin: {
top: '1.5cm',
right: '1cm',
bottom: '1cm',
left: '1cm'
}
},
dest: path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${name}.pdf`
)
}
).catch(console.error);
})
.then(() => {
//remove temp file
fsextra.removeSync(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${options.MD_FILE_NAME}_TEMP.md`
)
);
})
.then(() => {
processedCount++;
if (onProgress) onProgress(processedCount, totalCount);
})
);
}
return Promise.all(filePromises);
};
const generateWebMD = async (tree, options) => {
let filePromises = [];
let docsifySideBar = '';
for (const item of tree) {
//sidebar
docsifySideBar += `${' '.repeat(item.level - 1)}* [${item.name}](${encodeURIPath(
path.join(...path.join(item.dir).split(path.sep).splice(1), options.WEB_FILE_NAME)
)})\n`;
let name = getFolderName(item.dir, options.ROOT_FOLDER, options.HOMEPAGE_NAME);
//title
let MD = `# ${name}`;
//concatenate markdown files
MD = await compileDocument(MD, item, options, async (item, pumlFile, options) => {
let diagramUrl = encodeURIPath(
path.join(
path.dirname(pumlFile.dir),
path.parse(pumlFile.dir).name + `.${pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT}`
)
);
if (!options.GENERATE_LOCAL_IMAGES)
diagramUrl = plantUmlServerUrl(
options.PLANTUML_SERVER_URL,
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT,
pumlFile.content
);
if (options.EMBED_DIAGRAM) {
let imgContent = '';
if (options.GENERATE_LOCAL_IMAGES)
imgContent = (
await readFile(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
diagramUrl
)
)
).toString('base64');
else imgContent = await httpGet(diagramUrl);
let diagramImage = `\n![${path.parse(pumlFile.dir).name}](data:${getMime(
pumlFile.isDitaa ? 'png' : options.DIAGRAM_FORMAT
)};base64,${imgContent})\n`;
let diagramLink = `[Download ${
path.parse(pumlFile.dir).name
} diagram](${diagramUrl} ':ignore')`;
return diagramImage + diagramLink;
} else {
let diagramImage = `![diagram](${diagramUrl})`;
let diagramLink = `[Go to ${path.parse(pumlFile.dir).name} diagram](${diagramUrl})`;
if (!options.INCLUDE_LINK_TO_DIAGRAM)
//img
return diagramImage;
//link
else return diagramLink;
}
});
//write to disk
filePromises.push(
writeFile(
path.join(
options.DIST_FOLDER,
item.dir.replace(options.ROOT_FOLDER, ''),
`${options.WEB_FILE_NAME}.md`
),
MD
)
);
}
if (options.DOCSIFY_TEMPLATE && options.DOCSIFY_TEMPLATE !== '') {
docsifyTemplate = require(path.join(process.cwd(), options.DOCSIFY_TEMPLATE));
}
//docsify homepage
filePromises.push(
writeFile(
path.join(options.DIST_FOLDER, `index.html`),
docsifyTemplate({
name: options.PROJECT_NAME,
repo: options.REPO_NAME,
loadSidebar: true,
auto2top: true,
homepage: `${options.WEB_FILE_NAME}.md`,
plantuml: {
skin: 'classic'
},
stylesheet: options.WEB_THEME,
alias: { '/.*/_sidebar.md': '/_sidebar.md' },
supportSearch: options.SUPPORT_SEARCH
})
)
);
//github pages preparation
filePromises.push(writeFile(path.join(options.DIST_FOLDER, `.nojekyll`), ''));
//sidebar
filePromises.push(writeFile(path.join(options.DIST_FOLDER, '_sidebar.md'), docsifySideBar));
return Promise.all(filePromises);
};
const build = async (options, conf) => {
let start_date = new Date();
const bkFolderName = options.DIST_FOLDER + DIST_BACKUP_FOLDER_SUFFIX;
// Generating local images, remove old backup image folder, rename current dist folder to new backup
if (options.GENERATE_LOCAL_IMAGES) {
await fsextra.removeSync(bkFolderName);
if (await fsextra.existsSync(options.DIST_FOLDER)) {
await fsextra.rename(options.DIST_FOLDER, bkFolderName);
}
} else {
//clear dist directory
await fsextra.emptyDir(options.DIST_FOLDER);
}
await makeDirectory(path.join(options.DIST_FOLDER));
//actual build
console.log(chalk.green(`\nbuilding documentation in ./${options.DIST_FOLDER}`));
let tree = await generateTree(options.ROOT_FOLDER, options);
console.log(chalk.blue(`parsed ${tree.length} folders`));
if (options.GENERATE_LOCAL_IMAGES) {
console.log(chalk.blue('generating images'));
await generateImages(
tree,
options,
(count, total) => {
process.stdout.write(`processed ${count}/${total} images\r`);
},
conf
);
console.log('');
}
if (options.GENERATE_MD) {
console.log(chalk.blue('generating markdown files'));
await generateMD(tree, options, (count, total) => {
process.stdout.write(`processed ${count}/${total} files\r`);
});
console.log('');
}
if (options.GENERATE_WEBSITE) {
console.log(chalk.blue('generating docsify site'));
await generateWebMD(tree, options);
}
if (options.GENERATE_COMPLETE_MD_FILE) {
console.log(chalk.blue('generating complete markdown file'));
await generateCompleteMD(tree, options);
}
if (options.GENERATE_COMPLETE_PDF_FILE) {
console.log(chalk.blue('generating complete pdf file'));
await generateCompletePDF(tree, options);
}
if (options.GENERATE_PDF) {
console.log(chalk.blue('generating pdf files'));
await generatePDF(tree, options, (count, total) => {
process.stdout.write(`processed ${count}/${total} files\r`);
});
console.log('');
}
// Remove image backup folder
await fsextra.removeSync(bkFolderName);
console.log(chalk.green(`built in ${(new Date() - start_date) / 1000} seconds`));
};
exports.build = build;