react-native-navigation的迁移库

MarkdownWriter.ts 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import * as _ from 'lodash';
  2. import * as Handlebars from 'handlebars';
  3. import * as fs from 'fs';
  4. import { ClassContext } from './ClassParser';
  5. import { EnumContext } from './EnumParser';
  6. export class MarkdownWriter {
  7. private classFn;
  8. private enumFn;
  9. private menuFn;
  10. constructor(private templatesDir: string, private outputDir: string) {
  11. this.classFn = this.setupClassHandlebars();
  12. this.enumFn = this.setupEnumHandlebars();
  13. this.menuFn = this.setupMenuHandlebars();
  14. }
  15. public writeClasses(classContexts: ClassContext[]) {
  16. classContexts.forEach((c) => {
  17. const markdown = this.classFn(c);
  18. fs.writeFileSync(`${this.outputDir}/${c.name}.md`, markdown, { encoding: 'utf8' });
  19. });
  20. }
  21. public writeEnums(enumContexts: EnumContext[]) {
  22. enumContexts.forEach((c) => {
  23. const markdown = this.enumFn(c);
  24. fs.writeFileSync(`${this.outputDir}/${c.name}.md`, markdown, { encoding: 'utf8' });
  25. });
  26. }
  27. public writeMenu(classContexts: ClassContext[], interfaceContexts: ClassContext[], enumContexts: EnumContext[]) {
  28. const mapper = (c) => ({ name: c.name, path: `/api/${c.name}` });
  29. const files = classContexts.map(mapper);
  30. const files2 = interfaceContexts.map(mapper);
  31. const files3 = enumContexts.map(mapper);
  32. const menuMarkdown = this.menuFn({ files: _.concat(files, files2, files3) });
  33. fs.writeFileSync(`${this.outputDir}/_sidebar.md`, menuMarkdown, { encoding: 'utf8' });
  34. fs.writeFileSync(`${this.outputDir}/README.md`, menuMarkdown, { encoding: 'utf8' });
  35. }
  36. private setupClassHandlebars() {
  37. const classTemplate = fs.readFileSync(`${this.templatesDir}/class.hbs`).toString();
  38. const methodTemplate = fs.readFileSync(`${this.templatesDir}/method.hbs`).toString();
  39. const propertyTemplate = fs.readFileSync(`${this.templatesDir}/property.hbs`).toString();
  40. Handlebars.registerPartial('class', classTemplate);
  41. Handlebars.registerPartial('method', methodTemplate);
  42. Handlebars.registerPartial('property', propertyTemplate);
  43. return Handlebars.compile('{{> class}}', { strict: true, noEscape: true });
  44. }
  45. private setupEnumHandlebars() {
  46. const enumTemplate = fs.readFileSync(`${this.templatesDir}/enum.hbs`).toString();
  47. return Handlebars.compile(enumTemplate, { strict: true, noEscape: true });
  48. }
  49. private setupMenuHandlebars() {
  50. const template = fs.readFileSync(`${this.templatesDir}/menu.hbs`).toString();
  51. return Handlebars.compile(template, { strict: true, noEscape: true });
  52. }
  53. }