docgen-utils.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import fs from 'fs';
  2. import klawSync from 'klaw-sync';
  3. import { basename } from 'path';
  4. /* eslint-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. export function normalizeForUrlPart<T extends string | undefined>(input: T): T {
  26. if (input == null) {
  27. return input;
  28. }
  29. return input
  30. .replace(/([a-z])([A-Z])/g, '$1-$2')
  31. .replace(/[^a-zA-Z0-9-_/]/g, ' ')
  32. .replace(/\s+/g, '-')
  33. .toLowerCase() as T;
  34. }
  35. /**
  36. * Delete all generated docs found in the outputPath.
  37. */
  38. export function deleteGeneratedDocs(outputPath: string) {
  39. if (!fs.existsSync(outputPath)) {
  40. return;
  41. }
  42. try {
  43. let deleteCount = 0;
  44. const files = klawSync(outputPath, { nodir: true });
  45. for (const file of files) {
  46. const content = fs.readFileSync(file.path, 'utf-8');
  47. if (isGenerated(content)) {
  48. fs.unlinkSync(file.path);
  49. deleteCount++;
  50. }
  51. }
  52. if (deleteCount) {
  53. console.log(`Deleted ${deleteCount} generated docs from ${outputPath}`);
  54. }
  55. } catch (e: any) {
  56. console.error('Could not delete generated docs!');
  57. console.log(e);
  58. process.exitCode = 1;
  59. }
  60. }
  61. /**
  62. * Returns true if the content matches that of a generated document.
  63. */
  64. function isGenerated(content: string) {
  65. return /generated\: true\n---\n/.test(content);
  66. }