Skip to content

Commit 29e5855

Browse files
committed
first run
1 parent 98c1d22 commit 29e5855

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

scripts/generateHeaderIDs.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
const fs = require('fs');
2+
3+
function walk(dir) {
4+
let results = [];
5+
const list = fs.readdirSync(dir);
6+
list.forEach(function(file) {
7+
file = dir + '/' + file;
8+
const stat = fs.statSync(file);
9+
if (stat && stat.isDirectory()) {
10+
/* Recurse into a subdirectory */
11+
results = results.concat(walk(file));
12+
} else {
13+
/* Is a file */
14+
results.push(file);
15+
}
16+
});
17+
return results;
18+
}
19+
20+
function generateID(text) {
21+
return text
22+
.toLowerCase()
23+
.replace(/\s/g, '-')
24+
.replace(/[^-a-z0-9]/g, '');
25+
}
26+
27+
function addHeaderID(line) {
28+
// check if we're a header at all
29+
if (!line.startsWith('#')) return;
30+
// check if it already has an id
31+
if (/\{#[-A-Za-z0-9]+\}/.match(line)) return;
32+
const headingText = line.slice(line.indexOf(' ')).trim();
33+
const headingLevel = line.slice(0, line.indexOf(' '));
34+
return `${headingLevel} ${headingText} ${generateID(headingText)}`;
35+
}
36+
37+
function addHeaderIDs(lines) {
38+
let inCode = false;
39+
const results = [];
40+
lines.forEach(line => {
41+
// Ignore code blocks
42+
if (line.startsWith('```')) {
43+
inCode = !inCode;
44+
return;
45+
}
46+
if (inCode) {
47+
results.push(line);
48+
}
49+
50+
results.push(addHeaderID(line));
51+
});
52+
}
53+
54+
const [path] = process.argv.slice(2);
55+
56+
const files = walk(path);
57+
files.forEach(file => {
58+
if (!file.endsWith('.md')) return;
59+
60+
const file = fs.readFileSync(file, 'utf8');
61+
const lines = file.split('\n');
62+
const updatedLines = addHeaderIDs(lines);
63+
fs.writeFileSync(file, updatedLines.join('\n'));
64+
});

0 commit comments

Comments
 (0)