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}`;
}
});
};
}