Skip to content

Instantly share code, notes, and snippets.

@maksimil
Last active September 16, 2021 05:00
Show Gist options
  • Save maksimil/777bdbbe9ebe60cb0c9a2c290e133224 to your computer and use it in GitHub Desktop.
Save maksimil/777bdbbe9ebe60cb0c9a2c290e133224 to your computer and use it in GitHub Desktop.
import { promises as fs } from "fs";
import * as path from "path";
import * as jsyaml from "js-yaml";
import { fileURLToPath } from "url";
import MarkdownIt from "markdown-it";
const mdit = new MarkdownIt({});
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const srcdir = path.resolve(__dirname, "./src");
const builddir = path.resolve(__dirname, "./build");
const filedata = (contents) => {
const match = contents.match(/---(.*?)---(.*)/s);
if (match) {
const yaml = match[1];
const md = match[2];
const html = mdit.render(md);
const meta = jsyaml.load(yaml);
return { html, meta: JSON.stringify(meta) };
} else {
const html = mdit.render(contents);
const meta = "{}";
return { html, meta };
}
};
const processfolder = async (folder) => {
const entrs = await fs.readdir(folder, { withFileTypes: true });
const dirspromise = Promise.all(
entrs
.filter((e) => e.isDirectory())
.map((e) => path.resolve(folder, e.name))
.map(processfolder)
);
const cpromise = (async () => {
const contents = await Promise.all(
entrs
.filter((e) => !e.isDirectory())
.map((e) => path.resolve(folder, e.name))
.map(async (file) => {
const contents = await fs.readFile(file, { encoding: "utf-8" });
const name = path.basename(file.match(/(\S*)\./)[1]);
const { html, meta } = filedata(contents);
console.log(" -", name);
return { name, html, meta };
})
);
const allexport = contents.reduce(
(acc, { name, html, meta }) =>
acc +
`export const ${name}Html = \`${html}\`\nexport const ${name}Meta = ${meta};\n`,
""
);
const htmlexport =
contents.reduce(
(acc, { name, html, meta }) => acc + `${name}:\`${html}\`,\n`,
"export const html = {"
) + "};\n";
const metaexport =
contents.reduce(
(acc, { name, html, meta }) => acc + `${name}:${meta},\n`,
"export const meta = {"
) + "};\n";
const filecontents = allexport + htmlexport + metaexport;
const outdir = path.resolve(builddir, path.relative(srcdir, folder));
await fs.mkdir(outdir, { recursive: true });
await Promise.all([
fs.writeFile(path.resolve(outdir, "index.ts"), filecontents),
fs.writeFile(path.resolve(outdir, "package.json"), '{"main":"index.ts"}'),
]);
})();
await Promise.all([dirspromise, cpromise]);
};
const main = async () => {
console.log("Processing markdown");
await processfolder(srcdir);
};
await main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment