From f7e3d4de247dde53bcb1e178788560ebc949d768 Mon Sep 17 00:00:00 2001 From: JT <547158+jntrnr@users.noreply.github.com> Date: Sun, 2 Jan 2022 13:18:39 +1100 Subject: [PATCH] Add fuzzy/ignore flag to get (#641) --- crates/nu-command/src/filters/get.rs | 21 ++++++++++++++++++--- src/tests/test_table_operations.rs | 5 +++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/nu-command/src/filters/get.rs b/crates/nu-command/src/filters/get.rs index 4c2eb6526..152978b21 100644 --- a/crates/nu-command/src/filters/get.rs +++ b/crates/nu-command/src/filters/get.rs @@ -1,7 +1,7 @@ use nu_engine::CallExt; use nu_protocol::ast::{Call, CellPath}; use nu_protocol::engine::{Command, EngineState, Stack}; -use nu_protocol::{Category, IntoPipelineData, PipelineData, Signature, SyntaxShape}; +use nu_protocol::{Category, IntoPipelineData, PipelineData, Signature, SyntaxShape, Value}; #[derive(Clone)] pub struct Get; @@ -22,6 +22,11 @@ impl Command for Get { SyntaxShape::CellPath, "the cell path to the data", ) + .switch( + "ignore-errors", + "return nothing if path can't be found", + Some('i'), + ) .category(Category::Filters) } @@ -33,9 +38,19 @@ impl Command for Get { input: PipelineData, ) -> Result { let cell_path: CellPath = call.req(engine_state, stack, 0)?; + let ignore_errors = call.has_flag("ignore-errors"); - input + let output = input .follow_cell_path(&cell_path.members, call.head) - .map(|x| x.into_pipeline_data()) + .map(|x| x.into_pipeline_data()); + + if ignore_errors { + match output { + Ok(output) => Ok(output), + Err(_) => Ok(Value::Nothing { span: call.head }.into_pipeline_data()), + } + } else { + output + } } } diff --git a/src/tests/test_table_operations.rs b/src/tests/test_table_operations.rs index 6ccb2528d..245d8accb 100644 --- a/src/tests/test_table_operations.rs +++ b/src/tests/test_table_operations.rs @@ -210,3 +210,8 @@ fn length_for_columns() -> TestResult { fn length_for_rows() -> TestResult { run_test(r#"[[name,age,grade]; [bill,20,a] [a b c]] | length"#, "2") } + +#[test] +fn get_fuzzy() -> TestResult { + run_test("(ls | get -i foo) == $nothing", "true") +}