make-table-of-contents.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Usage: esrun make-table-of-contents.ts
  2. import { readdir } from 'node:fs/promises';
  3. const log = console.log;
  4. // A serial async map function (because we like do things in order and performance doesn't matter)
  5. const asyncMap = async (array, asyncFunction) => {
  6. for (const item of array) {
  7. await asyncFunction(item);
  8. }
  9. };
  10. const PROJECT_TYPES = ['anchor', 'native', 'seahorse', 'solidity'];
  11. const CATEGORIES = ['basics', 'tokens', 'tokens/token-2022', 'compression', 'oracles'];
  12. interface LinkMap {
  13. [key: string]: boolean;
  14. }
  15. // Loop through the folders in CATEGORIES
  16. await asyncMap(CATEGORIES, async (category) => {
  17. const path = `./${category}`;
  18. const exampleFolders = (await readdir(path, { withFileTypes: true })).filter((item) => item.isDirectory()).map((dir) => dir.name);
  19. log(`\n\n### ${category}`);
  20. await asyncMap(exampleFolders, async (exampleFolder) => {
  21. // Check if the folder has a subfolder that matches a project type ('anchor', 'native' etc...)
  22. const projectTypeFolders = (await readdir(`./${category}/${exampleFolder}`, { withFileTypes: true }))
  23. .filter((item) => item.isDirectory())
  24. .filter((dir) => PROJECT_TYPES.includes(dir.name));
  25. // If there are no subfolders that match a project type, we can skip this folder - it's not example code
  26. if (projectTypeFolders.length === 0) {
  27. return;
  28. }
  29. log(`\n#### ${exampleFolder}`);
  30. // We can now create a map of the project types that are present in the example folder
  31. const linkMap: LinkMap = {};
  32. PROJECT_TYPES.forEach((projectType) => {
  33. linkMap[projectType] = projectTypeFolders.some((dir) => dir.name === projectType);
  34. });
  35. const links: Array<string> = [];
  36. // Go through the link map add a string link to the folder if the linkmap value is true
  37. for (const [projectType, exists] of Object.entries(linkMap)) {
  38. const link = `./${category}/${exampleFolder}/${projectType}`;
  39. if (exists) {
  40. links.push(`[${projectType}](${link})`);
  41. }
  42. }
  43. log(links.join(', '));
  44. });
  45. });