-
Notifications
You must be signed in to change notification settings - Fork 53
/
render-template.ts
executable file
·54 lines (45 loc) · 1.28 KB
/
render-template.ts
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
#! /usr/bin/env -S deno run --allow-read --allow-env --check
import markdownTOC from "npm:markdown-toc@1";
import nunjucks from "npm:nunjucks@3";
import TOML from "npm:@iarna/toml@3";
if (Deno.args.length !== 2) {
console.error("usage: render-template.ts template.njk data.toml");
Deno.exit(1);
}
const [templatePath, dataPath] = Deno.args;
interface INamedProject {
name: string;
[key: string]: string;
}
interface IProjects {
[key: string]: {
[key: string]: string;
};
}
const projList = (projects: IProjects): INamedProject[] =>
Object.entries(projects)
.map(([name, info]) =>
Object.assign({
name,
}, info)
);
try {
const template = (await Deno.readTextFile(templatePath)).trim();
const data = TOML.parse(await Deno.readTextFile(dataPath));
const tocToken = `%TOC-${Math.random()}%`;
const env = new nunjucks.configure({
lstripBlocks: true,
trimBlocks: true,
}).addGlobal("toc", tocToken);
const doc = env.renderString(template, {
projects: projList(<IProjects> data),
});
const headingFilter = (str: string) => !str.match(/Contents/);
const toc = markdownTOC(doc, {
filter: headingFilter,
}).content;
const docWithTOC = doc.replace(tocToken, toc);
console.log(docWithTOC);
} catch (err) {
console.error(err);
}