-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgentoc.js
20 lines (13 loc) · 835 Bytes
/
gentoc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import fs from 'fs/promises'
let contents = await fs.readFile(process.argv[2], 'utf-8')
contents = contents.replace(/<!-- TOC-START -->[\w\W]*<!-- TOC-END -->/, '%TOC%')
contents = contents.replaceAll('<', '<').replaceAll('>', '>')
const headings = Array.from(contents.matchAll(/^(##?#?) (.*)$/gm))
.map(array => array.slice(1,3))
.map(heading => `${' '.repeat((heading[0].length-1)*2)}- [${heading[1].replaceAll(/</g, '<').replaceAll(/>/g, '>')}](#${heading[1].replaceAll(/[^a-zA-Zа-яА-Я0-9 ]/g, '').replaceAll(' ', '-').toLowerCase()})`)
contents = contents.replaceAll(/(?<!".*)</gm, '<').replaceAll(/(?<!".*)>/gm, '>')
contents = contents.replace(/%TOC%/, `<!-- TOC-START -->
## Таблица контента
${headings.join('\n')}
<!-- TOC-END -->`)
await fs.writeFile(process.argv[2], contents)