-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.ts
More file actions
88 lines (74 loc) · 2.2 KB
/
build.ts
File metadata and controls
88 lines (74 loc) · 2.2 KB
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
import * as fs from 'fs';
import * as path from 'path';
import fm from 'front-matter';
const PATHS = {
wiki: path.resolve(__dirname, 'wiki'),
readme: path.resolve(__dirname, 'README.md'),
};
const prefix = `\n## Tags:\n\n`;
type WikiFrontMatter = Partial<{
tags: string[];
}>;
type Note = {
tags: string[];
title: string;
filepath: string;
};
async function main() {
const posts = await fs.promises.readdir(PATHS.wiki);
const promises = posts.map(
async (filepath: string): Promise<Note> => {
const content = await fs.promises.readFile(
path.join(PATHS.wiki, filepath),
);
const {attributes, body} = fm<WikiFrontMatter>(content.toString());
const title =
body.match(/#\s.*/m)?.[0].replace(/^#\s/, '') || filepath;
return {
filepath,
tags: attributes.tags || [],
title,
};
},
);
const notes = await Promise.all(promises);
const tagMap = notes.reduce((acc, note) => {
note.tags.forEach(tag => {
if (tag in acc) {
acc[tag].push(note);
} else {
acc[tag] = [note];
}
});
return acc;
}, {} as Record<string, Note[]>);
const details = Object.keys(tagMap)
.sort()
.map(tagName => {
const notes = tagMap[tagName];
const list = notes
.map(
note =>
`<li><a href="./${path.join('wiki', note.filepath)}">${
note.title
}</a></li>`,
)
.join('\n');
return [
`<details><summary>${tagName} (${notes.length})</summary>`,
`<ul>`,
list,
`</ul>`,
'</details>',
].join('\n');
})
.join('\n\n');
const split = (
await fs.promises.readFile(PATHS.readme).catch(() => '# Readme\n')
)
.toString()
.split(prefix);
const content = split[0] + prefix + details;
fs.writeFileSync(PATHS.readme, content);
}
main();