Skip to content

Commit

Permalink
feat(cli): Add Deno.env.delete() (#5859)
Browse files Browse the repository at this point in the history
  • Loading branch information
tumile committed Jun 9, 2020
1 parent 44251ce commit 878f306
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
10 changes: 10 additions & 0 deletions cli/js/lib.deno.ns.d.ts
Expand Up @@ -130,6 +130,16 @@ declare namespace Deno {
* Requires `allow-env` permission. */
set(key: string, value: string): void;

/** Delete the value of an environment variable.
*
* ```ts
* Deno.env.set("SOME_VAR", "Value"));
* Deno.env.delete("SOME_VAR"); // outputs "Undefined"
* ```
*
* Requires `allow-env` permission. */
delete(key: string): void;

/** Returns a snapshot of the environment variables at invocation.
*
* ```ts
Expand Down
5 changes: 5 additions & 0 deletions cli/js/ops/os.ts
Expand Up @@ -27,12 +27,17 @@ function getEnv(key: string): string | undefined {
return sendSync("op_get_env", { key })[0];
}

function deleteEnv(key: string): void {
sendSync("op_delete_env", { key });
}

export const env = {
get: getEnv,
toObject(): { [key: string]: string } {
return sendSync("op_env");
},
set: setEnv,
delete: deleteEnv,
};

type DirKind =
Expand Down
17 changes: 17 additions & 0 deletions cli/ops/os.rs
Expand Up @@ -15,6 +15,7 @@ pub fn init(i: &mut CoreIsolate, s: &State) {
i.register_op("op_exec_path", s.stateful_json_op(op_exec_path));
i.register_op("op_set_env", s.stateful_json_op(op_set_env));
i.register_op("op_get_env", s.stateful_json_op(op_get_env));
i.register_op("op_delete_env", s.stateful_json_op(op_delete_env));
i.register_op("op_get_dir", s.stateful_json_op(op_get_dir));
i.register_op("op_hostname", s.stateful_json_op(op_hostname));
i.register_op("op_loadavg", s.stateful_json_op(op_loadavg));
Expand Down Expand Up @@ -137,6 +138,22 @@ fn op_get_env(
Ok(JsonOp::Sync(r))
}

#[derive(Deserialize)]
struct DeleteEnv {
key: String,
}

fn op_delete_env(
state: &State,
args: Value,
_zero_copy: &mut [ZeroCopyBuf],
) -> Result<JsonOp, OpError> {
let args: DeleteEnv = serde_json::from_value(args)?;
state.check_env()?;
env::remove_var(args.key);
Ok(JsonOp::Sync(json!({})))
}

#[derive(Deserialize)]
struct Exit {
code: i32,
Expand Down
7 changes: 7 additions & 0 deletions cli/tests/unit/os_test.ts
Expand Up @@ -20,6 +20,13 @@ unitTest({ perms: { env: true } }, function envNotFound(): void {
assertEquals(r, undefined);
});

unitTest({ perms: { env: true } }, function deleteEnv(): void {
Deno.env.set("TEST_VAR", "A");
assertEquals(Deno.env.get("TEST_VAR"), "A");
assertEquals(Deno.env.delete("TEST_VAR"), undefined);
assertEquals(Deno.env.get("TEST_VAR"), undefined);
});

unitTest(function envPermissionDenied1(): void {
let err;
try {
Expand Down

0 comments on commit 878f306

Please sign in to comment.