forked from Aiven-Open/klaw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown-toc.cjs
193 lines (163 loc) · 5.53 KB
/
markdown-toc.cjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/* eslint-disable */
const fs = require("fs");
const path = require("path");
const glob = require("glob");
/* What this script does
*
* - creates a list of all files with the ".md" ending (checkAllMarkdownFiles)
* - checks if the `<!-- auto-generated-toc-start -->` and `<!-- auto-generated-toc-end-->`
* are marking the place where the TOC should go (tocShouldBeGenerated)
* - in files with that comments, it creates a list of links as TOC (generateTOC)
*/
// Marks the beginning where the TOC should go
const tocStartComment = "<!-- auto-generated-toc-start -->";
// Marks the end of the TOC
const tocEndComment = "<!-- auto-generated-toc-end -->";
function tocShouldBeGenerated(markdownContent, fileName) {
const hasAutoTocStartComment = markdownContent.includes(tocStartComment);
const hasAutoTocEndComment = markdownContent.includes(tocEndComment);
if (!hasAutoTocStartComment && !hasAutoTocEndComment) {
return false;
}
if (hasAutoTocStartComment && !hasAutoTocEndComment) {
console.log(
`\n ⚠️ File ${fileName}:\n Found ${tocStartComment} but no ${tocEndComment}.\n`
);
return false;
}
if (!hasAutoTocStartComment && hasAutoTocEndComment) {
console.log(
`\n ⚠️ File ${fileName}:\n Found ${tocEndComment} but no ${tocStartComment}.\n`
);
return false;
}
return true;
}
function checkAllMarkdownFiles() {
// Get all Markdown files in the current directory and its subdirectories
const files = glob.sync(["**/*.md", "../**/*.md"], {
cwd: process.cwd(),
ignore: ["**/node_modules/**", ".git/**"],
nodir: true,
absolute: true,
dot: true,
});
console.log(`🤖 checking file: `);
files.forEach((fileName) => {
console.log(`\n- ${fileName}`);
const markdownContent = fs.readFileSync(fileName, "utf-8");
if (tocShouldBeGenerated(markdownContent, fileName)) {
generateTOC(fileName, markdownContent);
} else {
console.log("No comment to autogenerate TOC found.");
}
});
console.log(
`\n 🏁 Finished check for autogenerated TOC for ${files.length} files.\n`
);
}
function checkSingleMarkdownFile(targetFile) {
const fileName = path.resolve(targetFile);
const markdownContent = fs.readFileSync(fileName, "utf-8");
if (tocShouldBeGenerated(markdownContent, fileName)) {
generateTOC(fileName, markdownContent);
} else {
console.log("No comment to autogenerate TOC found.");
}
}
function generateTOC(fileName, markdownContent) {
const existingTocStartIndex = markdownContent.indexOf(tocStartComment);
const existingTocEndIndex = markdownContent.indexOf(tocEndComment);
const tocHeading = "## Table of Contents";
const toc = [];
let isFirstHeading = true;
// Regular expression to match Markdown headings
const headingRegex = /^(#{1,6})\s+(.+)$/gm;
let match;
while ((match = headingRegex.exec(markdownContent)) !== null) {
const headingLevelSigns = match[1];
const headingLevel = headingLevelSigns.length;
const headingContent = match[2];
if (headingLevel === 1 && isFirstHeading) {
// Skip the first heading with level 1
isFirstHeading = false;
continue;
}
// check if the heading is the autogenerated one,
// if yes, do not continue with this loop
if (`${headingLevelSigns} ${headingContent}` === tocHeading) {
continue;
}
toc.push({
level: headingLevel,
content: headingContent,
});
isFirstHeading = false;
}
// Generate Table of Contents with proper indentation
const tocList = toc
.map((entry) => {
const linkContent = entry.content
.replace(/\[([^\]]+)\]\(.+?\)/, "$1")
.trim();
// Remove non-alphanumeric characters (except hyphens) for links
const link = linkContent
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/^[^a-zA-Z0-9]+/, "")
.replace(/[^a-zA-Z0-9- ]/g, "");
const indentation = " ".repeat(Math.max(entry.level - 2, 0));
return `${indentation}- [${linkContent}](#${link})`;
})
.join("\n");
try {
// If there's an existing TOC, replace it with the updated one.
if (existingTocStartIndex !== -1 && existingTocEndIndex !== -1) {
const beforeToc = markdownContent.substring(0, existingTocStartIndex);
const afterToc = markdownContent.substring(
existingTocEndIndex + tocEndComment.length
);
fs.writeFileSync(
fileName,
`${beforeToc}${tocStartComment}\n\n${tocHeading}\n\n${tocList}\n\n${tocEndComment}${afterToc}`,
"utf-8"
);
} else {
// Otherwise, add the TOC based on the location of comments.
fs.appendFileSync(
fileName,
`\n${tocStartComment}\n${tocHeading}\n\n${tocList}\n\n${tocEndComment}`,
"utf-8"
);
}
console.log(
`✅ Table of Contents added/updated in ${path.relative(
process.cwd(),
fileName
)}.`
);
} catch (error) {
console.error(
`Error writing to ${path.relative(process.cwd(), fileName)}:`,
error
);
}
}
const targetFileArgIndex = process.argv.indexOf("-f");
if (targetFileArgIndex !== -1) {
const targetFile = process.argv[targetFileArgIndex + 1];
if (!targetFile) {
console.error("⛔️ ERROR: Please provide a file path with -f flag.");
return;
}
if (path.extname(targetFile) !== ".md") {
console.error(
"⛔️ ERROR: The file specified with -f must have the .md extension."
);
return;
}
console.log(`🤖 Checking file: ${targetFile}`);
checkSingleMarkdownFile(targetFile);
} else {
checkAllMarkdownFiles();
}