docgen-utils.ts 2.1 KB

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