Skip to content

Commit 4f3c9a1

Browse files
Improve script's readability
1 parent a552599 commit 4f3c9a1

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

generate-readme-toc.js

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
import fs from 'fs/promises'
22

3-
async function generateTOC(content) {
3+
async function generateTableOfContents(content) {
44
const lines = content.split('\n')
55
const headings = []
6-
let contentsIndex = -1
6+
let contentsHeadingIndex = -1
77
let parsingHeadings = false
88

99
for (let i = 0; i < lines.length; i++) {
1010
const line = lines[i].trim()
1111
const nextLine = lines[i + 1]?.trim() || ''
1212

1313
if (line === 'Contents' && nextLine.startsWith('--------')) {
14-
contentsIndex = i
15-
parsingHeadings = true
14+
contentsHeadingIndex = i
15+
parsingHeadings = true // Start parsing headings after the "Contents" section
1616
i++ // Skip the underline
1717
continue
1818
}
@@ -33,38 +33,39 @@ async function generateTOC(content) {
3333
}
3434
}
3535

36+
// Generate table of contents
3637
const toc = [''] // Start with an empty line after the "Contents" section
3738
headings.forEach((heading) => {
3839
const indent = ' '.repeat(heading.level - 1)
3940
toc.push(`${indent}* \`${heading.text} <${heading.text}_>\`_`)
40-
toc.push('') // Add a newline after each item, including the last one
41+
toc.push('') // Add a newline after each item
4142
})
4243

43-
return { toc, contentsIndex }
44+
return { toc, contentsHeadingIndex }
4445
}
4546

4647
async function updateReadme() {
4748
try {
4849
const content = await fs.readFile('README.rst', 'utf8')
49-
const { toc, contentsIndex } = await generateTOC(content)
50+
const { toc, contentsHeadingIndex } = await generateTableOfContents(content)
5051

51-
if (contentsIndex === -1) {
52-
console.error('Contents heading not found in the file.')
52+
if (contentsHeadingIndex === -1) {
53+
console.error('Contents heading not found in the README.')
5354
process.exit(1)
5455
}
5556

5657
const lines = content.split('\n')
57-
const contentStartIndex = lines.findIndex(
58+
const tocTableEndIndex = lines.findIndex(
5859
(line, index) =>
59-
index > contentsIndex + 2 &&
60+
index > contentsHeadingIndex + 2 &&
6061
!line.trim().startsWith('*') &&
6162
line.trim() !== '',
6263
)
6364

6465
const newContent = [
65-
...lines.slice(0, contentsIndex + 2), // Include "Contents" and its underline
66+
...lines.slice(0, contentsHeadingIndex + 2), // Include readme content before "Contents" heading, the heading itself and its underline
6667
...toc,
67-
...lines.slice(contentStartIndex),
68+
...lines.slice(tocTableEndIndex), // Include all content after the previous TOC
6869
].join('\n')
6970

7071
await fs.writeFile('README.rst', newContent)

0 commit comments

Comments
 (0)