docgen-utils.ts 1.7 KB

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