about summary refs log tree commit diff stats
path: root/src/posts.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/posts.ts')
-rw-r--r--src/posts.ts63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/posts.ts b/src/posts.ts
new file mode 100644
index 0000000..c727e12
--- /dev/null
+++ b/src/posts.ts
@@ -0,0 +1,63 @@
+import path from "node:path";
+import fs from "node:fs/promises";
+
+import { matter } from "toml-matter";
+import * as marked from "marked";
+
+type MatterFile = ReturnType<typeof matter>;
+
+export type Post = {
+  input: string;
+  output: string;
+  basename: string;
+  url: string;
+  title: string;
+  date: Date;
+  description: string | undefined;
+  taxonomies: Record<string, string[]>;
+};
+
+export async function getPost(filename: string): Promise<MatterFile> {
+  return matter(await Bun.file(filename).text());
+}
+
+export async function readPosts(
+  root: string,
+  inputDir: string,
+  outputDir: string,
+): Promise<{ posts: Array<Post>; tags: Set<string> }> {
+  let tags = new Set<string>();
+  let posts = new Array<Post>();
+  const subdir = path.join(root, inputDir);
+  for (let pathname of await fs.readdir(subdir)) {
+    const pathFromDir = path.join(inputDir, pathname);
+    const pathFromRoot = path.join(subdir, pathname);
+    const stat = await fs.stat(pathFromRoot);
+    if (stat.isFile() && path.extname(pathname) === ".md") {
+      if (pathname !== "_index.md") {
+        const input = pathFromRoot;
+        const output = pathFromRoot
+          .replace(root, outputDir)
+          .replace(".md", "/index.html");
+        const url = pathFromRoot.replace(root, "").replace(".md", "/");
+
+        const file = await getPost(input);
+
+        file.data.taxonomies?.tags?.map((t: string) =>
+          tags.add(t.toLowerCase()),
+        );
+        posts.push({
+          input,
+          output,
+          basename: path.basename(pathname, ".md"),
+          url,
+          ...file.data,
+        } as Post);
+      }
+    }
+  }
+  return {
+    posts: posts.sort((a, b) => b.date.getTime() - a.date.getTime()),
+    tags,
+  };
+}