Doc transformer

This commit is contained in:
Sidharth Vinod
2022-09-03 02:13:21 +05:30
parent d73cafa7c8
commit cfae2b6a40
3 changed files with 192 additions and 4 deletions

43
src/docs.mts Normal file
View File

@@ -0,0 +1,43 @@
import { remark } from 'remark';
import type { Code, Root } from 'mdast';
import { readFileSync, writeFileSync, mkdirSync, copyFileSync } from 'fs';
// @ts-ignore
import flatmap from 'unist-util-flatmap';
import { globby } from 'globby';
import { join, dirname } from 'path';
// Possible Improvement: combine with lint-staged to only copy files that have changed
const prepareOutFile = (file: string): string => {
const outFile = join('docs', file.replace('src/docs/', ''));
mkdirSync(dirname(outFile), { recursive: true });
return outFile;
};
const transform = (file: string) => {
const doc = readFileSync(file, 'utf8');
const ast: Root = remark.parse(doc);
const out = flatmap(ast, (c: Code) => {
if (c.type !== 'code' || !c.lang?.startsWith('mermaid')) {
return [c];
}
if (c.lang === 'mermaid' || c.lang === 'mmd') {
c.lang = 'mermaid-example';
}
return [c, Object.assign({}, c, { lang: 'mermaid' })];
});
const transformed = `[//]: # 'THIS IS AN AUTOGENERATED FILE. DO NOT EDIT. Please edit corresponding file in src/docs.'\n${remark.stringify(
out
)}`;
const outFile = prepareOutFile(file);
writeFileSync(outFile, transformed);
};
(async () => {
const mdFiles = await globby(['./src/docs/**/*.md']);
mdFiles.forEach(transform);
const nonMDFiles = await globby(['src/docs/**', '!**/*.md']);
nonMDFiles.forEach((file) => {
copyFileSync(file, prepareOutFile(file));
});
})();