1
0

docgen-utils.ts 2.1 KB

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