Newer
Older
hello-programmer-world / src / plugins / remarkCodeFile.ts
@h.sakamoto h.sakamoto 21 days ago 766 bytes commit
import fs from "node:fs";
import { resolve } from "node:path";
import { visit } from "unist-util-visit";

export default function remarkCodeFile() {
  return (tree: any, _file: any) => {
    visit(tree, "code", (node) => {
      if (!node.meta) return;

      const metaList = node.meta.split(" ");

      const path = metaList
        .find((meta: string) => meta.startsWith("file="))
        ?.slice(5);

      if (!path) return;

      const fullPath = resolve(process.cwd(), path);

      if (!fs.existsSync(fullPath)) {
        node.value = `Error: File not found - ${path}`;
        return;
      }

      node.value = fs.readFileSync(fullPath, "utf8");

      if (!node.meta.includes("title=")) {
        node.meta += ` title=${path}`;
      }
    });
  };
}