Skip to content

Instantly share code, notes, and snippets.

@ppenelon
Created September 20, 2021 15:15
Show Gist options
  • Select an option

  • Save ppenelon/958e8755dc953317ad9b2dcb1142b23f to your computer and use it in GitHub Desktop.

Select an option

Save ppenelon/958e8755dc953317ad9b2dcb1142b23f to your computer and use it in GitHub Desktop.
Find out the differences between multiple .env
/**
* Imports
*/
const fs = require('fs');
/**
* Extract env keys from env content
*/
function parseEnv(envContent) {
const lines = envContent.split('\n');
const vars = lines.filter(line => line.trim() && !line.startsWith('#'));
const keys = vars.map(v => v.split('=')[0]);
return keys;
}
/**
* Read file and return parsed env
*/
function parseFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) {
reject(err);
} else {
resolve(parseEnv(data.toString('utf8')));
}
});
});
}
/**
* Return additionnal keys for this array compared to others
*/
Array.prototype.additionnal = function(...arrs) {
let keys = new Set();
for (let arr of arrs) {
if (arr !== this) {
for (let key of arr) {
keys.add(key);
}
}
}
keys = Array.from(keys);
return this.filter(key => !keys.includes(key));
};
/**
* Return missing keys for this array compared to others
*/
Array.prototype.missing = function(...arrs) {
let keys = new Set();
for (let arr of arrs) {
if (arr !== this) {
for (let key of arr) {
keys.add(key);
}
}
}
return Array.from(keys).filter(key => !this.includes(key));
};
/**
* Check differences for every array
*/
function diffArray(...arrs) {
return arrs.map(arr => ({
additionnal: arr.additionnal(...arrs),
missing: arr.missing(...arrs),
}));
}
/**
* Starting point, read argv, process differences and print!
*/
const entryFiles = process.argv.slice(2);
Promise.all(entryFiles.map(parseFile))
.then(files => diffArray(...files))
.then(results => {
for (let i = 0; i < results.length; i++) {
console.log('>>> %s <<<', process.argv[i + 2]);
console.log(results[i]);
}
});
# Usage node diff-env.js [...env files]
node diff-env.js .env.example .env
node diff-env.js .env.example .env .env.development .env.production
# Example output with .env.example and .env
# >>> .env.example <<<
# {
# additionnal: [
# 'CREDENTIALS'
# ],
# missing: [
# 'NEW_FEATURE_ENV'
# ],
# }
# >>> .env <<<
# {
# additionnal: [
# 'NEW_FEATURE_ENV'
# ],
# missing: [
# 'CREDENTIALS'
# ],
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment