(directory)
| 34 | ) |
| 35 | |
| 36 | function updateOrCreateToc(directory) { |
| 37 | const children = fs.readdirSync(directory).filter((subpath) => !subpath.endsWith('index.md')) |
| 38 | if (!children.length) return |
| 39 | |
| 40 | const tocFile = path.posix.join(directory, 'index.md') |
| 41 | |
| 42 | let content, data |
| 43 | |
| 44 | // If the index.md file already exists, read it (to be updated later). |
| 45 | if (fs.existsSync(tocFile)) { |
| 46 | const parsed = readFrontmatter(fs.readFileSync(tocFile, 'utf8')) |
| 47 | content = parsed.content |
| 48 | data = parsed.data |
| 49 | } |
| 50 | // If the index.md file does not exist, create it. |
| 51 | else { |
| 52 | content = '' |
| 53 | data = { |
| 54 | title: sentenceCase(path.basename(directory)), // fake the title of the index.md from the directory name |
| 55 | versions: '*', // default to all versions |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Add the children - this will default to the alphabetical list of files in the directory. |
| 60 | data.children = children.map((child) => `/${child.replace('.md', '')}`) |
| 61 | |
| 62 | // Write the file. |
| 63 | const newContents = readFrontmatter.stringify(content, data, { lineWidth: 10000 }) |
| 64 | fs.writeFileSync(tocFile, newContents) |
| 65 | |
| 66 | // Process any child directories recursively. |
| 67 | children.forEach((child) => { |
| 68 | if (child.endsWith('.md')) return |
| 69 | updateOrCreateToc(path.posix.join(directory, child)) |
| 70 | }) |
| 71 | } |
no test coverage detected