Michael Angerman d06f457b2a
nu-cli refactor moving commands into their own crate nu-command (#2910)
* move commands, futures.rs, script.rs, utils

* move over maybe_print_errors

* add nu_command crate references to nu_cli

* in commands.rs open up to pub mod from pub(crate)

* nu-cli, nu-command, and nu tests are now passing

* cargo fmt

* clean up nu-cli/src/prelude.rs

* code cleanup

* for some reason lex.rs was not formatted, may be causing my error

* remove mod completion from lib.rs which was not being used along with quickcheck macros

* add in allow unused imports

* comment out one failing external test; comment out one failing internal test

* revert commenting out failing tests; something else might be going on; someone with a windows machine should check and see what is going on with these failing windows tests

* Update Cargo.toml

Extend the optional features to nu-command

Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com>
2021-01-12 17:59:53 +13:00

129 lines
3.9 KiB
Rust

use crate::prelude::*;
use nu_engine::run_block;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{
hir::CapturedBlock, Signature, SpannedTypeName, SyntaxShape, UntaggedValue, Value,
};
pub struct WithEnv;
#[derive(Deserialize, Debug)]
struct WithEnvArgs {
variable: Value,
block: CapturedBlock,
}
#[async_trait]
impl WholeStreamCommand for WithEnv {
fn name(&self) -> &str {
"with-env"
}
fn signature(&self) -> Signature {
Signature::build("with-env")
.required(
"variable",
SyntaxShape::Any,
"the environment variable to temporarily set",
)
.required(
"block",
SyntaxShape::Block,
"the block to run once the variable is set",
)
}
fn usage(&self) -> &str {
"Runs a block with an environment set. Eg) with-env [NAME 'foo'] { echo $nu.env.NAME }"
}
async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
with_env(args).await
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Set the MYENV environment variable",
example: r#"with-env [MYENV "my env value"] { echo $nu.env.MYENV }"#,
result: Some(vec![Value::from("my env value")]),
},
Example {
description: "Set by primitive value list",
example: r#"with-env [X Y W Z] { echo $nu.env.X $nu.env.W }"#,
result: Some(vec![Value::from("Y"), Value::from("Z")]),
},
Example {
description: "Set by single row table",
example: r#"with-env [[X W]; [Y Z]] { echo $nu.env.X $nu.env.W }"#,
result: Some(vec![Value::from("Y"), Value::from("Z")]),
},
Example {
description: "Set by row(e.g. `open x.json` or `from json`)",
example: r#"echo '{"X":"Y","W":"Z"}'|from json|with-env $it { echo $nu.env.X $nu.env.W }"#,
result: None,
},
]
}
}
async fn with_env(raw_args: CommandArgs) -> Result<OutputStream, ShellError> {
let context = EvaluationContext::from_raw(&raw_args);
let (WithEnvArgs { variable, block }, input) = raw_args.process().await?;
let mut env = IndexMap::new();
match &variable.value {
UntaggedValue::Table(table) => {
if table.len() == 1 {
// single row([[X W]; [Y Z]])
for (k, v) in table[0].row_entries() {
env.insert(k.clone(), v.convert_to_string());
}
} else {
// primitive values([X Y W Z])
for row in table.chunks(2) {
if row.len() == 2 && row[0].is_primitive() && row[1].is_primitive() {
env.insert(row[0].convert_to_string(), row[1].convert_to_string());
}
}
}
}
// when get object by `open x.json` or `from json`
UntaggedValue::Row(row) => {
for (k, v) in &row.entries {
env.insert(k.clone(), v.convert_to_string());
}
}
_ => {
return Err(ShellError::type_error(
"string list or single row",
variable.spanned_type_name(),
));
}
};
context.scope.enter_scope();
context.scope.add_env(env);
context.scope.add_vars(&block.captured.entries);
let result = run_block(&block.block, &context, input).await;
context.scope.exit_scope();
result.map(|x| x.to_output_stream())
}
#[cfg(test)]
mod tests {
use super::ShellError;
use super::WithEnv;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
Ok(test_examples(WithEnv {})?)
}
}