Fail commit if docs changed

This commit is contained in:
Sidharth Vinod 2022-09-03 09:45:59 +05:30
parent 0aabae40ad
commit f45c0e3617
No known key found for this signature in database
GPG Key ID: FB5CCD378D3907CD
1 changed files with 27 additions and 4 deletions

View File

@ -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);
}
})();