1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-21 23:04:45 -05:00

feat(unstable): clean environmental variables for subprocess (#11571)

This commit adds "Deno.RunOptions.clearEnv" option, that allows
to clear environmental variables from parent process before spawning
a subprocess.
This commit is contained in:
Leo K 2021-08-04 21:47:43 +02:00 committed by GitHub
parent 1cd95dd8b5
commit 2ac031d6fd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 48 additions and 0 deletions

View file

@ -2034,6 +2034,10 @@ declare namespace Deno {
* Subprocess uses same working directory as parent process unless `opt.cwd`
* is specified.
*
* Environmental variables from parent process can be cleared using `opt.clearEnv`.
* Doesn't guarantee that only `opt.env` variables are present,
* as the OS may set environmental variables for processes.
*
* Environmental variables for subprocess can be specified using `opt.env`
* mapping.
*

View file

@ -791,6 +791,14 @@ declare namespace Deno {
mtime: number | Date,
): Promise<void>;
export function run<
T extends RunOptions & {
clearEnv?: boolean;
} = RunOptions & {
clearEnv?: boolean;
},
>(opt: T): Process<T>;
/** **UNSTABLE**: The `signo` argument may change to require the Deno.Signal
* enum.
*

View file

@ -510,3 +510,31 @@ unitTest({ perms: { run: true, read: true } }, function killFailed(): void {
p.close();
});
unitTest(
{ perms: { run: true, read: true, env: true } },
async function clearEnv(): Promise<void> {
const p = Deno.run({
cmd: [
Deno.execPath(),
"eval",
"-p",
"JSON.stringify(Deno.env.toObject())",
],
stdout: "piped",
clearEnv: true,
env: {
FOO: "23147",
},
});
const obj = JSON.parse(new TextDecoder().decode(await p.output()));
// can't check for object equality because the OS may set additional env vars for processes
// so we check if PATH isn't present as that is a common env var across OS's and isn't set for processes.
assertEquals(obj.FOO, "23147");
assert(!("PATH" in obj));
p.close();
},
);

View file

@ -100,6 +100,7 @@
function run({
cmd,
cwd = undefined,
clearEnv = false,
env = {},
stdout = "inherit",
stderr = "inherit",
@ -111,6 +112,7 @@
const res = opRun({
cmd: ArrayPrototypeMap(cmd, String),
cwd,
clearEnv,
env: ObjectEntries(env),
stdin: isRid(stdin) ? "" : stdin,
stdout: isRid(stdout) ? "" : stdout,

View file

@ -61,6 +61,7 @@ fn subprocess_stdio_map(s: &str) -> Result<std::process::Stdio, AnyError> {
pub struct RunArgs {
cmd: Vec<String>,
cwd: Option<String>,
clear_env: bool,
env: Vec<(String, String)>,
stdin: String,
stdout: String,
@ -113,6 +114,11 @@ fn op_run(
c.arg(arg);
});
cwd.map(|d| c.current_dir(d));
if run_args.clear_env {
super::check_unstable(state, "Deno.run.clearEnv");
c.env_clear();
}
for (key, value) in &env {
c.env(key, value);
}