main.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. const { walk, EXCLUDE_LISTS } = require('../file-walker/test');
  2. const fs = require('fs').promises;
  3. const path_ = require('node:path');
  4. const FILE_EXCLUDES = [
  5. /(^|\/)\.git/,
  6. /^volatile\//,
  7. /^node_modules\//,
  8. /\/node_modules$/,
  9. /^submodules\//,
  10. /^node_modules$/,
  11. /package-lock\.json/,
  12. /^src\/dev-center\/js/,
  13. /src\/backend\/src\/public\/assets/,
  14. /^src\/gui\/src\/lib/,
  15. /^eslint\.config\.js$/,
  16. // translation readme copies
  17. /(^|\/)doc\/i18n/,
  18. // irrelevant documentation
  19. /(^|\/)doc\/graveyard/,
  20. // development logs
  21. /\/devlog\.md$/,
  22. ]
  23. const ROOT_DIR = path_.join(__dirname, '../..');
  24. const WIKI_DIR = path_.join(__dirname, '../../submodules/wiki');
  25. const path_to_name = path => {
  26. // Remove src/ and doc/ components
  27. // path = path.replace(/src\//g, '')
  28. path = path.replace(/doc\//g, '')
  29. // Hyphenate components
  30. path = path.replace(/-/g, '_')
  31. path = path.replace(/\//g, '-')
  32. // Remove extension
  33. path = path.replace(/\.md$/, '')
  34. return path;
  35. }
  36. const fix_relative_links = (content, entry) => {
  37. const originalDir = path_.dirname(entry);
  38. // Markdown links: [text](path/to/file.md), [text](path/to/file#section), etc
  39. return content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, link) => {
  40. // Skip external links
  41. if (link.startsWith('http://') || link.startsWith('https://') || link.startsWith('/')) {
  42. return match;
  43. }
  44. // Anchor links within the same file aren't changed
  45. if (link.startsWith('#')) return match;
  46. // Split the link to separate the path from the anchor
  47. const [linkPath, anchor] = link.split('#');
  48. // Resolve the relative path
  49. let resolvedPath = path_.normalize(path_.join(originalDir, linkPath));
  50. // Find the matching wiki path
  51. const wikiPath = path_to_name(resolvedPath);
  52. const newLink = anchor ? `${wikiPath}#${anchor}` : wikiPath;
  53. return `[${text}](${newLink})`;
  54. });
  55. };
  56. const main = async () => {
  57. const walk_iter = walk({
  58. excludes: FILE_EXCLUDES,
  59. }, ROOT_DIR);
  60. const documents = [];
  61. for await ( const value of walk_iter ) {
  62. let path = value.path;
  63. path = path_.relative(ROOT_DIR, path);
  64. // File must be under a doc/ directory
  65. if ( ! path.match(/(^|\/)doc\//) ) continue;
  66. // File must be markdown
  67. if ( ! path.match(/\.md/) ) continue;
  68. let outputName = path_to_name(path);
  69. // Read file content
  70. let content = await fs.readFile(value.path, 'utf8');
  71. // Get the first heading from the file to use as title
  72. const titleMatch = content.match(/^#\s+(.+)$/m);
  73. const title = titleMatch ? titleMatch[1] : outputName.replace(/-/g, ' ');
  74. // Fix internal links
  75. content = fix_relative_links(content, path);
  76. // Write the modified content to the wiki directory
  77. await fs.writeFile(path_.join(WIKI_DIR, outputName + '.md'), content);
  78. // Store information for sidebar
  79. const sidebarPath = outputName.split('-');
  80. // The original path structure (minus doc/) helps determine the hierarchy
  81. documents.push({
  82. sidebarPath,
  83. outputName,
  84. title: title
  85. });
  86. }
  87. // Generate _Sidebar.md
  88. const sidebarContent = generate_sidebar(documents);
  89. await fs.writeFile(path_.join(WIKI_DIR, '_Sidebar.md'), sidebarContent);
  90. }
  91. const format_name = name => {
  92. if ( name === 'api' ) return 'API';
  93. if ( name === 'contributors' ) return 'For Contributors';
  94. return name.charAt(0).toUpperCase() + name.slice(1);
  95. }
  96. const generate_sidebar = (documents) => {
  97. // Sort entries by path to group related files together
  98. documents.sort((a, b) => {
  99. const pathA = a.sidebarPath.slice(0, -1).join('/');
  100. const pathB = b.sidebarPath.slice(0, -1).join('/');
  101. if ( pathA !== pathB ) {
  102. return pathA.localeCompare(pathB);
  103. }
  104. // README.md always goes first
  105. const isReadmeA = a.outputName.toLowerCase().includes('readme');
  106. const isReadmeB = b.outputName.toLowerCase().includes('readme');
  107. if (isReadmeA) return -1;
  108. if (isReadmeB) return 1;
  109. return a.title.localeCompare(b.title);
  110. });
  111. // Format a document link the same way everywhere
  112. const formatDocumentLink = (document) => {
  113. let title = document.title;
  114. if ( document.outputName.split('-').slice(-1)[0].toLowerCase() === 'readme' ) {
  115. title = 'Index (README.md)';
  116. }
  117. return `* [${title}](${document.outputName.replace('.md', '')})\n`;
  118. };
  119. // Recursive function to build sidebar sections
  120. const buildSection = (docs, depth = 0, prefix = '') => {
  121. let result = '';
  122. const directDocs = [];
  123. const subSections = new Map();
  124. // Separate direct documents from those in subsections
  125. for (const doc of docs) {
  126. if (doc.sidebarPath.length <= depth + 1) {
  127. // Direct document at this level
  128. directDocs.push(doc);
  129. } else {
  130. // Document belongs in a subsection
  131. const sectionName = doc.sidebarPath[depth];
  132. if (!subSections.has(sectionName)) {
  133. subSections.set(sectionName, []);
  134. }
  135. subSections.get(sectionName).push(doc);
  136. }
  137. }
  138. // Add direct documents
  139. for (const doc of directDocs) {
  140. result += formatDocumentLink(doc);
  141. }
  142. // Process subsections recursively
  143. for (const [sectionName, sectionDocs] of subSections.entries()) {
  144. // Generate heading with appropriate level
  145. const headingLevel = '#'.repeat(depth + 2);
  146. const formattedName = format_name(sectionName)
  147. result += `\n${headingLevel} ${formattedName}\n`;
  148. // Process the subsection documents
  149. result += buildSection(sectionDocs, depth + 1, `${prefix}${sectionName}/`);
  150. }
  151. return result;
  152. };
  153. // Start with the main heading
  154. let sidebar = "## General\n\n";
  155. // Split documents into top-level and those in sections
  156. const topLevelDocs = documents.filter(doc => doc.sidebarPath.length <= 1);
  157. const sectionDocs = documents.filter(doc => doc.sidebarPath.length > 1);
  158. // Add top-level documents
  159. for (const doc of topLevelDocs) {
  160. sidebar += formatDocumentLink(doc);
  161. }
  162. // Group the remaining documents by their top-level sections
  163. const topLevelSections = new Map();
  164. for (const doc of sectionDocs) {
  165. const sectionName = doc.sidebarPath[0];
  166. if (!topLevelSections.has(sectionName)) {
  167. topLevelSections.set(sectionName, []);
  168. }
  169. topLevelSections.get(sectionName).push(doc);
  170. }
  171. // Process each top-level section
  172. for (const [sectionName, sectionDocs] of topLevelSections.entries()) {
  173. const formattedName = format_name(sectionName);
  174. sidebar += `\n## ${formattedName}\n`;
  175. sidebar += buildSection(sectionDocs, 1, `${sectionName}/`);
  176. }
  177. return sidebar;
  178. };
  179. main();