Skip to content

Commit

Permalink
analyse which env vars should not be overwritten fastify#558
Browse files Browse the repository at this point in the history
  • Loading branch information
tandibar committed Nov 11, 2022
1 parent 31929a5 commit dbd7b70
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions lib/watch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,34 @@ const watch = function (args, ignoreWatch, verboseWatch) {
})

let readyEmitted = false
const envVarsToProtect = [];

const run = (event) => {
const childEvent = { childEvent: event }

// in order to not override existing env vars, we have to load and parse
// dotenv without modifying process.env
let dotenvParsed = {}
const dotenvPath = path.resolve(process.cwd(), '.env')
let dotenvParsed = {};
const dotenvPath = path.resolve(process.cwd(), '.env');
if (existsSync(dotenvPath)) {
dotenvParsed = require('dotenv').parse(readFileSync(dotenvPath, { encoding: 'utf-8' }))
Object.keys(dotenvParsed).forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(process.env, key)) {
// we do not want to overrideexisting env-vars
delete dotenvParsed[key]
}
})
dotenvParsed = require('dotenv').parse(readFileSync(dotenvPath, { encoding: 'utf-8' }));
if (event == 'start') {
// analyse which env-vars should not be overwritten
Object.keys(dotenvParsed).forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(process.env, key)) {
// if a env var already exists with a different value
// than in parsed dotenv, it has to be protected
if (process.env[key] != dotenvParsed[key]) {
envVarsToProtect.push(key);
}
}
});
}
for (const envVarToProtect of envVarsToProtect) {
delete dotenvParsed[envVarToProtect];
}
}
// const env = Object.assign({}, process.env, childEvent, dotenvParsed)
const env = Object.assign({}, dotenvParsed, process.env, childEvent)
const env = Object.assign({}, process.env, dotenvParsed, childEvent);

const _child = cp.fork(forkPath, args, {
env,
Expand Down

0 comments on commit dbd7b70

Please sign in to comment.