nushell/crates/nu-command/src/commands/env/load_env.rs
Hristo Filaretov 88817a8f10
Allow environment variables to be hidden (#3950)
* Allow environment variables to be hidden

This change allows environment variables in Nushell to have a value of
`Nothing`, which can be set by the user by passing `$nothing` to
`let-env` and friends.

Environment variables with a value of Nothing behave as if they are not
set at all. This allows a user to shadow the value of an environment
variable in a parent scope, effectively removing it from their current
scope. This was not possible before, because a scope can not affect its
parent scopes.

This is a workaround for issues like #3920.

Additionally, this allows a user to simultaneously set, change and
remove multiple environment variables via `load-env`. Any environment
variables set to $nothing will be hidden and thus act as if they are
removed. This simplifies working with virtual environments, which rely
on setting multiple environment variables, including PATH, to specific
values, and remove/change them on deactivation.

One surprising behavior is that an environment variable set to $nothing
will act as if it is not set when querying it (via $nu.env.X), but it is
still possible to remove it entirely via `unlet-env`. If the same
environment variable is present in the parent scope, the value in the
parent scope will be visible to the user. This might be surprising
behavior to users who are not familiar with the implementation details.

An additional corner case is the the shorthand form of `with-env` does
not work with this feature. Using `X=$nothing` will set $nu.env.X to the
string "$nothing". The long-form works as expected: `with-env [X
$nothing] {...}`.

* Remove unused import

* Allow all primitives to be convert to strings
2021-08-26 08:15:58 -05:00

100 lines
3.0 KiB
Rust

use std::convert::TryInto;
use crate::prelude::*;
use nu_engine::{EnvVar, WholeStreamCommand};
use nu_errors::ShellError;
use nu_protocol::{Signature, SyntaxShape, Value};
pub struct LoadEnv;
impl WholeStreamCommand for LoadEnv {
fn name(&self) -> &str {
"load-env"
}
fn signature(&self) -> Signature {
Signature::build("load-env").optional(
"environ",
SyntaxShape::Any,
"Optional environment table to load in. If not provided, will use the table provided on the input stream",
)
}
fn usage(&self) -> &str {
"Set environment variables using a table stream"
}
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
load_env(args)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Load variables from an input stream",
example: r#"echo [[name, value]; ["NAME", "JT"] ["AGE", "UNKNOWN"]] | load-env; echo $nu.env.NAME"#,
result: Some(vec![Value::from("JT")]),
},
Example {
description: "Load variables from an argument",
example: r#"load-env [[name, value]; ["NAME", "JT"] ["AGE", "UNKNOWN"]]; echo $nu.env.NAME"#,
result: Some(vec![Value::from("JT")]),
},
Example {
description: "Load variables from an argument and an input stream",
example: r#"echo [[name, value]; ["NAME", "JT"]] | load-env [[name, value]; ["VALUE", "FOO"]]; echo $nu.env.NAME $nu.env.VALUE"#,
result: Some(vec![Value::from("JT"), Value::from("UNKNOWN")]),
},
]
}
}
fn load_env_from_table(
values: impl IntoIterator<Item = Value>,
ctx: &EvaluationContext,
) -> Result<(), ShellError> {
for value in values {
let mut var_name = None;
let mut var_value = None;
let tag = value.tag();
for (key, value) in value.row_entries() {
if key == "name" {
var_name = Some(value);
} else if key == "value" {
var_value = Some(value);
}
}
match (var_name, var_value) {
(Some(name), Some(value)) => {
let env_var: EnvVar = value.try_into()?;
ctx.scope.add_env_var(name.as_string()?, env_var);
}
_ => {
return Err(ShellError::labeled_error(
r#"Expected each row in the table to have a "name" and "value" field."#,
r#"expected a "name" and "value" field"#,
tag,
))
}
}
}
Ok(())
}
pub fn load_env(args: CommandArgs) -> Result<ActionStream, ShellError> {
let ctx = &args.context;
if let Some(values) = args.opt::<Vec<Value>>(0)? {
load_env_from_table(values, ctx)?;
}
load_env_from_table(args.input, ctx)?;
Ok(ActionStream::empty())
}