diff --git a/README.md b/README.md index cc284b6..c969ffe 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ The options object can have the following properties: - `nodeOptions` - any valid options to node's underlying `spawn` function - `throwOnError` - if true, non-zero exit codes will throw an error - `nodePath` - if `false`, `node_modules/.bin` directories and the current node executable's directory will not be prepended to `PATH` (defaults to `true`) +- `inheritEnv` - if `false`, `process.env` will not be inherited (defaults to `true`) ### Passing a string to stdin diff --git a/src/env.ts b/src/env.ts index a269c8a..6f66c6e 100644 --- a/src/env.ts +++ b/src/env.ts @@ -59,10 +59,12 @@ function addNodeBinToPath(cwd: URL | string, path: EnvPathInfo): EnvPathInfo { export function computeEnv( cwd: URL | string, env?: EnvLike, - nodePath: boolean = true + nodePath: boolean = true, + inheritEnv: boolean = true ): EnvLike { + const baseEnv = inheritEnv ? process.env : {}; const envWithDefault = { - ...process.env, + ...baseEnv, ...env }; diff --git a/src/main.ts b/src/main.ts index 424d1e7..aa9dc0c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -57,6 +57,7 @@ export interface CommonOptions { timeout: number; throwOnError: boolean; nodePath: boolean; + inheritEnv: boolean; } export interface Options extends CommonOptions { @@ -316,7 +317,12 @@ export class ExecProcess implements Result { nodeOptions.signal = combineSignals(signals); } - nodeOptions.env = computeEnv(cwd, nodeOptions.env, options.nodePath); + nodeOptions.env = computeEnv( + cwd, + nodeOptions.env, + options.nodePath, + options.inheritEnv + ); const crossResult = normalizeSpawnCommand( this._command, @@ -394,7 +400,12 @@ export function xSync( nodeOptions.timeout = opts.timeout; } - nodeOptions.env = computeEnv(cwd, nodeOptions.env, opts.nodePath); + nodeOptions.env = computeEnv( + cwd, + nodeOptions.env, + opts.nodePath, + opts.inheritEnv + ); const crossResult = normalizeSpawnCommand(command, args ?? [], nodeOptions); diff --git a/src/test/env_test.ts b/src/test/env_test.ts index 9f92aa3..34570c0 100644 --- a/src/test/env_test.ts +++ b/src/test/env_test.ts @@ -79,6 +79,17 @@ describe('computeEnv', async () => { expect(env[pathKey]).toBe(originalPath); }); + test('does not inherit process.env when inheritEnv is false', () => { + process.env.TINYEXEC_ISOLATE_TEST = 'foo'; + try { + const env = computeEnv(process.cwd(), {BAR: 'bar'}, false, false); + + expect(env).toEqual({BAR: 'bar'}); + } finally { + delete process.env.TINYEXEC_ISOLATE_TEST; + } + }); + test('prepends local node_modules/.bin and directory of node executable to PATH', () => { /** The original variable is just `PATH=/usr/local/bin` */ const originalPath = path.join(pathSep, 'usr', 'local', 'bin');