docgen-utils.ts 1.9 KB

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