news/utils/build.js

89 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-02-12 10:30:05 +01:00
import { join } from "https://deno.land/std@0.208.0/path/mod.ts";
import { emptyDir } from "https://deno.land/std@0.196.0/fs/empty_dir.ts";
2024-02-13 14:12:54 +01:00
import { addDays, format, nextMonday, setWeek } from "npm:date-fns";
import { marked } from "npm:marked";
import matter from "npm:front-matter";
2024-02-12 10:30:05 +01:00
2024-02-12 11:00:15 +01:00
const SRC_DIR = "./data";
2024-02-12 10:30:05 +01:00
const DEST_DIR = "./dist";
2024-02-26 16:04:13 +01:00
function upgradeText (text) {
text = text.replace(/\@([a-zA-Z0-9_]+)/, (_, twitterId) => {
return `[@${twitterId}](https://twitter.com/${twitterId})`
})
return text
}
2024-02-12 10:30:05 +01:00
async function build() {
2024-02-13 14:12:54 +01:00
let issues = [];
for await (const dirEntry of Deno.readDir(SRC_DIR)) {
if (!dirEntry.isDirectory || !dirEntry.name.match(/^\d{4}$/)) {
continue;
2024-02-12 10:30:05 +01:00
}
2024-02-13 14:12:54 +01:00
//const [fn, ext] = dirEntry.name.split(".");
const year = dirEntry.name;
const yearDir = join(SRC_DIR, year);
console.log(`Processing year: ${year}`);
for await (const dirEntry of Deno.readDir(yearDir)) {
const [fn, ext] = dirEntry.name.split(".");
const weekMatch = fn.match(/^week(\d{2})$/);
if (!weekMatch || ext !== "md") {
continue;
}
const week = weekMatch[1];
const mdPath = join(SRC_DIR, year, dirEntry.name);
const source = await Deno.readTextFile(mdPath);
const issue = {
week: `${year}-${week}`,
period: calcPeriod(year, week),
};
await renderData(issue, source);
issues.push(issue);
2024-02-12 14:03:51 +01:00
}
2024-02-13 14:12:54 +01:00
}
await emptyDir(DEST_DIR);
const outputFn = join(DEST_DIR, "index.json");
await writeJSONFile(outputFn, issues);
2024-02-12 10:30:05 +01:00
}
async function renderData(issue, source) {
2024-02-13 14:12:54 +01:00
const fm = matter(source);
2024-02-26 16:04:13 +01:00
const md = upgradeText(fm.body);
2024-02-13 14:12:54 +01:00
2024-02-26 16:04:13 +01:00
const parsed = marked.parse(md);
2024-02-13 14:12:54 +01:00
return Object.assign(issue, fm.attributes, {
2024-02-26 16:04:13 +01:00
newsMd: md,
2024-02-13 14:12:54 +01:00
newsHtml: parsed,
});
//const fm = matter(issue.source)
//console.log(fm)
//console.log(parsed)
//return
2024-02-12 10:30:05 +01:00
}
function calcPeriod(year, week) {
2024-02-13 14:12:54 +01:00
const weekStart = setWeek(
nextMonday(new Date(Number(year), 0, 4)),
Number(week),
{
weekStartsOn: 1,
firstWeekContainsDate: 4,
},
);
const weekEnd = addDays(weekStart, 6);
return [weekStart, weekEnd];
}
2024-02-12 10:30:05 +01:00
async function writeJSONFile(fn, data) {
2024-02-13 14:12:54 +01:00
console.log(`File written: ${fn}`);
return Deno.writeTextFile(fn, JSON.stringify(data, null, 2));
2024-02-12 10:30:05 +01:00
}
2024-02-13 14:12:54 +01:00
build();