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 = `
\n`;
out += elt;
} else { // subdirectory
out += '\n';
out += `
${entry}/\n`;
out += '
\n';
out += generateTree(sub, path + "/" + entry);
out += "
\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: `;
else
return `Created: , last updated: `;
}
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("", generateTree(tree, pathRoot));
html = html.replace("", content);
html = html.replace("", await generateDatetime(repodir, contentPath))
return html;
}
module.exports = template;