docgen-utils.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import fs from 'fs';
  2. import klawSync from 'klaw-sync';
  3. import { basename } from 'path';
  4. // tslint:disable:no-console
  5. /**
  6. * Generates the Hugo front matter with the title of the document
  7. */
  8. export function generateFrontMatter(title: string, weight: number, showToc: boolean = true): string {
  9. return `---
  10. title: "${titleCase(title.replace(/-/g, ' '))}"
  11. weight: ${weight}
  12. date: ${new Date().toISOString()}
  13. showtoc: ${showToc}
  14. generated: true
  15. ---
  16. <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script -->
  17. `;
  18. }
  19. export function titleCase(input: string): string {
  20. return input
  21. .split(' ')
  22. .map(w => w[0].toLocaleUpperCase() + w.substr(1))
  23. .join(' ');
  24. }
  25. /**
  26. * Delete all generated docs found in the outputPath.
  27. */
  28. export function deleteGeneratedDocs(outputPath: string) {
  29. if (!fs.existsSync(outputPath)) {
  30. return;
  31. }
  32. try {
  33. let deleteCount = 0;
  34. const files = klawSync(outputPath, { nodir: true });
  35. for (const file of files) {
  36. const content = fs.readFileSync(file.path, 'utf-8');
  37. if (isGenerated(content)) {
  38. fs.unlinkSync(file.path);
  39. deleteCount++;
  40. }
  41. }
  42. if (deleteCount) {
  43. console.log(`Deleted ${deleteCount} generated docs from ${outputPath}`);
  44. }
  45. } catch (e: any) {
  46. console.error('Could not delete generated docs!');
  47. console.log(e);
  48. process.exitCode = 1;
  49. }
  50. }
  51. /**
  52. * Returns true if the content matches that of a generated document.
  53. */
  54. function isGenerated(content: string) {
  55. return /generated\: true\n---\n/.test(content);
  56. }