Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created August 16, 2024 01:34
Show Gist options
  • Save WomB0ComB0/2630e681fb248b5a7c88e5653d8a6e22 to your computer and use it in GitHub Desktop.
Save WomB0ComB0/2630e681fb248b5a7c88e5653d8a6e22 to your computer and use it in GitHub Desktop.
This TypeScript script compares environment variables from .env files with a predefined set, performing set operations (union, intersection, or difference) specified via command-line arguments. It parses the variables, executes the chosen operation, and outputs the results to a file, providing a flexible tool for analyzing and managing environme…
import { readFileSync, writeFileSync, readdirSync } from "node:fs";
import { join } from "path";
const paste: string = `
<key>=<value>
...
`
const envFiles: string[] = readdirSync(process.cwd()).filter((file) => file.startsWith(".env"));
const parseEnvContent = (content: string): Record<string, string> => {
const lines = content.split("\n");
return lines.reduce((acc, line) => {
const [key, value] = line.split("=").map(part => part.trim());
if (key && value) {
acc[key] = value;
}
return acc;
}, {} as Record<string, string>);
};
const pasteEnv: Record<string, string> = parseEnvContent(paste);
const fileEnvs: { fileName: string; vars: Record<string, string> }[] = envFiles.map(file => ({
fileName: file,
vars: parseEnvContent(readFileSync(join(process.cwd(), file), "utf-8"))
}));
const operation: string = process.argv[2] || 'intersection';
const performSetOperation = (operation: string): { file: string; key: string; value: string }[] => {
const result: { file: string; key: string; value: string }[] = [];
fileEnvs.forEach(({ fileName, vars }): void => {
Object.entries(vars).forEach(([key, value]): void => {
const inPaste = pasteEnv[key] === value || Object.values(pasteEnv).includes(value);
const inFile = true;
switch (operation) {
case 'union':
if (inPaste || inFile) result.push({ file: fileName, key, value });
break;
case 'intersection':
if (inPaste && inFile) result.push({ file: fileName, key, value });
break;
case 'difference':
if (inFile && !inPaste) result.push({ file: fileName, key, value });
break;
}
});
});
return result;
};
const matchingPairs: { file: string; key: string; value: string }[] = performSetOperation(operation);
const output: string = matchingPairs.map(({ file, key, value }): string => `${file}: ${key}=${value}`).join("\n");
writeFileSync(join(process.cwd(), `${operation}_env_vars.txt`), output);
console.log(`${operation.charAt(0).toUpperCase() + operation.slice(1)} of environment variables have been written to ${operation}_env_vars.txt`);
console.log("Paste variables processed:", Object.keys(pasteEnv).length);
console.log("File variables processed:", fileEnvs.reduce((sum, { vars }) => sum + Object.keys(vars).length, 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment