docgen-utils.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import fs from 'fs';
  2. import klawSync from 'klaw-sync';
  3. import { basename } from 'path';
  4. // tslint: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. `;
  18. }
  19. export function titleCase(input: string): string {
  20. return input.split(' ').map(w => w[0].toLocaleUpperCase() + w.substr(1)).join(' ');
  21. }
  22. /**
  23. * Delete all generated docs found in the outputPath.
  24. */
  25. export function deleteGeneratedDocs(outputPath: string) {
  26. if (!fs.existsSync(outputPath)) {
  27. return;
  28. }
  29. try {
  30. let deleteCount = 0;
  31. const files = klawSync(outputPath, {nodir: true});
  32. for (const file of files) {
  33. const content = fs.readFileSync(file.path, 'utf-8');
  34. if (isGenerated(content)) {
  35. fs.unlinkSync(file.path);
  36. deleteCount++;
  37. }
  38. }
  39. if (deleteCount) {
  40. console.log(`Deleted ${deleteCount} generated docs from ${outputPath}`);
  41. }
  42. } catch (e) {
  43. console.error('Could not delete generated docs!');
  44. console.log(e);
  45. process.exitCode = 1;
  46. }
  47. }
  48. /**
  49. * Returns true if the content matches that of a generated document.
  50. */
  51. function isGenerated(content: string) {
  52. return /generated\: true\n---\n/.test(content);
  53. }