Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(env,cli): stale env variables after env files change #28935

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/@expo/env/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

### 🐛 Bug fixes

- Fixed `.load(_, { strict: true })`. As expected, now it overwrites env variables after second call. ([#28935](https://github.com/expo/expo/pull/28935) by [@XantreDev](https://github.com/XantreDev))

### 💡 Others

## 0.3.0 — 2024-04-18
Expand Down
68 changes: 68 additions & 0 deletions packages/@expo/env/src/__tests__/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,74 @@ describe('_getForce', () => {
});
});

describe('load', () => {
const originalError = console.error;
let runtimeEnv: ReturnType<typeof createControlledEnvironment>;
beforeEach(() => {
mockEnv();
runtimeEnv = createControlledEnvironment();
console.error = jest.fn();
});
afterEach(() => {
console.error = originalError;
});

it('loads', () => {
expect(process.env.FOO).toBe(undefined);
vol.fromJSON(
{
'.env': 'FOO=bar',
},
'/'
);
runtimeEnv.load('/');
expect(process.env.FOO).toBe('bar');
});

it('correctly updates vars on env change', () => {
expect(process.env.FOO).toBe(undefined);
vol.fromJSON(
{
'.env': 'FOO=bar',
},
'/'
);
runtimeEnv.load('/', { force: true });
expect(process.env.FOO).toBe('bar');

vol.fromJSON(
{
'.env': 'FOO=foo',
},
'/'
);

runtimeEnv.load('/', { force: true });
expect(process.env.FOO).toBe('foo');
});

it("removes variable if it's no longer exist", () => {
vol.fromJSON(
{
'.env': 'OMIT_ME=1',
},
'/'
);

runtimeEnv.load('/', { force: true });
expect(process.env.OMIT_ME).toBe('1');
vol.fromJSON(
{
'.env': '',
},
'/'
);

runtimeEnv.load('/', { force: true });
expect(process.env.OMIT_ME).toBe(undefined);
});
});

it('does not leak environment variables between tests', () => {
// If this test fails, it means that the test environment is not set-up properly.
// Environment variables are leaking between "originalEnv" and "process.env", causing unexpected test failures/passes.
Expand Down
17 changes: 16 additions & 1 deletion packages/@expo/env/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export function isEnabled(): boolean {
export function createControlledEnvironment() {
let userDefinedEnvironment: NodeJS.ProcessEnv | undefined = undefined;
let memo: { env: NodeJS.ProcessEnv; files: string[] } | undefined = undefined;
let currentParsedEnv: Record<string, unknown> | undefined = undefined;

function _getForce(
projectRoot: string,
Expand Down Expand Up @@ -102,11 +103,16 @@ export function createControlledEnvironment() {
function _expandEnv(parsedEnv: Record<string, string>) {
const expandedEnv: Record<string, string> = {};

const envCopy = { ...process.env };
// allowing vars to be overwritten
for (const key in parsedEnv) {
delete envCopy[key];
}
// Pass a clone of `process.env` to avoid mutating the original environment.
// When the expansion is done, we only store the environment variables that were initially parsed from `parsedEnv`.
const allExpandedEnv = dotenvExpand({
parsed: parsedEnv,
processEnv: { ...process.env } as Record<string, string>,
processEnv: envCopy as Record<string, string>,
});

if (allExpandedEnv.error) {
Expand All @@ -122,6 +128,7 @@ export function createControlledEnvironment() {
expandedEnv[key] = allExpandedEnv.parsed[key];
}
}
currentParsedEnv = allExpandedEnv.parsed;

return expandedEnv;
}
Expand Down Expand Up @@ -149,6 +156,8 @@ export function createControlledEnvironment() {
return process.env;
}

// saving before it will be mutated inside of _expandEnv
const prevParsedEnv = currentParsedEnv;
const envInfo = get(projectRoot, options);

if (!options.force) {
Expand All @@ -161,6 +170,12 @@ export function createControlledEnvironment() {
}
}

// deleting keys that possibly removed from .env file
if (prevParsedEnv) {
for (const key in prevParsedEnv) {
delete process.env[key];
}
}
for (const key of Object.keys(envInfo.env)) {
// Avoid creating a new object, mutate it instead as this causes problems in Bun
process.env[key] = envInfo.env[key];
Expand Down