docgen-utils.ts 2.1 KB

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