From 99eec73b4b8813c6db7cae83f5415b031de0c2c7 Mon Sep 17 00:00:00 2001 From: Jed Fox Date: Wed, 2 Oct 2019 11:55:28 -0400 Subject: feat: Add support for passing a key to Deno.env() (#2952) This adds a new op to get a single env var. --- cli/deno_error.rs | 12 ++++++++++++ cli/ops/os.rs | 19 +++++++++++++++++++ cli/worker.rs | 4 ++++ 3 files changed, 35 insertions(+) (limited to 'cli') diff --git a/cli/deno_error.rs b/cli/deno_error.rs index eb885adb8..551547e26 100644 --- a/cli/deno_error.rs +++ b/cli/deno_error.rs @@ -11,6 +11,7 @@ use hyper; use reqwest; use rustyline::error::ReadlineError; use std; +use std::env::VarError; use std::error::Error; use std::fmt; use std::io; @@ -136,6 +137,16 @@ impl GetErrorKind for ModuleResolutionError { } } +impl GetErrorKind for VarError { + fn kind(&self) -> ErrorKind { + use VarError::*; + match self { + NotPresent => ErrorKind::NotFound, + NotUnicode(..) => ErrorKind::InvalidData, + } + } +} + impl GetErrorKind for io::Error { fn kind(&self) -> ErrorKind { use io::ErrorKind::*; @@ -294,6 +305,7 @@ impl GetErrorKind for dyn AnyError { .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) + .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| self.downcast_ref::().map(Get::kind)) .or_else(|| { self diff --git a/cli/ops/os.rs b/cli/ops/os.rs index 770af404c..b35b76c2a 100644 --- a/cli/ops/os.rs +++ b/cli/ops/os.rs @@ -102,6 +102,25 @@ pub fn op_env( Ok(JsonOp::Sync(json!(v))) } +#[derive(Deserialize)] +struct GetEnv { + key: String, +} + +pub fn op_get_env( + state: &ThreadSafeState, + args: Value, + _zero_copy: Option, +) -> Result { + let args: GetEnv = serde_json::from_value(args)?; + state.check_env()?; + let r = match env::var(args.key) { + Err(env::VarError::NotPresent) => json!([]), + v => json!([v?]), + }; + Ok(JsonOp::Sync(r)) +} + #[derive(Deserialize)] struct Exit { code: i32, diff --git a/cli/worker.rs b/cli/worker.rs index 6f5e6af41..9bdf2ae08 100644 --- a/cli/worker.rs +++ b/cli/worker.rs @@ -63,6 +63,10 @@ impl Worker { "set_env", state_.cli_op(json_op(state_.stateful_op(os::op_set_env))), ); + i.register_op( + "get_env", + state_.cli_op(json_op(state_.stateful_op(os::op_get_env))), + ); i.register_op( "home_dir", state_.cli_op(json_op(state_.stateful_op(os::op_home_dir))), -- cgit v1.2.3