From f45c0e36172ae942e55958f7aef3f51c41dd14bd Mon Sep 17 00:00:00 2001 From: Sidharth Vinod Date: Sat, 3 Sep 2022 09:45:59 +0530 Subject: [PATCH] Fail commit if docs changed --- src/docs.mts | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/docs.mts b/src/docs.mts index 3958331af..b1096d08a 100644 --- a/src/docs.mts +++ b/src/docs.mts @@ -1,11 +1,12 @@ import { remark } from 'remark'; import type { Code, Root } from 'mdast'; -import { readFileSync, writeFileSync, mkdirSync, copyFileSync } from 'fs'; +import { readFileSync, writeFileSync, mkdirSync, copyFileSync, existsSync } from 'fs'; // @ts-ignore import flatmap from 'unist-util-flatmap'; import { globby } from 'globby'; import { join, dirname } from 'path'; +let fileChanged = false; // 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/', '')); @@ -13,6 +14,25 @@ const prepareOutFile = (file: string): string => { return outFile; }; +const verifyAndCopy = (file: string, content?: string) => { + const outFile = prepareOutFile(file); + const existing = existsSync(outFile) ? readFileSync(outFile) : Buffer.from('#NEW FILE#'); + if (content !== undefined) { + if (!existing.equals(Buffer.from(content))) { + console.log(`Updating ${outFile}`); + writeFileSync(outFile, content); + fileChanged = true; + } + } else { + const newFile = readFileSync(file); + if (!existing.equals(newFile)) { + console.log(`Copying ${file} to ${outFile}`); + writeFileSync(outFile, newFile); + fileChanged = true; + } + } +}; + const transform = (file: string) => { const doc = readFileSync(file, 'utf8'); const ast: Root = remark.parse(doc); @@ -29,8 +49,7 @@ const transform = (file: string) => { 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); + verifyAndCopy(file, transformed); }; (async () => { @@ -38,6 +57,10 @@ const transform = (file: string) => { mdFiles.forEach(transform); const nonMDFiles = await globby(['src/docs/**', '!**/*.md']); nonMDFiles.forEach((file) => { - copyFileSync(file, prepareOutFile(file)); + verifyAndCopy(file); }); + if (fileChanged) { + console.log('Please commit the changes to the docs folder'); + process.exit(1); + } })();