Skip to content

Instantly share code, notes, and snippets.

@dmmarmol
Last active July 31, 2023 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmmarmol/4f51c147fcb5a5271d4aba925777cc0c to your computer and use it in GitHub Desktop.
Save dmmarmol/4f51c147fcb5a5271d4aba925777cc0c to your computer and use it in GitHub Desktop.
Script to check the existing variable names of the .env.example file matches the ones in the sibling .env.development file
import fs from "fs";
import dotenv from "dotenv";
import { fileURLToPath } from "url";
import path from "path";
const referenceFiles = [
".env.development",
".env.local",
".env.production",
".env",
];
function fileExists(filePath) {
try {
return fs.existsSync(filePath);
} catch (err) {
return false;
}
}
function findReferenceFile() {
for (const file of referenceFiles) {
if (fileExists(file)) {
return file;
}
}
return null;
}
const __filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(__filename);
const rootDir = path.resolve(dirname, "../");
/**
* @param {string} fileName just the file name + extension, no path required
* @returns
*/
function getEnvVariables(fileName) {
const resolvePath = path.resolve(rootDir, fileName);
const fileContent = fs.readFileSync(resolvePath, "utf-8");
const envConfig = dotenv.parse(fileContent);
return Object.keys(envConfig);
}
function init() {
try {
const referenceFile = findReferenceFile();
if (!referenceFile) {
console.error(
`Error: No reference file (${referenceFiles.join(", ")}) found.`
);
process.exit(1);
}
const referenceEnvVariables = getEnvVariables(referenceFile);
const exampleEnvVariables = getEnvVariables(".env.example");
const missingVariables = referenceEnvVariables.filter(
(variable) => !exampleEnvVariables.includes(variable)
);
if (missingVariables.length === 0) {
console.log(
`All environment variables in .env.example are defined in ${referenceFile}.`
);
} else {
console.error(
`The following environment variables are missing in ${referenceFile}:`
);
console.error(missingVariables);
process.exit(1); // Exit with an error code to fail the pre-push hook
}
} catch (error) {
throw new Error(error);
}
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment