1
1
import fs from 'fs/promises'
2
2
3
- async function generateTOC ( content ) {
3
+ async function generateTableOfContents ( content ) {
4
4
const lines = content . split ( '\n' )
5
5
const headings = [ ]
6
- let contentsIndex = - 1
6
+ let contentsHeadingIndex = - 1
7
7
let parsingHeadings = false
8
8
9
9
for ( let i = 0 ; i < lines . length ; i ++ ) {
10
10
const line = lines [ i ] . trim ( )
11
11
const nextLine = lines [ i + 1 ] ?. trim ( ) || ''
12
12
13
13
if ( line === 'Contents' && nextLine . startsWith ( '--------' ) ) {
14
- contentsIndex = i
15
- parsingHeadings = true
14
+ contentsHeadingIndex = i
15
+ parsingHeadings = true // Start parsing headings after the "Contents" section
16
16
i ++ // Skip the underline
17
17
continue
18
18
}
@@ -33,38 +33,39 @@ async function generateTOC(content) {
33
33
}
34
34
}
35
35
36
+ // Generate table of contents
36
37
const toc = [ '' ] // Start with an empty line after the "Contents" section
37
38
headings . forEach ( ( heading ) => {
38
39
const indent = ' ' . repeat ( heading . level - 1 )
39
40
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
41
42
} )
42
43
43
- return { toc, contentsIndex }
44
+ return { toc, contentsHeadingIndex }
44
45
}
45
46
46
47
async function updateReadme ( ) {
47
48
try {
48
49
const content = await fs . readFile ( 'README.rst' , 'utf8' )
49
- const { toc, contentsIndex } = await generateTOC ( content )
50
+ const { toc, contentsHeadingIndex } = await generateTableOfContents ( content )
50
51
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 .' )
53
54
process . exit ( 1 )
54
55
}
55
56
56
57
const lines = content . split ( '\n' )
57
- const contentStartIndex = lines . findIndex (
58
+ const tocTableEndIndex = lines . findIndex (
58
59
( line , index ) =>
59
- index > contentsIndex + 2 &&
60
+ index > contentsHeadingIndex + 2 &&
60
61
! line . trim ( ) . startsWith ( '*' ) &&
61
62
line . trim ( ) !== '' ,
62
63
)
63
64
64
65
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
66
67
...toc ,
67
- ...lines . slice ( contentStartIndex ) ,
68
+ ...lines . slice ( tocTableEndIndex ) , // Include all content after the previous TOC
68
69
] . join ( '\n' )
69
70
70
71
await fs . writeFile ( 'README.rst' , newContent )
0 commit comments