build-docs.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { promises } from 'fs';
  2. import { join, dirname, parse, format } from 'path';
  3. import { parse as marked } from './lib/marked.esm.js';
  4. import { HighlightJS } from 'highlight.js';
  5. import titleize from 'titleize';
  6. const { mkdir, rm, readdir, stat, readFile, writeFile, copyFile } = promises;
  7. const { highlight, highlightAuto } = HighlightJS;
  8. const cwd = process.cwd();
  9. const inputDir = join(cwd, 'docs');
  10. const outputDir = join(cwd, 'public');
  11. const templateFile = join(inputDir, '_document.html');
  12. const isUppercase = str => /[A-Z_]+/.test(str);
  13. const getTitle = str => str === 'INDEX' ? '' : titleize(str.replace(/_/g, ' ')) + ' - ';
  14. async function init() {
  15. console.log('Cleaning up output directory ' + outputDir);
  16. await rm(outputDir, { force: true, recursive: true });
  17. await mkdir(outputDir);
  18. await copyFile(join(cwd, 'LICENSE.md'), join(inputDir, 'LICENSE.md'));
  19. const tmpl = await readFile(templateFile, 'utf8');
  20. console.log('Building markdown...');
  21. await build(inputDir, tmpl);
  22. console.log('Build complete!');
  23. }
  24. async function build(currentDir, tmpl) {
  25. const files = await readdir(currentDir);
  26. for (const file of files) {
  27. const filename = join(currentDir, file);
  28. const stats = await stat(filename);
  29. const { mode } = stats;
  30. if (stats.isDirectory()) {
  31. // console.log('Found directory ' + filename);
  32. await build(filename, tmpl);
  33. } else {
  34. // console.log('Reading file ' + filename);
  35. let buffer = await readFile(filename);
  36. const parsed = parse(filename);
  37. if (parsed.ext === '.md' && isUppercase(parsed.name)) {
  38. const html = marked(buffer.toString('utf8'), {
  39. highlight: (code, language) => {
  40. if (!language) {
  41. return highlightAuto(code).value;
  42. }
  43. return highlight(code, { language }).value;
  44. }
  45. });
  46. buffer = Buffer.from(tmpl
  47. .replace('<!--{{title}}-->', getTitle(parsed.name))
  48. .replace('<!--{{content}}-->', html),
  49. 'utf8'
  50. );
  51. parsed.ext = '.html';
  52. parsed.name = parsed.name.toLowerCase();
  53. delete parsed.base;
  54. }
  55. parsed.dir = parsed.dir.replace(inputDir, outputDir);
  56. const outfile = format(parsed);
  57. // console.log('Ensure directory ' + dirname(outfile));
  58. await mkdir(dirname(outfile), { recursive: true });
  59. console.log('Writing file ' + outfile);
  60. await writeFile(outfile, buffer, { mode });
  61. }
  62. }
  63. }
  64. init().catch(console.error);