Skip to content

Commit bd402dc

Browse files
committedJul 25, 2022
ci: check README table of content
1 parent 898a432 commit bd402dc

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
 

‎.github/workflows/tests.yml

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ jobs:
2020
- run: npm ci
2121
- run: npm run lint
2222
- run: npm run format
23+
- run: node tools/toc.js check
2324
- run: npx markdown-link-check -p README.md
2425

2526
integration:

‎tools/toc.js

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
const { readFileSync: read, writeFileSync: write } = require("fs")
2+
3+
const action = process.argv[2]
4+
5+
switch (action) {
6+
case "check": {
7+
const currentToc = splitReadme()[1]
8+
if (currentToc !== generateToc()) {
9+
console.log("Table of content is outdated. Use 'write' to update it.")
10+
process.exit(1)
11+
} else {
12+
console.log("Table of content is up to date.")
13+
}
14+
break
15+
}
16+
17+
case "write": {
18+
const [start, _, end] = splitReadme()
19+
writeReadme(start + generateToc() + end)
20+
break
21+
}
22+
23+
default:
24+
console.log(
25+
`${process.argv[1]} takes one argument, either "check" or "write"`
26+
)
27+
process.exit(1)
28+
}
29+
30+
function readReadme() {
31+
return read("README.md", { encoding: "utf-8" })
32+
}
33+
34+
function writeReadme(content) {
35+
write("README.md", content, { encoding: "utf-8" })
36+
}
37+
38+
function splitReadme() {
39+
const content = readReadme()
40+
let startTocIndex = content.indexOf("\n\n") + 2
41+
let endTocIndex = content.indexOf("\n\n", startTocIndex)
42+
43+
return [
44+
content.slice(0, startTocIndex),
45+
content.slice(startTocIndex, endTocIndex),
46+
content.slice(endTocIndex),
47+
]
48+
}
49+
50+
function generateToc() {
51+
return readReadme()
52+
.split("\n")
53+
.flatMap((line) => {
54+
const level = line.match(/^#*/)[0].length
55+
if (!level) return []
56+
57+
const title = line.slice(level + 1)
58+
const urlHash = title
59+
.toLowerCase()
60+
.replace(/ /g, "-")
61+
.replace(/[^-a-z0-9]/g, "")
62+
return `${" ".repeat(level - 2)}- [${title}](#${urlHash})`
63+
})
64+
.join("\n")
65+
}

0 commit comments

Comments
 (0)
Please sign in to comment.