summaryrefslogtreecommitdiff
path: root/modules/blog/template.js
blob: a1d4d3dda4ded197f0c7d86844a63cff13eefd3d (plain)
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
const fs = require("fs").promises;

const blogUtil = require("./util.js");

const pathRoot = "blog";

async function recursiveTree(dir) {
	const res = new Map();

	const entries = await fs.readdir(dir, { withFileTypes: true });
	for (const entry of entries) {
		if (entry.name[0] == ".") continue;

		if (entry.isDirectory()) {
			res.set(entry.name, await recursiveTree(dir + "/" + entry.name));
		} else if (entry.isFile() && entry.name.endsWith(".html")) {
			res.set(entry.name.slice(0, entry.name.length - 5), true);
		}
	}

	return res;
}

// path: url prefix
function generateTree(tree, path) {
	let out = "";

	for (const [entry, sub] of tree) {
		if (sub === true) {  // file
			const elt = `<div class="tree-node tree-file"><a href="/${path}/${entry}">${entry}</a></div>\n`;
			out += elt;
		} else {  // subdirectory
			out += '<div class="tree-node tree-dir">\n';
			out += `<span class="tree-dir-name">${entry}/</span>\n`;
			out += '<div class="tree-sub">\n';
			out += generateTree(sub, path + "/" + entry);
			out += "</div></div>\n";
		}
	}

	return out;
}

// path: file path inside repo
async function generateDatetime(repodir, path) {
	if (path == "index.html") return "";

	const stat = await fs.stat(repodir + "/" + path);
	const gitout = await blogUtil.runCommandOutput("git", ["-C", repodir, "log", "--format=format:%as", "--", path]);
	const lines = gitout.toString().trim().split("\n");
	const last = lines[0];
	const first = lines[lines.length - 1];
	if (last == first)
		return `Last updated: <time datetime="${last}">${last}</time>`;
	else
		return `Created: <time datetime="${first}">${first}</time>, last updated: <time datetime="${last}">${last}</time>`;
}

async function template(repodir, contentPath) {
	const tree = await recursiveTree(repodir);
	tree.delete("$template");
	tree.delete("index");

	let html = await fs.readFile(repodir + "/$template.html", { encoding: "utf-8" });

	const content = await fs.readFile(repodir + "/" + contentPath, { encoding: "utf-8" });

	html = html.replace("<!-- REPLACE TREE -->", generateTree(tree, pathRoot));
	html = html.replace("<!-- REPLACE CONTENT -->", content);
	html = html.replace("<!-- REPLACE DATETIME -->", await generateDatetime(repodir, contentPath))

	return html;
}

module.exports = template;