about summary refs log tree commit diff stats
path: root/src/posts.ts
blob: 2b678b9cde6db4645d39dd86f0de6b0b09fd712b (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
import path from "node:path";
import fs from "node:fs/promises";

import { matter } from "toml-matter";

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 fs.readFile(filename, "utf8"));
}

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 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"] as any)?.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,
  };
}