From 41306aa7e0834892e72b1c93423bffb82fc21d4a Mon Sep 17 00:00:00 2001 From: Hofer-Julian <30049909+Hofer-Julian@users.noreply.github.com> Date: Tue, 24 Jan 2023 12:23:42 +0100 Subject: [PATCH] Reduce again the number of match calls (#7815) - Reduce the number of match calls (see commit messages) - A few miscellaneous improvements --- crates/nu-cli/src/config_files.rs | 11 +- crates/nu-cli/src/menus/menu_completions.rs | 7 +- crates/nu-cli/src/prompt_update.rs | 32 +++-- crates/nu-cli/src/reedline_config.rs | 11 +- crates/nu-cli/src/repl.rs | 21 ++-- crates/nu-cli/src/util.rs | 28 ++--- crates/nu-command/src/bytes/at.rs | 38 +++--- crates/nu-command/src/charting/histogram.rs | 21 ++-- .../nu-command/src/conversions/into/string.rs | 7 +- .../nu-command/src/database/values/sqlite.rs | 30 ++--- crates/nu-command/src/dataframe/eager/list.rs | 5 +- crates/nu-command/src/dataframe/eager/open.rs | 9 +- .../src/dataframe/test_dataframe.rs | 36 +++--- crates/nu-command/src/example_test.rs | 25 ++-- crates/nu-command/src/progress_bar.rs | 5 +- crates/nu-command/src/sort_utils.rs | 20 ++- crates/nu-explore/src/commands/tweak.rs | 15 +-- crates/nu-explore/src/lib.rs | 15 +-- crates/nu-explore/src/nu_common/command.rs | 12 +- crates/nu-explore/src/nu_common/table.rs | 17 +-- crates/nu-explore/src/nu_common/value.rs | 8 +- crates/nu-explore/src/pager/events.rs | 9 +- crates/nu-pretty-hex/src/pretty_hex.rs | 10 +- crates/nu-protocol/src/config.rs | 70 ++++------- crates/nu-protocol/src/engine/engine_state.rs | 25 ++-- crates/nu-protocol/src/engine/overlay.rs | 7 +- crates/nu-protocol/src/lev_distance.rs | 5 +- crates/nu-protocol/src/pipeline_data.rs | 49 +++----- crates/nu-protocol/src/value/mod.rs | 114 ++++++++++-------- crates/nu-protocol/src/value/stream.rs | 53 ++++---- crates/nu-system/examples/sys_demo.rs | 7 +- crates/nu-system/src/linux.rs | 57 ++++----- crates/nu-system/src/windows.rs | 22 +--- crates/nu-table/src/nu_protocol_table.rs | 9 +- crates/nu-table/src/table.rs | 15 ++- crates/nu-test-support/src/locale_override.rs | 6 +- .../src/playground/director.rs | 7 +- .../src/playground/matchers.rs | 6 +- crates/nu-utils/src/locale.rs | 21 ++-- crates/nu-utils/src/utils.rs | 15 +-- .../src/cool_custom_value.rs | 21 ++-- crates/nu_plugin_example/src/example.rs | 14 ++- crates/nu_plugin_gstat/src/gstat.rs | 60 ++++----- crates/nu_plugin_inc/src/inc.rs | 11 +- crates/nu_plugin_query/src/query_web.rs | 43 +++---- crates/nu_plugin_query/src/query_xml.rs | 11 +- src/config_files.rs | 27 ++--- src/logger.rs | 19 ++- src/test_bins.rs | 15 +-- 49 files changed, 467 insertions(+), 634 deletions(-) diff --git a/crates/nu-cli/src/config_files.rs b/crates/nu-cli/src/config_files.rs index 695fc21316..cf9fc7b045 100644 --- a/crates/nu-cli/src/config_files.rs +++ b/crates/nu-cli/src/config_files.rs @@ -56,12 +56,11 @@ pub fn add_plugin_file( let working_set = StateWorkingSet::new(engine_state); let cwd = working_set.get_cwd(); - match canonicalize_with(&plugin_file.item, cwd) { - Ok(path) => engine_state.plugin_signatures = Some(path), - Err(_) => { - let e = ParseError::FileNotFound(plugin_file.item, plugin_file.span); - report_error(&working_set, &e); - } + if let Ok(path) = canonicalize_with(&plugin_file.item, cwd) { + engine_state.plugin_signatures = Some(path) + } else { + let e = ParseError::FileNotFound(plugin_file.item, plugin_file.span); + report_error(&working_set, &e); } } else if let Some(mut plugin_path) = nu_path::config_dir() { // Path to store plugins signatures diff --git a/crates/nu-cli/src/menus/menu_completions.rs b/crates/nu-cli/src/menus/menu_completions.rs index fe414a3f6b..8f904b3289 100644 --- a/crates/nu-cli/src/menus/menu_completions.rs +++ b/crates/nu-cli/src/menus/menu_completions.rs @@ -81,13 +81,10 @@ fn convert_to_suggestions( ) -> Vec { match value { Value::Record { .. } => { - let text = match value + let text = value .get_data_by_key("value") .and_then(|val| val.as_string().ok()) - { - Some(val) => val, - None => "No value key".to_string(), - }; + .unwrap_or_else(|| "No value key".to_string()); let description = value .get_data_by_key("description") diff --git a/crates/nu-cli/src/prompt_update.rs b/crates/nu-cli/src/prompt_update.rs index 5dac7674e1..1b98f4c8ca 100644 --- a/crates/nu-cli/src/prompt_update.rs +++ b/crates/nu-cli/src/prompt_update.rs @@ -77,20 +77,17 @@ fn get_prompt_string( .and_then(|pipeline_data| { let output = pipeline_data.collect_string("", config).ok(); - match output { - Some(mut x) => { - // Just remove the very last newline. - if x.ends_with('\n') { - x.pop(); - } - - if x.ends_with('\r') { - x.pop(); - } - Some(x) + output.map(|mut x| { + // Just remove the very last newline. + if x.ends_with('\n') { + x.pop(); } - None => None, - } + + if x.ends_with('\r') { + x.pop(); + } + x + }) }) } @@ -107,12 +104,13 @@ pub(crate) fn update_prompt<'prompt>( // Now that we have the prompt string lets ansify it. // <133 A><133 B><133 C> let left_prompt_string = if config.shell_integration { - match left_prompt_string { - Some(prompt_string) => Some(format!( + if let Some(prompt_string) = left_prompt_string { + Some(format!( "{}{}{}", PRE_PROMPT_MARKER, prompt_string, POST_PROMPT_MARKER - )), - None => left_prompt_string, + )) + } else { + left_prompt_string } } else { left_prompt_string diff --git a/crates/nu-cli/src/reedline_config.rs b/crates/nu-cli/src/reedline_config.rs index 5fd023d492..4b5dd615fb 100644 --- a/crates/nu-cli/src/reedline_config.rs +++ b/crates/nu-cli/src/reedline_config.rs @@ -651,14 +651,15 @@ fn add_parsed_keybinding( let pos1 = char_iter.next(); let pos2 = char_iter.next(); - let char = match (pos1, pos2) { - (Some(char), None) => Ok(char), - _ => Err(ShellError::UnsupportedConfigValue( + let char = if let (Some(char), None) = (pos1, pos2) { + char + } else { + return Err(ShellError::UnsupportedConfigValue( "char_".to_string(), c.to_string(), keybinding.keycode.span()?, - )), - }?; + )); + }; KeyCode::Char(char) } diff --git a/crates/nu-cli/src/repl.rs b/crates/nu-cli/src/repl.rs index e8aa9ea0da..1ca4a26787 100644 --- a/crates/nu-cli/src/repl.rs +++ b/crates/nu-cli/src/repl.rs @@ -1002,18 +1002,15 @@ fn run_hook_block( } fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> { - match io::stdout().write_all(seq.as_bytes()) { - Ok(it) => it, - Err(err) => { - return Err(ShellError::GenericError( - "Error writing ansi sequence".into(), - err.to_string(), - Some(Span::unknown()), - None, - Vec::new(), - )); - } - }; + io::stdout().write_all(seq.as_bytes()).map_err(|e| { + ShellError::GenericError( + "Error writing ansi sequence".into(), + e.to_string(), + Some(Span::unknown()), + None, + Vec::new(), + ) + })?; io::stdout().flush().map_err(|e| { ShellError::GenericError( "Error flushing stdio".into(), diff --git a/crates/nu-cli/src/util.rs b/crates/nu-cli/src/util.rs index 39ff70c14b..13dbf89ff0 100644 --- a/crates/nu-cli/src/util.rs +++ b/crates/nu-cli/src/util.rs @@ -315,27 +315,19 @@ pub fn report_error_new( } pub fn get_init_cwd() -> PathBuf { - match std::env::current_dir() { - Ok(cwd) => cwd, - Err(_) => match std::env::var("PWD") { - Ok(cwd) => PathBuf::from(cwd), - Err(_) => match nu_path::home_dir() { - Some(cwd) => cwd, - None => PathBuf::new(), - }, - }, - } + std::env::current_dir().unwrap_or_else(|_| { + std::env::var("PWD") + .map(Into::into) + .unwrap_or_else(|_| nu_path::home_dir().unwrap_or_default()) + }) } pub fn get_guaranteed_cwd(engine_state: &EngineState, stack: &Stack) -> PathBuf { - match nu_engine::env::current_dir(engine_state, stack) { - Ok(p) => p, - Err(e) => { - let working_set = StateWorkingSet::new(engine_state); - report_error(&working_set, &e); - get_init_cwd() - } - } + nu_engine::env::current_dir(engine_state, stack).unwrap_or_else(|e| { + let working_set = StateWorkingSet::new(engine_state); + report_error(&working_set, &e); + get_init_cwd() + }) } #[cfg(test)] diff --git a/crates/nu-command/src/bytes/at.rs b/crates/nu-command/src/bytes/at.rs index 8e9c4dd600..7ce52b288c 100644 --- a/crates/nu-command/src/bytes/at.rs +++ b/crates/nu-command/src/bytes/at.rs @@ -98,32 +98,26 @@ fn parse_range(range: Value, head: Span) -> Result<(isize, isize, Span), ShellEr let start: isize = if start.is_empty() || start == "_" { 0 } else { - match start.trim().parse() { - Ok(s) => s, - Err(_) => { - return Err(ShellError::UnsupportedInput( - "could not perform subbytes".to_string(), - "with this range".to_string(), - head, - span, - )) - } - } + start.trim().parse().map_err(|_| { + ShellError::UnsupportedInput( + "could not perform subbytes".to_string(), + "with this range".to_string(), + head, + span, + ) + })? }; let end: isize = if end.is_empty() || end == "_" { isize::max_value() } else { - match end.trim().parse() { - Ok(s) => s, - Err(_) => { - return Err(ShellError::UnsupportedInput( - "could not perform subbytes".to_string(), - "with this range".to_string(), - head, - span, - )) - } - } + end.trim().parse().map_err(|_| { + ShellError::UnsupportedInput( + "could not perform subbytes".to_string(), + "with this range".to_string(), + head, + span, + ) + })? }; Ok((start, end, span)) } diff --git a/crates/nu-command/src/charting/histogram.rs b/crates/nu-command/src/charting/histogram.rs index 08e77b39fa..56c859fdd8 100644 --- a/crates/nu-command/src/charting/histogram.rs +++ b/crates/nu-command/src/charting/histogram.rs @@ -129,18 +129,15 @@ impl Command for Histogram { let span = call.head; let data_as_value = input.into_value(span); // `input` is not a list, here we can return an error. - match data_as_value.as_list() { - Ok(list_value) => run_histogram( - list_value.to_vec(), - column_name, - frequency_column_name, - calc_method, - span, - // Note that as_list() filters out Value::Error here. - data_as_value.expect_span(), - ), - Err(e) => Err(e), - } + run_histogram( + data_as_value.as_list()?.to_vec(), + column_name, + frequency_column_name, + calc_method, + span, + // Note that as_list() filters out Value::Error here. + data_as_value.expect_span(), + ) } } diff --git a/crates/nu-command/src/conversions/into/string.rs b/crates/nu-command/src/conversions/into/string.rs index 7771c7c3bc..2d058e4ca3 100644 --- a/crates/nu-command/src/conversions/into/string.rs +++ b/crates/nu-command/src/conversions/into/string.rs @@ -234,12 +234,7 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value { span, }, Value::Error { error } => Value::String { - val: { - match into_code(error) { - Some(code) => code, - None => "".to_string(), - } - }, + val: into_code(error).unwrap_or_default(), span, }, Value::Nothing { .. } => Value::String { diff --git a/crates/nu-command/src/database/values/sqlite.rs b/crates/nu-command/src/database/values/sqlite.rs index 714c4c95cb..47c6c4344b 100644 --- a/crates/nu-command/src/database/values/sqlite.rs +++ b/crates/nu-command/src/database/values/sqlite.rs @@ -107,12 +107,7 @@ impl SQLiteDatabase { } pub fn open_connection(&self) -> Result { - let conn = match Connection::open(&self.path) { - Ok(conn) => conn, - Err(err) => return Err(err), - }; - - Ok(conn) + Connection::open(&self.path) } pub fn get_tables(&self, conn: &Connection) -> Result, rusqlite::Error> { @@ -582,18 +577,13 @@ mod test { } pub fn open_connection_in_memory() -> Result { - let db = match Connection::open_in_memory() { - Ok(conn) => conn, - Err(err) => { - return Err(ShellError::GenericError( - "Failed to open SQLite connection in memory".into(), - err.to_string(), - Some(Span::test_data()), - None, - Vec::new(), - )) - } - }; - - Ok(db) + Connection::open_in_memory().map_err(|err| { + ShellError::GenericError( + "Failed to open SQLite connection in memory".into(), + err.to_string(), + Some(Span::test_data()), + None, + Vec::new(), + ) + }) } diff --git a/crates/nu-command/src/dataframe/eager/list.rs b/crates/nu-command/src/dataframe/eager/list.rs index caa911d57d..b88b69b5ea 100644 --- a/crates/nu-command/src/dataframe/eager/list.rs +++ b/crates/nu-command/src/dataframe/eager/list.rs @@ -51,9 +51,8 @@ impl Command for ListDF { let vals = vals .into_iter() - .filter_map(|(name, value)| match NuDataFrame::try_from_value(value) { - Ok(df) => Some((name, df)), - Err(_) => None, + .filter_map(|(name, value)| { + NuDataFrame::try_from_value(value).ok().map(|df| (name, df)) }) .map(|(name, df)| { let name = Value::String { diff --git a/crates/nu-command/src/dataframe/eager/open.rs b/crates/nu-command/src/dataframe/eager/open.rs index 7a315c84d2..af2d8779fb 100644 --- a/crates/nu-command/src/dataframe/eager/open.rs +++ b/crates/nu-command/src/dataframe/eager/open.rs @@ -103,14 +103,13 @@ fn command( let type_id = match &type_option { Some(ref t) => Some((t.item.to_owned(), "Invalid type", t.span)), - None => match file.item.extension() { - Some(e) => Some(( + None => file.item.extension().map(|e| { + ( e.to_string_lossy().into_owned(), "Invalid extension", file.span, - )), - None => None, - }, + ) + }), }; match type_id { diff --git a/crates/nu-command/src/dataframe/test_dataframe.rs b/crates/nu-command/src/dataframe/test_dataframe.rs index 9ca1ebf708..d2b78f5423 100644 --- a/crates/nu-command/src/dataframe/test_dataframe.rs +++ b/crates/nu-command/src/dataframe/test_dataframe.rs @@ -71,32 +71,30 @@ pub fn test_dataframe(cmds: Vec>) { let mut stack = Stack::new(); - match eval_block( + let result = eval_block( &engine_state, &mut stack, &block, PipelineData::empty(), true, true, - ) { - Err(err) => panic!("test eval error in `{}`: {:?}", example.example, err), - Ok(result) => { - let result = result.into_value(Span::test_data()); - println!("input: {}", example.example); - println!("result: {:?}", result); - println!("done: {:?}", start.elapsed()); + ) + .unwrap_or_else(|err| panic!("test eval error in `{}`: {:?}", example.example, err)) + .into_value(Span::test_data()); - // Note. Value implements PartialEq for Bool, Int, Float, String and Block - // If the command you are testing requires to compare another case, then - // you need to define its equality in the Value struct - if let Some(expected) = example.result { - if result != expected { - panic!( - "the example result is different to expected value: {:?} != {:?}", - result, expected - ) - } - } + println!("input: {}", example.example); + println!("result: {:?}", result); + println!("done: {:?}", start.elapsed()); + + // Note. Value implements PartialEq for Bool, Int, Float, String and Block + // If the command you are testing requires to compare another case, then + // you need to define its equality in the Value struct + if let Some(expected) = example.result { + if result != expected { + panic!( + "the example result is different to expected value: {:?} != {:?}", + result, expected + ) } } } diff --git a/crates/nu-command/src/example_test.rs b/crates/nu-command/src/example_test.rs index 1346bd0ad1..cb5f09b93a 100644 --- a/crates/nu-command/src/example_test.rs +++ b/crates/nu-command/src/example_test.rs @@ -306,22 +306,19 @@ mod test_examples { engine_state: &mut Box, ) -> Option { let (mut block, delta) = parse(src, engine_state); - match block.pipelines.len() { - 1 => { - let n_expressions = block.pipelines[0].elements.len(); - block.pipelines[0].elements.truncate(&n_expressions - 1); + if block.pipelines.len() == 1 { + let n_expressions = block.pipelines[0].elements.len(); + block.pipelines[0].elements.truncate(&n_expressions - 1); - if !block.pipelines[0].elements.is_empty() { - let empty_input = PipelineData::empty(); - Some(eval_block(block, empty_input, cwd, engine_state, delta)) - } else { - Some(Value::nothing(Span::test_data())) - } - } - _ => { - // E.g. multiple semicolon-separated statements - None + if !block.pipelines[0].elements.is_empty() { + let empty_input = PipelineData::empty(); + Some(eval_block(block, empty_input, cwd, engine_state, delta)) + } else { + Some(Value::nothing(Span::test_data())) } + } else { + // E.g. multiple semicolon-separated statements + None } } } diff --git a/crates/nu-command/src/progress_bar.rs b/crates/nu-command/src/progress_bar.rs index cb3ca3d0a8..b757cde48d 100644 --- a/crates/nu-command/src/progress_bar.rs +++ b/crates/nu-command/src/progress_bar.rs @@ -26,10 +26,7 @@ impl NuProgressBar { } }; - let total_bytes = match total_bytes { - Some(total_size) => total_size, - _ => 0, - }; + let total_bytes = total_bytes.unwrap_or_default(); let new_progress_bar = ProgressBar::new(total_bytes); new_progress_bar.set_style( diff --git a/crates/nu-command/src/sort_utils.rs b/crates/nu-command/src/sort_utils.rs index 4560a8505b..b8313d5cf4 100644 --- a/crates/nu-command/src/sort_utils.rs +++ b/crates/nu-command/src/sort_utils.rs @@ -45,16 +45,13 @@ pub fn sort_value_in_place( insensitive: bool, natural: bool, ) -> Result<(), ShellError> { - match val { - Value::List { vals, span } => { - sort(vals, sort_columns, *span, insensitive, natural)?; - if !ascending { - vals.reverse(); - } - Ok(()) + if let Value::List { vals, span } = val { + sort(vals, sort_columns, *span, insensitive, natural)?; + if !ascending { + vals.reverse(); } - _ => Ok(()), } + Ok(()) } pub fn sort( @@ -102,10 +99,9 @@ pub fn sort( let mut vals = vec![]; for item in vec.iter() { for col in &sort_columns { - let val = match item.get_data_by_key(col) { - Some(v) => v, - None => Value::nothing(Span::unknown()), - }; + let val = item + .get_data_by_key(col) + .unwrap_or_else(|| Value::nothing(Span::unknown())); vals.push(val); } } diff --git a/crates/nu-explore/src/commands/tweak.rs b/crates/nu-explore/src/commands/tweak.rs index 6f0d4f701a..d197cbbf9e 100644 --- a/crates/nu-explore/src/commands/tweak.rs +++ b/crates/nu-explore/src/commands/tweak.rs @@ -53,15 +53,12 @@ impl SimpleCommand for TweakCmd { let input = input.trim(); let args = input.split_once(' '); - let (key, value) = match args { - Some(args) => args, - None => { - return Err(io::Error::new( - io::ErrorKind::Other, - "expected to get 2 arguments 'key value'", - )) - } - }; + let (key, value) = args.ok_or_else(|| { + io::Error::new( + io::ErrorKind::Other, + "expected to get 2 arguments 'key value'", + ) + })?; self.value = parse_value(value); diff --git a/crates/nu-explore/src/lib.rs b/crates/nu-explore/src/lib.rs index dd654b30ef..f4e789bc82 100644 --- a/crates/nu-explore/src/lib.rs +++ b/crates/nu-explore/src/lib.rs @@ -171,15 +171,8 @@ fn create_help_manual(cmd: &Command) -> HelpManual { } fn __create_help_manual(manual: Option, name: &'static str) -> HelpManual { - match manual { - Some(manual) => manual, - None => HelpManual { - name, - description: "", - arguments: Vec::new(), - examples: Vec::new(), - input: Vec::new(), - config_options: Vec::new(), - }, - } + manual.unwrap_or(HelpManual { + name, + ..HelpManual::default() + }) } diff --git a/crates/nu-explore/src/nu_common/command.rs b/crates/nu-explore/src/nu_common/command.rs index 44bc9c425c..006e1eae80 100644 --- a/crates/nu-explore/src/nu_common/command.rs +++ b/crates/nu-explore/src/nu_common/command.rs @@ -16,13 +16,11 @@ pub fn run_command_with_value( } let pipeline = PipelineData::Value(input.clone(), None); - let pipeline = run_nu_command(engine_state, stack, command, pipeline); - match pipeline { - Ok(PipelineData::Value(Value::Error { error }, ..)) => { - Err(ShellError::IOError(error.to_string())) - } - Ok(pipeline) => Ok(pipeline), - Err(err) => Err(err), + let pipeline = run_nu_command(engine_state, stack, command, pipeline)?; + if let PipelineData::Value(Value::Error { error }, ..) = pipeline { + Err(ShellError::IOError(error.to_string())) + } else { + Ok(pipeline) } } diff --git a/crates/nu-explore/src/nu_common/table.rs b/crates/nu-explore/src/nu_common/table.rs index f88c4bf154..edc256b44f 100644 --- a/crates/nu-explore/src/nu_common/table.rs +++ b/crates/nu-explore/src/nu_common/table.rs @@ -87,14 +87,9 @@ fn try_build_list( false, ); - let val = table.draw(table_config, usize::MAX); - - match val { - Some(result) => result, - None => { - value_to_styled_string(&Value::List { vals, span }, config, style_computer).0 - } - } + table.draw(table_config, usize::MAX).unwrap_or_else(|| { + value_to_styled_string(&Value::List { vals, span }, config, style_computer).0 + }) } Ok(None) | Err(_) => { // it means that the list is empty @@ -848,10 +843,8 @@ fn make_styled_string( match value { Value::Float { .. } => { // set dynamic precision from config - let precise_number = match convert_with_precision(&text, float_precision) { - Ok(num) => num, - Err(e) => e.to_string(), - }; + let precise_number = convert_with_precision(&text, float_precision) + .unwrap_or_else(|e| e.to_string()); (precise_number, style_computer.style_primitive(value)) } _ => (text, style_computer.style_primitive(value)), diff --git a/crates/nu-explore/src/nu_common/value.rs b/crates/nu-explore/src/nu_common/value.rs index 84050e4980..c9dd820155 100644 --- a/crates/nu-explore/src/nu_common/value.rs +++ b/crates/nu-explore/src/nu_common/value.rs @@ -170,11 +170,9 @@ fn record_lookup_value(item: &Value, header: &str) -> Value { span: NuSpan::unknown(), }; - let value = item.clone().follow_cell_path(&[path], false, false); - match value { - Ok(value) => value, - Err(_) => item.clone(), - } + item.clone() + .follow_cell_path(&[path], false, false) + .unwrap_or_else(|_| item.clone()) } item => item.clone(), } diff --git a/crates/nu-explore/src/pager/events.rs b/crates/nu-explore/src/pager/events.rs index 7d8348c4ab..97e6879ffd 100644 --- a/crates/nu-explore/src/pager/events.rs +++ b/crates/nu-explore/src/pager/events.rs @@ -35,15 +35,16 @@ impl UIEvents { pub fn next(&self) -> Result> { let now = Instant::now(); match poll(self.tick_rate) { - Ok(true) => match read()? { - Event::Key(event) => Ok(Some(event)), - _ => { + Ok(true) => { + if let Event::Key(event) = read()? { + Ok(Some(event)) + } else { let time_spent = now.elapsed(); let rest = self.tick_rate - time_spent; Self { tick_rate: rest }.next() } - }, + } Ok(false) => Ok(None), Err(err) => Err(err), } diff --git a/crates/nu-pretty-hex/src/pretty_hex.rs b/crates/nu-pretty-hex/src/pretty_hex.rs index b3fac48cc2..0aeafc16c3 100644 --- a/crates/nu-pretty-hex/src/pretty_hex.rs +++ b/crates/nu-pretty-hex/src/pretty_hex.rs @@ -160,10 +160,7 @@ where return Ok(()); } - let amount = match cfg.length { - Some(len) => len, - None => source.as_ref().len(), - }; + let amount = cfg.length.unwrap_or_else(|| source.as_ref().len()); let skip = cfg.skip.unwrap_or(0); @@ -239,10 +236,7 @@ where write!(writer, " ")?; for x in row { let (style, a_char) = categorize_byte(x); - let replacement_char = match a_char { - Some(c) => c, - None => *x as char, - }; + let replacement_char = a_char.unwrap_or(*x as char); if use_color { write!( writer, diff --git a/crates/nu-protocol/src/config.rs b/crates/nu-protocol/src/config.rs index 361389363d..d361a33e37 100644 --- a/crates/nu-protocol/src/config.rs +++ b/crates/nu-protocol/src/config.rs @@ -1119,34 +1119,22 @@ impl Value { // Reconstruct let mut hook_cols = vec![]; let mut hook_vals = vec![]; - match &config.hooks.pre_prompt { - Some(v) => { - hook_cols.push("pre_prompt".into()); - hook_vals.push(v.clone()); - } - None => (), - }; - match &config.hooks.pre_execution { - Some(v) => { - hook_cols.push("pre_execution".into()); - hook_vals.push(v.clone()); - } - None => (), - }; - match &config.hooks.env_change { - Some(v) => { - hook_cols.push("env_change".into()); - hook_vals.push(v.clone()); - } - None => (), - }; - match &config.hooks.display_output { - Some(v) => { - hook_cols.push("display_output".into()); - hook_vals.push(v.clone()); - } - None => (), - }; + if let Some(ref value) = config.hooks.pre_prompt { + hook_cols.push("pre_prompt".into()); + hook_vals.push(value.clone()); + } + if let Some(ref value) = config.hooks.pre_execution { + hook_cols.push("pre_execution".into()); + hook_vals.push(value.clone()); + } + if let Some(ref value) = config.hooks.env_change { + hook_cols.push("env_change".into()); + hook_vals.push(value.clone()); + } + if let Some(ref value) = config.hooks.display_output { + hook_cols.push("display_output".into()); + hook_vals.push(value.clone()); + } vals.push(Value::Record { cols: hook_cols, vals: hook_vals, @@ -1496,8 +1484,8 @@ fn try_parse_trim_strategy( } fn try_parse_trim_methodology(value: &Value) -> Option { - match value.as_string() { - Ok(value) => match value.to_lowercase().as_str() { + if let Ok(value) = value.as_string() { + match value.to_lowercase().as_str() { "wrapping" => { return Some(TrimStrategy::Wrap { try_to_keep_words: false, @@ -1505,8 +1493,9 @@ fn try_parse_trim_methodology(value: &Value) -> Option { } "truncating" => return Some(TrimStrategy::Truncate { suffix: None }), _ => eprintln!("unrecognized $config.table.trim.methodology value; expected either 'truncating' or 'wrapping'"), - }, - Err(_) => eprintln!("$env.config.table.trim.methodology is not a string"), + } + } else { + eprintln!("$env.config.table.trim.methodology is not a string") } None @@ -1548,18 +1537,11 @@ fn create_hooks(value: &Value) -> Result { Ok(hooks) } - v => match v.span() { - Ok(span) => Err(ShellError::UnsupportedConfigValue( - "record for 'hooks' config".into(), - "non-record value".into(), - span, - )), - _ => Err(ShellError::UnsupportedConfigValue( - "record for 'hooks' config".into(), - "non-record value".into(), - Span::unknown(), - )), - }, + v => Err(ShellError::UnsupportedConfigValue( + "record for 'hooks' config".into(), + "non-record value".into(), + v.span().unwrap_or_else(|_| Span::unknown()), + )), } } diff --git a/crates/nu-protocol/src/engine/engine_state.rs b/crates/nu-protocol/src/engine/engine_state.rs index 9ec122eacc..6f744b02da 100644 --- a/crates/nu-protocol/src/engine/engine_state.rs +++ b/crates/nu-protocol/src/engine/engine_state.rs @@ -484,15 +484,17 @@ impl EngineState { serde_json::to_string_pretty(&decl.signature()) .map(|signature| { // Extracting the possible path to the shell used to load the plugin - let shell_str = match shell { - Some(path) => format!( - "-s {}", - path.to_str().expect( - "shell path was checked during registration as a str" + let shell_str = shell + .as_ref() + .map(|path| { + format!( + "-s {}", + path.to_str().expect( + "shell path was checked during registration as a str" + ) ) - ), - None => "".into(), - }; + }) + .unwrap_or_default(); // Each signature is stored in the plugin file with the shell and signature // This information will be used when loading the plugin @@ -1020,9 +1022,10 @@ impl TypeScope { } pub fn add_type(&mut self, input: Type) { - match self.outputs.last_mut() { - Some(v) => v.push(input), - None => self.outputs.push(vec![input]), + if let Some(v) = self.outputs.last_mut() { + v.push(input) + } else { + self.outputs.push(vec![input]) } } diff --git a/crates/nu-protocol/src/engine/overlay.rs b/crates/nu-protocol/src/engine/overlay.rs index 490dd7f645..ff51f3e926 100644 --- a/crates/nu-protocol/src/engine/overlay.rs +++ b/crates/nu-protocol/src/engine/overlay.rs @@ -225,9 +225,10 @@ impl OverlayFrame { } pub fn get_decl(&self, name: &[u8], input: &Type) -> Option { - match self.decls.get(&(name, input) as &dyn DeclKey) { - Some(decl) => Some(*decl), - None => self.decls.get(&(name, &Type::Any) as &dyn DeclKey).cloned(), + if let Some(decl) = self.decls.get(&(name, input) as &dyn DeclKey) { + Some(*decl) + } else { + self.decls.get(&(name, &Type::Any) as &dyn DeclKey).cloned() } } } diff --git a/crates/nu-protocol/src/lev_distance.rs b/crates/nu-protocol/src/lev_distance.rs index 7db054735a..274c0bea11 100644 --- a/crates/nu-protocol/src/lev_distance.rs +++ b/crates/nu-protocol/src/lev_distance.rs @@ -157,11 +157,12 @@ fn find_best_match_for_name_impl<'c>( let mut dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3); let mut best = None; for c in candidates { - match if use_substring_score { + let lev_dist = if use_substring_score { lev_distance_with_substrings(lookup, c, dist) } else { lev_distance(lookup, c, dist) - } { + }; + match lev_dist { Some(0) => return Some(*c), Some(d) => { dist = d - 1; diff --git a/crates/nu-protocol/src/pipeline_data.rs b/crates/nu-protocol/src/pipeline_data.rs index e019047e04..9548386fcd 100644 --- a/crates/nu-protocol/src/pipeline_data.rs +++ b/crates/nu-protocol/src/pipeline_data.rs @@ -266,13 +266,7 @@ impl PipelineData { let mut output = String::new(); for val in s { - match val { - Ok(val) => match val.as_string() { - Ok(s) => output.push_str(&s), - Err(err) => return Err(err), - }, - Err(e) => return Err(e), - } + output.push_str(&val?.as_string()?); } if trim_end_newline { output.truncate(output.trim_end_matches(LINE_ENDING_PATTERN).len()); @@ -449,12 +443,10 @@ impl PipelineData { .into_pipeline_data(ctrlc)) } } - PipelineData::Value(Value::Range { val, .. }, ..) => { - match val.into_range_iter(ctrlc.clone()) { - Ok(iter) => Ok(iter.flat_map(f).into_pipeline_data(ctrlc)), - Err(error) => Err(error), - } - } + PipelineData::Value(Value::Range { val, .. }, ..) => Ok(val + .into_range_iter(ctrlc.clone())? + .flat_map(f) + .into_pipeline_data(ctrlc)), PipelineData::Value(v, ..) => Ok(f(v).into_iter().into_pipeline_data(ctrlc)), } } @@ -558,10 +550,10 @@ impl PipelineData { let stderr = stderr.map(|stderr_stream| { let stderr_ctrlc = stderr_stream.ctrlc.clone(); let stderr_span = stderr_stream.span; - let stderr_bytes = match stderr_stream.into_bytes() { - Err(_) => vec![], - Ok(bytes) => bytes.item, - }; + let stderr_bytes = stderr_stream + .into_bytes() + .map(|bytes| bytes.item) + .unwrap_or_default(); RawStream::new( Box::new(vec![Ok(stderr_bytes)].into_iter()), stderr_ctrlc, @@ -642,20 +634,17 @@ impl PipelineData { */ } - match engine_state.find_decl("table".as_bytes(), &[]) { - Some(decl_id) => { - let command = engine_state.get_decl(decl_id); - if command.get_block_id().is_some() { - return self.write_all_and_flush(engine_state, config, no_newline, to_stderr); - } - - let table = command.run(engine_state, stack, &Call::new(Span::new(0, 0)), self)?; - - table.write_all_and_flush(engine_state, config, no_newline, to_stderr)?; - } - None => { - self.write_all_and_flush(engine_state, config, no_newline, to_stderr)?; + if let Some(decl_id) = engine_state.find_decl("table".as_bytes(), &[]) { + let command = engine_state.get_decl(decl_id); + if command.get_block_id().is_some() { + return self.write_all_and_flush(engine_state, config, no_newline, to_stderr); } + + let table = command.run(engine_state, stack, &Call::new(Span::new(0, 0)), self)?; + + table.write_all_and_flush(engine_state, config, no_newline, to_stderr)?; + } else { + self.write_all_and_flush(engine_state, config, no_newline, to_stderr)?; }; Ok(0) diff --git a/crates/nu-protocol/src/value/mod.rs b/crates/nu-protocol/src/value/mod.rs index 83a34a8218..efc7f0babd 100644 --- a/crates/nu-protocol/src/value/mod.rs +++ b/crates/nu-protocol/src/value/mod.rs @@ -197,9 +197,6 @@ impl Value { Value::Binary { val, .. } => Ok(match std::str::from_utf8(val) { Ok(s) => s.to_string(), Err(_) => { - // println!("{:?}", e); - // println!("bytes: {}", pretty_hex::pretty_hex(&val)); - // panic!("let's see it"); return Err(ShellError::CantConvert( "string".into(), "binary".into(), @@ -495,9 +492,10 @@ impl Value { separator: &str, config: &Config, ) -> Result { - match self { - Value::Error { error } => Err(error.to_owned()), - _ => Ok(self.into_string(separator, config)), + if let Value::Error { error } = self { + Err(error.to_owned()) + } else { + Ok(self.into_string(separator, config)) } } @@ -1813,10 +1811,13 @@ impl PartialOrd for Value { result } } - Value::LazyRecord { val, .. } => match val.collect() { - Ok(rhs) => self.partial_cmp(&rhs), - Err(_) => None, - }, + Value::LazyRecord { val, .. } => { + if let Ok(rhs) = val.collect() { + self.partial_cmp(&rhs) + } else { + None + } + } Value::List { .. } => Some(Ordering::Less), Value::Block { .. } => Some(Ordering::Less), Value::Closure { .. } => Some(Ordering::Less), @@ -1967,10 +1968,13 @@ impl PartialOrd for Value { Value::CustomValue { .. } => Some(Ordering::Less), }, (Value::CustomValue { val: lhs, .. }, rhs) => lhs.partial_cmp(rhs), - (Value::LazyRecord { val, .. }, rhs) => match val.collect() { - Ok(val) => val.partial_cmp(rhs), - Err(_) => None, - }, + (Value::LazyRecord { val, .. }, rhs) => { + if let Ok(val) = val.collect() { + val.partial_cmp(rhs) + } else { + None + } + } } } } @@ -2012,13 +2016,14 @@ impl Value { span, }), (Value::Date { val: lhs, .. }, Value::Duration { val: rhs, .. }) => { - match lhs.checked_add_signed(chrono::Duration::nanoseconds(*rhs)) { - Some(val) => Ok(Value::Date { val, span }), - _ => Err(ShellError::OperatorOverflow( + if let Some(val) = lhs.checked_add_signed(chrono::Duration::nanoseconds(*rhs)) { + Ok(Value::Date { val, span }) + } else { + Err(ShellError::OperatorOverflow( "addition operation overflowed".into(), span, "".into(), - )), + )) } } (Value::Duration { val: lhs, .. }, Value::Duration { val: rhs, .. }) => { @@ -2114,13 +2119,14 @@ impl Value { (Value::Date { val: lhs, .. }, Value::Date { val: rhs, .. }) => { let result = lhs.signed_duration_since(*rhs); - match result.num_nanoseconds() { - Some(v) => Ok(Value::Duration { val: v, span }), - None => Err(ShellError::OperatorOverflow( + if let Some(v) = result.num_nanoseconds() { + Ok(Value::Duration { val: v, span }) + } else { + Err(ShellError::OperatorOverflow( "subtraction operation overflowed".into(), span, "".into(), - )), + )) } } (Value::Date { val: lhs, .. }, Value::Duration { val: rhs, .. }) => { @@ -2552,18 +2558,19 @@ impl Value { return Err(ShellError::TypeMismatch("compatible type".to_string(), op)); } - match self.partial_cmp(rhs) { - Some(ordering) => Ok(Value::Bool { + if let Some(ordering) = self.partial_cmp(rhs) { + Ok(Value::Bool { val: matches!(ordering, Ordering::Less), span, - }), - None => Err(ShellError::OperatorMismatch { + }) + } else { + Err(ShellError::OperatorMismatch { op_span: op, lhs_ty: self.get_type(), lhs_span: self.span()?, rhs_ty: rhs.get_type(), rhs_span: rhs.span()?, - }), + }) } } @@ -2584,19 +2591,18 @@ impl Value { return Err(ShellError::TypeMismatch("compatible type".to_string(), op)); } - match self.partial_cmp(rhs) { - Some(ordering) => Ok(Value::Bool { + self.partial_cmp(rhs) + .map(|ordering| Value::Bool { val: matches!(ordering, Ordering::Less | Ordering::Equal), span, - }), - None => Err(ShellError::OperatorMismatch { + }) + .ok_or(ShellError::OperatorMismatch { op_span: op, lhs_ty: self.get_type(), lhs_span: self.span()?, rhs_ty: rhs.get_type(), rhs_span: rhs.span()?, - }), - } + }) } pub fn gt(&self, op: Span, rhs: &Value, span: Span) -> Result { @@ -2616,19 +2622,18 @@ impl Value { return Err(ShellError::TypeMismatch("compatible type".to_string(), op)); } - match self.partial_cmp(rhs) { - Some(ordering) => Ok(Value::Bool { + self.partial_cmp(rhs) + .map(|ordering| Value::Bool { val: matches!(ordering, Ordering::Greater), span, - }), - None => Err(ShellError::OperatorMismatch { + }) + .ok_or(ShellError::OperatorMismatch { op_span: op, lhs_ty: self.get_type(), lhs_span: self.span()?, rhs_ty: rhs.get_type(), rhs_span: rhs.span()?, - }), - } + }) } pub fn gte(&self, op: Span, rhs: &Value, span: Span) -> Result { @@ -2668,12 +2673,13 @@ impl Value { return lhs.operation(*span, Operator::Comparison(Comparison::Equal), op, rhs); } - match self.partial_cmp(rhs) { - Some(ordering) => Ok(Value::Bool { + if let Some(ordering) = self.partial_cmp(rhs) { + Ok(Value::Bool { val: matches!(ordering, Ordering::Equal), span, - }), - None => match (self, rhs) { + }) + } else { + match (self, rhs) { (Value::Nothing { .. }, _) | (_, Value::Nothing { .. }) => { Ok(Value::Bool { val: false, span }) } @@ -2684,7 +2690,7 @@ impl Value { rhs_ty: rhs.get_type(), rhs_span: rhs.span()?, }), - }, + } } } @@ -2693,12 +2699,13 @@ impl Value { return lhs.operation(*span, Operator::Comparison(Comparison::NotEqual), op, rhs); } - match self.partial_cmp(rhs) { - Some(ordering) => Ok(Value::Bool { + if let Some(ordering) = self.partial_cmp(rhs) { + Ok(Value::Bool { val: !matches!(ordering, Ordering::Equal), span, - }), - None => match (self, rhs) { + }) + } else { + match (self, rhs) { (Value::Nothing { .. }, _) | (_, Value::Nothing { .. }) => { Ok(Value::Bool { val: true, span }) } @@ -2709,7 +2716,7 @@ impl Value { rhs_ty: rhs.get_type(), rhs_span: rhs.span()?, }), - }, + } } } @@ -2844,9 +2851,10 @@ impl Value { }, ) => { let is_match = match engine_state.regex_cache.try_lock() { - Ok(mut cache) => match cache.get(rhs) { - Some(regex) => regex.is_match(lhs), - None => { + Ok(mut cache) => { + if let Some(regex) = cache.get(rhs) { + regex.is_match(lhs) + } else { let regex = Regex::new(rhs).map_err(|e| { ShellError::UnsupportedInput( format!("{e}"), @@ -2859,7 +2867,7 @@ impl Value { cache.put(rhs.clone(), regex); ret } - }, + } Err(_) => { let regex = Regex::new(rhs).map_err(|e| { ShellError::UnsupportedInput( diff --git a/crates/nu-protocol/src/value/stream.rs b/crates/nu-protocol/src/value/stream.rs index d9b3621888..e826a7013a 100644 --- a/crates/nu-protocol/src/value/stream.rs +++ b/crates/nu-protocol/src/value/stream.rs @@ -84,28 +84,24 @@ impl Iterator for RawStream { // If we know we're already binary, just output that if self.is_binary { - match self.stream.next() { - Some(buffer) => match buffer { - Ok(mut v) => { - if !self.leftover.is_empty() { - while let Some(b) = self.leftover.pop() { - v.insert(0, b); - } + self.stream.next().map(|buffer| { + buffer.map(|mut v| { + if !self.leftover.is_empty() { + for b in self.leftover.drain(..).rev() { + v.insert(0, b); } - Some(Ok(Value::Binary { - val: v, - span: self.span, - })) } - Err(e) => Some(Err(e)), - }, - None => None, - } + Value::Binary { + val: v, + span: self.span, + } + }) + }) } else { // We *may* be text. We're only going to try utf-8. Other decodings // needs to be taken as binary first, then passed through `decode`. - match self.stream.next() { - Some(buffer) => match buffer { + if let Some(buffer) = self.stream.next() { + match buffer { Ok(mut v) => { if !self.leftover.is_empty() { while let Some(b) = self.leftover.pop() { @@ -164,20 +160,17 @@ impl Iterator for RawStream { } } Err(e) => Some(Err(e)), - }, - None => { - if !self.leftover.is_empty() { - let output = Ok(Value::Binary { - val: self.leftover.clone(), - span: self.span, - }); - self.leftover.clear(); - - Some(output) - } else { - None - } } + } else if !self.leftover.is_empty() { + let output = Ok(Value::Binary { + val: self.leftover.clone(), + span: self.span, + }); + self.leftover.clear(); + + Some(output) + } else { + None } } } diff --git a/crates/nu-system/examples/sys_demo.rs b/crates/nu-system/examples/sys_demo.rs index 316e295e30..088c314757 100644 --- a/crates/nu-system/examples/sys_demo.rs +++ b/crates/nu-system/examples/sys_demo.rs @@ -6,10 +6,9 @@ fn main() { target_os = "windows" ))] { - let cores = match std::thread::available_parallelism() { - Ok(p) => p.get(), - Err(_) => 1usize, - }; + let cores = std::thread::available_parallelism() + .map(|p| p.get()) + .unwrap_or(1); for run in 1..=10 { for proc in nu_system::collect_proc(std::time::Duration::from_millis(100), false) { if proc.cpu_usage() > 0.00001 { diff --git a/crates/nu-system/src/linux.rs b/crates/nu-system/src/linux.rs index 28f010dd17..70b3df08f4 100644 --- a/crates/nu-system/src/linux.rs +++ b/crates/nu-system/src/linux.rs @@ -12,10 +12,7 @@ pub enum ProcessTask { impl ProcessTask { pub fn stat(&self) -> Result { match self { - ProcessTask::Process(x) => match x.stat() { - Ok(it) => Ok(it), - Err(err) => Err(err), - }, + ProcessTask::Process(x) => x.stat(), ProcessTask::Task { stat: x, owner: _ } => Ok(*x.clone()), } } @@ -36,13 +33,7 @@ impl ProcessTask { pub fn fd(&self) -> Result, ProcError> { match self { - ProcessTask::Process(x) => { - let fds = match x.fd() { - Ok(f) => f, - Err(e) => return Err(e), - }; - fds.collect() - } + ProcessTask::Process(x) => x.fd()?.collect(), _ => Err(ProcError::Other("not supported".to_string())), } } @@ -113,10 +104,7 @@ pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec let curr_status = curr_proc.status().ok(); let curr_time = Instant::now(); let interval = curr_time - prev_time; - let ppid = match curr_proc.stat() { - Ok(p) => p.ppid, - Err(_) => 0, - }; + let ppid = curr_proc.stat().map(|p| p.ppid).unwrap_or_default(); let curr_proc = ProcessTask::Process(curr_proc); let proc = ProcessInfo { @@ -174,23 +162,25 @@ impl ProcessInfo { /// Get the status of the process pub fn status(&self) -> String { - match self.curr_proc.stat() { - Ok(p) => match p.state { - 'S' => "Sleeping".into(), - 'R' => "Running".into(), - 'D' => "Disk sleep".into(), - 'Z' => "Zombie".into(), - 'T' => "Stopped".into(), - 't' => "Tracing".into(), - 'X' => "Dead".into(), - 'x' => "Dead".into(), - 'K' => "Wakekill".into(), - 'W' => "Waking".into(), - 'P' => "Parked".into(), - _ => "Unknown".into(), - }, - Err(_) => "Unknown".into(), + if let Ok(p) = self.curr_proc.stat() { + match p.state { + 'S' => "Sleeping", + 'R' => "Running", + 'D' => "Disk sleep", + 'Z' => "Zombie", + 'T' => "Stopped", + 't' => "Tracing", + 'X' => "Dead", + 'x' => "Dead", + 'K' => "Wakekill", + 'W' => "Waking", + 'P' => "Parked", + _ => "Unknown", + } + } else { + "Unknown" } + .into() } /// CPU usage as a percent of total @@ -223,9 +213,6 @@ impl ProcessInfo { /// Virtual memory size in bytes pub fn virtual_size(&self) -> u64 { - match self.curr_proc.stat() { - Ok(p) => p.vsize, - Err(_) => 0u64, - } + self.curr_proc.stat().map(|p| p.vsize).unwrap_or_default() } } diff --git a/crates/nu-system/src/windows.rs b/crates/nu-system/src/windows.rs index c7ba79f0b3..7e293aa69a 100644 --- a/crates/nu-system/src/windows.rs +++ b/crates/nu-system/src/windows.rs @@ -194,18 +194,6 @@ pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec all_ok &= thread.is_some(); if all_ok { - // let process_params = unsafe { get_process_params(handle) }; - // match process_params { - // Ok((pp_cmd, pp_env, pp_cwd)) => { - // eprintln!( - // "cmd: {:?}, env: {:?}, cwd: {:?}", - // pp_cmd, - // "noop".to_string(), - // pp_cwd - // ); - // } - // Err(_) => {} - // } let (proc_cmd, proc_env, proc_cwd) = match unsafe { get_process_params(handle) } { Ok(pp) => (pp.0, pp.1, pp.2), Err(_) => (vec![], vec![], PathBuf::new()), @@ -733,10 +721,7 @@ fn get_cmd_line_new(handle: HANDLE) -> Vec { fn get_cmd_line_old(params: &T, handle: HANDLE) -> Vec { match params.get_cmdline(handle) { Ok(buffer) => unsafe { get_cmdline_from_buffer(buffer.as_ptr()) }, - Err(_e) => { - // sysinfo_debug!("get_cmd_line_old failed to get data: {}", _e); - Vec::new() - } + Err(_e) => Vec::new(), } } @@ -765,10 +750,7 @@ fn get_proc_env(params: &T, handle: HANDLE) -> Vec< } result } - Err(_e) => { - // sysinfo_debug!("get_proc_env failed to get data: {}", _e); - Vec::new() - } + Err(_e) => Vec::new(), } } diff --git a/crates/nu-table/src/nu_protocol_table.rs b/crates/nu-table/src/nu_protocol_table.rs index 0c7ce3145e..5006ad3c23 100644 --- a/crates/nu-table/src/nu_protocol_table.rs +++ b/crates/nu-table/src/nu_protocol_table.rs @@ -67,15 +67,16 @@ fn nu_protocol_value_to_json( let mut used_cols: Option<&[String]> = None; for val in &vals { match val { - Value::Record { cols, .. } => match &used_cols { - Some(_cols) => { + Value::Record { cols, .. } => { + if let Some(_cols) = &used_cols { if _cols != cols { used_cols = None; break; } + } else { + used_cols = Some(cols) } - None => used_cols = Some(cols), - }, + } _ => { used_cols = None; break; diff --git a/crates/nu-table/src/table.rs b/crates/nu-table/src/table.rs index 9fe3f796d5..295ff8f729 100644 --- a/crates/nu-table/src/table.rs +++ b/crates/nu-table/src/table.rs @@ -574,15 +574,14 @@ impl Peaker for PriorityMax { fn peak(&mut self, _: &[usize], widths: &[usize]) -> Option { let col = (0..widths.len()).rev().max_by_key(|&i| widths[i]); - match col { - Some(col) => { - if widths[col] == 0 { - None - } else { - Some(col) - } + if let Some(col) = col { + if widths[col] == 0 { + None + } else { + Some(col) } - None => None, + } else { + None } } } diff --git a/crates/nu-test-support/src/locale_override.rs b/crates/nu-test-support/src/locale_override.rs index 7aa0b320f5..2fafd2693a 100644 --- a/crates/nu-test-support/src/locale_override.rs +++ b/crates/nu-test-support/src/locale_override.rs @@ -36,9 +36,5 @@ pub fn with_locale_override(locale_string: &str, func: fn() -> T) -> T { result }; - - match result { - Ok(result) => result, - Err(err) => std::panic::resume_unwind(err), - } + result.unwrap_or_else(|err| std::panic::resume_unwind(err)) } diff --git a/crates/nu-test-support/src/playground/director.rs b/crates/nu-test-support/src/playground/director.rs index 1d795313f4..5c5554bf7f 100644 --- a/crates/nu-test-support/src/playground/director.rs +++ b/crates/nu-test-support/src/playground/director.rs @@ -99,17 +99,14 @@ impl Executable for Director { } } - let process = match binary + let process = binary .construct() .stdout(Stdio::piped()) // .stdin(Stdio::piped()) .stderr(Stdio::piped()) .arg(format!("-c '{}'", commands)) .spawn() - { - Ok(child) => child, - Err(why) => panic!("Can't run test {}", why), - }; + .expect("It should be possible to run tests"); process .wait_with_output() diff --git a/crates/nu-test-support/src/playground/matchers.rs b/crates/nu-test-support/src/playground/matchers.rs index 7c36489e2d..d167a8e41c 100644 --- a/crates/nu-test-support/src/playground/matchers.rs +++ b/crates/nu-test-support/src/playground/matchers.rs @@ -48,10 +48,8 @@ impl CheckerMatchers for Play { Some(out) => out, None => return Ok(()), }; - let actual = match str::from_utf8(actual) { - Err(..) => return Err(format!("{} was not utf8 encoded", description)), - Ok(actual) => actual, - }; + let actual = + str::from_utf8(actual).map_err(|_| format!("{} was not utf8 encoded", description))?; if actual != *out { return Err(format!( diff --git a/crates/nu-utils/src/locale.rs b/crates/nu-utils/src/locale.rs index 13e59d5a5f..f4979ecf58 100644 --- a/crates/nu-utils/src/locale.rs +++ b/crates/nu-utils/src/locale.rs @@ -9,20 +9,15 @@ pub fn get_system_locale() -> Locale { // however Locale::from_name() wants only de so we split and parse it out. let locale_string = locale_string.replace('_', "-"); // en_AU -> en-AU - match Locale::from_name(&locale_string) { - Ok(loc) => loc, - _ => { - let all = num_format::Locale::available_names(); - let locale_prefix = &locale_string.split('-').collect::>(); - if all.contains(&locale_prefix[0]) { - // eprintln!("Found alternate: {}", &locale_prefix[0]); - Locale::from_name(locale_prefix[0]).unwrap_or(Locale::en) - } else { - // eprintln!("Unable to find matching locale. Defaulting to en-US"); - Locale::en - } + Locale::from_name(&locale_string).unwrap_or_else(|_| { + let all = num_format::Locale::available_names(); + let locale_prefix = &locale_string.split('-').collect::>(); + if all.contains(&locale_prefix[0]) { + Locale::from_name(locale_prefix[0]).unwrap_or(Locale::en) + } else { + Locale::en } - } + }) } #[cfg(debug_assertions)] diff --git a/crates/nu-utils/src/utils.rs b/crates/nu-utils/src/utils.rs index 3688225440..d3e789a270 100644 --- a/crates/nu-utils/src/utils.rs +++ b/crates/nu-utils/src/utils.rs @@ -30,12 +30,8 @@ where T: AsRef<[u8]>, { let stdout = std::io::stdout(); - let ret = match stdout.lock().write_all(output.as_ref()) { - Ok(_) => Ok(stdout.lock().flush()?), - Err(err) => Err(err), - }; - - ret + stdout.lock().write_all(output.as_ref())?; + stdout.lock().flush() } pub fn stderr_write_all_and_flush(output: T) -> Result<()> @@ -60,8 +56,9 @@ pub fn get_default_config() -> &'static str { } pub fn get_ls_colors(lscolors_env_string: Option) -> LsColors { - match lscolors_env_string { - Some(s) => LsColors::from_string(&s), - None => LsColors::from_string("st=0:di=0;38;5;81:so=0;38;5;16;48;5;203:ln=0;38;5;203:cd=0;38;5;203;48;5;236:ex=1;38;5;203:or=0;38;5;16;48;5;203:fi=0:bd=0;38;5;81;48;5;236:ow=0:mi=0;38;5;16;48;5;203:*~=0;38;5;243:no=0:tw=0:pi=0;38;5;16;48;5;81:*.z=4;38;5;203:*.t=0;38;5;48:*.o=0;38;5;243:*.d=0;38;5;48:*.a=1;38;5;203:*.c=0;38;5;48:*.m=0;38;5;48:*.p=0;38;5;48:*.r=0;38;5;48:*.h=0;38;5;48:*.ml=0;38;5;48:*.ll=0;38;5;48:*.gv=0;38;5;48:*.cp=0;38;5;48:*.xz=4;38;5;203:*.hs=0;38;5;48:*css=0;38;5;48:*.ui=0;38;5;149:*.pl=0;38;5;48:*.ts=0;38;5;48:*.gz=4;38;5;203:*.so=1;38;5;203:*.cr=0;38;5;48:*.fs=0;38;5;48:*.bz=4;38;5;203:*.ko=1;38;5;203:*.as=0;38;5;48:*.sh=0;38;5;48:*.pp=0;38;5;48:*.el=0;38;5;48:*.py=0;38;5;48:*.lo=0;38;5;243:*.bc=0;38;5;243:*.cc=0;38;5;48:*.pm=0;38;5;48:*.rs=0;38;5;48:*.di=0;38;5;48:*.jl=0;38;5;48:*.rb=0;38;5;48:*.md=0;38;5;185:*.js=0;38;5;48:*.go=0;38;5;48:*.vb=0;38;5;48:*.hi=0;38;5;243:*.kt=0;38;5;48:*.hh=0;38;5;48:*.cs=0;38;5;48:*.mn=0;38;5;48:*.nb=0;38;5;48:*.7z=4;38;5;203:*.ex=0;38;5;48:*.rm=0;38;5;208:*.ps=0;38;5;186:*.td=0;38;5;48:*.la=0;38;5;243:*.aux=0;38;5;243:*.xmp=0;38;5;149:*.mp4=0;38;5;208:*.rpm=4;38;5;203:*.m4a=0;38;5;208:*.zip=4;38;5;203:*.dll=1;38;5;203:*.bcf=0;38;5;243:*.awk=0;38;5;48:*.aif=0;38;5;208:*.zst=4;38;5;203:*.bak=0;38;5;243:*.tgz=4;38;5;203:*.com=1;38;5;203:*.clj=0;38;5;48:*.sxw=0;38;5;186:*.vob=0;38;5;208:*.fsx=0;38;5;48:*.doc=0;38;5;186:*.mkv=0;38;5;208:*.tbz=4;38;5;203:*.ogg=0;38;5;208:*.wma=0;38;5;208:*.mid=0;38;5;208:*.kex=0;38;5;186:*.out=0;38;5;243:*.ltx=0;38;5;48:*.sql=0;38;5;48:*.ppt=0;38;5;186:*.tex=0;38;5;48:*.odp=0;38;5;186:*.log=0;38;5;243:*.arj=4;38;5;203:*.ipp=0;38;5;48:*.sbt=0;38;5;48:*.jpg=0;38;5;208:*.yml=0;38;5;149:*.txt=0;38;5;185:*.csv=0;38;5;185:*.dox=0;38;5;149:*.pro=0;38;5;149:*.bst=0;38;5;149:*TODO=1:*.mir=0;38;5;48:*.bat=1;38;5;203:*.m4v=0;38;5;208:*.pod=0;38;5;48:*.cfg=0;38;5;149:*.pas=0;38;5;48:*.tml=0;38;5;149:*.bib=0;38;5;149:*.ini=0;38;5;149:*.apk=4;38;5;203:*.h++=0;38;5;48:*.pyc=0;38;5;243:*.img=4;38;5;203:*.rst=0;38;5;185:*.swf=0;38;5;208:*.htm=0;38;5;185:*.ttf=0;38;5;208:*.elm=0;38;5;48:*hgrc=0;38;5;149:*.bmp=0;38;5;208:*.fsi=0;38;5;48:*.pgm=0;38;5;208:*.dpr=0;38;5;48:*.xls=0;38;5;186:*.tcl=0;38;5;48:*.mli=0;38;5;48:*.ppm=0;38;5;208:*.bbl=0;38;5;243:*.lua=0;38;5;48:*.asa=0;38;5;48:*.pbm=0;38;5;208:*.avi=0;38;5;208:*.def=0;38;5;48:*.mov=0;38;5;208:*.hxx=0;38;5;48:*.tif=0;38;5;208:*.fon=0;38;5;208:*.zsh=0;38;5;48:*.png=0;38;5;208:*.inc=0;38;5;48:*.jar=4;38;5;203:*.swp=0;38;5;243:*.pid=0;38;5;243:*.gif=0;38;5;208:*.ind=0;38;5;243:*.erl=0;38;5;48:*.ilg=0;38;5;243:*.eps=0;38;5;208:*.tsx=0;38;5;48:*.git=0;38;5;243:*.inl=0;38;5;48:*.rtf=0;38;5;186:*.hpp=0;38;5;48:*.kts=0;38;5;48:*.deb=4;38;5;203:*.svg=0;38;5;208:*.pps=0;38;5;186:*.ps1=0;38;5;48:*.c++=0;38;5;48:*.cpp=0;38;5;48:*.bsh=0;38;5;48:*.php=0;38;5;48:*.exs=0;38;5;48:*.toc=0;38;5;243:*.mp3=0;38;5;208:*.epp=0;38;5;48:*.rar=4;38;5;203:*.wav=0;38;5;208:*.xlr=0;38;5;186:*.tmp=0;38;5;243:*.cxx=0;38;5;48:*.iso=4;38;5;203:*.dmg=4;38;5;203:*.gvy=0;38;5;48:*.bin=4;38;5;203:*.wmv=0;38;5;208:*.blg=0;38;5;243:*.ods=0;38;5;186:*.psd=0;38;5;208:*.mpg=0;38;5;208:*.dot=0;38;5;48:*.cgi=0;38;5;48:*.xml=0;38;5;185:*.htc=0;38;5;48:*.ics=0;38;5;186:*.bz2=4;38;5;203:*.tar=4;38;5;203:*.csx=0;38;5;48:*.ico=0;38;5;208:*.sxi=0;38;5;186:*.nix=0;38;5;149:*.pkg=4;38;5;203:*.bag=4;38;5;203:*.fnt=0;38;5;208:*.idx=0;38;5;243:*.xcf=0;38;5;208:*.exe=1;38;5;203:*.flv=0;38;5;208:*.fls=0;38;5;243:*.otf=0;38;5;208:*.vcd=4;38;5;203:*.vim=0;38;5;48:*.sty=0;38;5;243:*.pdf=0;38;5;186:*.odt=0;38;5;186:*.purs=0;38;5;48:*.h264=0;38;5;208:*.jpeg=0;38;5;208:*.dart=0;38;5;48:*.pptx=0;38;5;186:*.lock=0;38;5;243:*.bash=0;38;5;48:*.rlib=0;38;5;243:*.hgrc=0;38;5;149:*.psm1=0;38;5;48:*.toml=0;38;5;149:*.tbz2=4;38;5;203:*.yaml=0;38;5;149:*.make=0;38;5;149:*.orig=0;38;5;243:*.html=0;38;5;185:*.fish=0;38;5;48:*.diff=0;38;5;48:*.xlsx=0;38;5;186:*.docx=0;38;5;186:*.json=0;38;5;149:*.psd1=0;38;5;48:*.tiff=0;38;5;208:*.flac=0;38;5;208:*.java=0;38;5;48:*.less=0;38;5;48:*.mpeg=0;38;5;208:*.conf=0;38;5;149:*.lisp=0;38;5;48:*.epub=0;38;5;186:*.cabal=0;38;5;48:*.patch=0;38;5;48:*.shtml=0;38;5;185:*.class=0;38;5;243:*.xhtml=0;38;5;185:*.mdown=0;38;5;185:*.dyn_o=0;38;5;243:*.cache=0;38;5;243:*.swift=0;38;5;48:*README=0;38;5;16;48;5;186:*passwd=0;38;5;149:*.ipynb=0;38;5;48:*shadow=0;38;5;149:*.toast=4;38;5;203:*.cmake=0;38;5;149:*.scala=0;38;5;48:*.dyn_hi=0;38;5;243:*.matlab=0;38;5;48:*.config=0;38;5;149:*.gradle=0;38;5;48:*.groovy=0;38;5;48:*.ignore=0;38;5;149:*LICENSE=0;38;5;249:*TODO.md=1:*COPYING=0;38;5;249:*.flake8=0;38;5;149:*INSTALL=0;38;5;16;48;5;186:*setup.py=0;38;5;149:*.gemspec=0;38;5;149:*.desktop=0;38;5;149:*Makefile=0;38;5;149:*Doxyfile=0;38;5;149:*TODO.txt=1:*README.md=0;38;5;16;48;5;186:*.kdevelop=0;38;5;149:*.rgignore=0;38;5;149:*configure=0;38;5;149:*.DS_Store=0;38;5;243:*.fdignore=0;38;5;149:*COPYRIGHT=0;38;5;249:*.markdown=0;38;5;185:*.cmake.in=0;38;5;149:*.gitconfig=0;38;5;149:*INSTALL.md=0;38;5;16;48;5;186:*CODEOWNERS=0;38;5;149:*.gitignore=0;38;5;149:*Dockerfile=0;38;5;149:*SConstruct=0;38;5;149:*.scons_opt=0;38;5;243:*README.txt=0;38;5;16;48;5;186:*SConscript=0;38;5;149:*.localized=0;38;5;243:*.travis.yml=0;38;5;186:*Makefile.in=0;38;5;243:*.gitmodules=0;38;5;149:*LICENSE-MIT=0;38;5;249:*Makefile.am=0;38;5;149:*INSTALL.txt=0;38;5;16;48;5;186:*MANIFEST.in=0;38;5;149:*.synctex.gz=0;38;5;243:*.fdb_latexmk=0;38;5;243:*CONTRIBUTORS=0;38;5;16;48;5;186:*configure.ac=0;38;5;149:*.applescript=0;38;5;48:*appveyor.yml=0;38;5;186:*.clang-format=0;38;5;149:*.gitattributes=0;38;5;149:*LICENSE-APACHE=0;38;5;249:*CMakeCache.txt=0;38;5;243:*CMakeLists.txt=0;38;5;149:*CONTRIBUTORS.md=0;38;5;16;48;5;186:*requirements.txt=0;38;5;149:*CONTRIBUTORS.txt=0;38;5;16;48;5;186:*.sconsign.dblite=0;38;5;243:*package-lock.json=0;38;5;243:*.CFUserTextEncoding=0;38;5;243"), + if let Some(s) = lscolors_env_string { + LsColors::from_string(&s) + } else { + LsColors::from_string("st=0:di=0;38;5;81:so=0;38;5;16;48;5;203:ln=0;38;5;203:cd=0;38;5;203;48;5;236:ex=1;38;5;203:or=0;38;5;16;48;5;203:fi=0:bd=0;38;5;81;48;5;236:ow=0:mi=0;38;5;16;48;5;203:*~=0;38;5;243:no=0:tw=0:pi=0;38;5;16;48;5;81:*.z=4;38;5;203:*.t=0;38;5;48:*.o=0;38;5;243:*.d=0;38;5;48:*.a=1;38;5;203:*.c=0;38;5;48:*.m=0;38;5;48:*.p=0;38;5;48:*.r=0;38;5;48:*.h=0;38;5;48:*.ml=0;38;5;48:*.ll=0;38;5;48:*.gv=0;38;5;48:*.cp=0;38;5;48:*.xz=4;38;5;203:*.hs=0;38;5;48:*css=0;38;5;48:*.ui=0;38;5;149:*.pl=0;38;5;48:*.ts=0;38;5;48:*.gz=4;38;5;203:*.so=1;38;5;203:*.cr=0;38;5;48:*.fs=0;38;5;48:*.bz=4;38;5;203:*.ko=1;38;5;203:*.as=0;38;5;48:*.sh=0;38;5;48:*.pp=0;38;5;48:*.el=0;38;5;48:*.py=0;38;5;48:*.lo=0;38;5;243:*.bc=0;38;5;243:*.cc=0;38;5;48:*.pm=0;38;5;48:*.rs=0;38;5;48:*.di=0;38;5;48:*.jl=0;38;5;48:*.rb=0;38;5;48:*.md=0;38;5;185:*.js=0;38;5;48:*.go=0;38;5;48:*.vb=0;38;5;48:*.hi=0;38;5;243:*.kt=0;38;5;48:*.hh=0;38;5;48:*.cs=0;38;5;48:*.mn=0;38;5;48:*.nb=0;38;5;48:*.7z=4;38;5;203:*.ex=0;38;5;48:*.rm=0;38;5;208:*.ps=0;38;5;186:*.td=0;38;5;48:*.la=0;38;5;243:*.aux=0;38;5;243:*.xmp=0;38;5;149:*.mp4=0;38;5;208:*.rpm=4;38;5;203:*.m4a=0;38;5;208:*.zip=4;38;5;203:*.dll=1;38;5;203:*.bcf=0;38;5;243:*.awk=0;38;5;48:*.aif=0;38;5;208:*.zst=4;38;5;203:*.bak=0;38;5;243:*.tgz=4;38;5;203:*.com=1;38;5;203:*.clj=0;38;5;48:*.sxw=0;38;5;186:*.vob=0;38;5;208:*.fsx=0;38;5;48:*.doc=0;38;5;186:*.mkv=0;38;5;208:*.tbz=4;38;5;203:*.ogg=0;38;5;208:*.wma=0;38;5;208:*.mid=0;38;5;208:*.kex=0;38;5;186:*.out=0;38;5;243:*.ltx=0;38;5;48:*.sql=0;38;5;48:*.ppt=0;38;5;186:*.tex=0;38;5;48:*.odp=0;38;5;186:*.log=0;38;5;243:*.arj=4;38;5;203:*.ipp=0;38;5;48:*.sbt=0;38;5;48:*.jpg=0;38;5;208:*.yml=0;38;5;149:*.txt=0;38;5;185:*.csv=0;38;5;185:*.dox=0;38;5;149:*.pro=0;38;5;149:*.bst=0;38;5;149:*TODO=1:*.mir=0;38;5;48:*.bat=1;38;5;203:*.m4v=0;38;5;208:*.pod=0;38;5;48:*.cfg=0;38;5;149:*.pas=0;38;5;48:*.tml=0;38;5;149:*.bib=0;38;5;149:*.ini=0;38;5;149:*.apk=4;38;5;203:*.h++=0;38;5;48:*.pyc=0;38;5;243:*.img=4;38;5;203:*.rst=0;38;5;185:*.swf=0;38;5;208:*.htm=0;38;5;185:*.ttf=0;38;5;208:*.elm=0;38;5;48:*hgrc=0;38;5;149:*.bmp=0;38;5;208:*.fsi=0;38;5;48:*.pgm=0;38;5;208:*.dpr=0;38;5;48:*.xls=0;38;5;186:*.tcl=0;38;5;48:*.mli=0;38;5;48:*.ppm=0;38;5;208:*.bbl=0;38;5;243:*.lua=0;38;5;48:*.asa=0;38;5;48:*.pbm=0;38;5;208:*.avi=0;38;5;208:*.def=0;38;5;48:*.mov=0;38;5;208:*.hxx=0;38;5;48:*.tif=0;38;5;208:*.fon=0;38;5;208:*.zsh=0;38;5;48:*.png=0;38;5;208:*.inc=0;38;5;48:*.jar=4;38;5;203:*.swp=0;38;5;243:*.pid=0;38;5;243:*.gif=0;38;5;208:*.ind=0;38;5;243:*.erl=0;38;5;48:*.ilg=0;38;5;243:*.eps=0;38;5;208:*.tsx=0;38;5;48:*.git=0;38;5;243:*.inl=0;38;5;48:*.rtf=0;38;5;186:*.hpp=0;38;5;48:*.kts=0;38;5;48:*.deb=4;38;5;203:*.svg=0;38;5;208:*.pps=0;38;5;186:*.ps1=0;38;5;48:*.c++=0;38;5;48:*.cpp=0;38;5;48:*.bsh=0;38;5;48:*.php=0;38;5;48:*.exs=0;38;5;48:*.toc=0;38;5;243:*.mp3=0;38;5;208:*.epp=0;38;5;48:*.rar=4;38;5;203:*.wav=0;38;5;208:*.xlr=0;38;5;186:*.tmp=0;38;5;243:*.cxx=0;38;5;48:*.iso=4;38;5;203:*.dmg=4;38;5;203:*.gvy=0;38;5;48:*.bin=4;38;5;203:*.wmv=0;38;5;208:*.blg=0;38;5;243:*.ods=0;38;5;186:*.psd=0;38;5;208:*.mpg=0;38;5;208:*.dot=0;38;5;48:*.cgi=0;38;5;48:*.xml=0;38;5;185:*.htc=0;38;5;48:*.ics=0;38;5;186:*.bz2=4;38;5;203:*.tar=4;38;5;203:*.csx=0;38;5;48:*.ico=0;38;5;208:*.sxi=0;38;5;186:*.nix=0;38;5;149:*.pkg=4;38;5;203:*.bag=4;38;5;203:*.fnt=0;38;5;208:*.idx=0;38;5;243:*.xcf=0;38;5;208:*.exe=1;38;5;203:*.flv=0;38;5;208:*.fls=0;38;5;243:*.otf=0;38;5;208:*.vcd=4;38;5;203:*.vim=0;38;5;48:*.sty=0;38;5;243:*.pdf=0;38;5;186:*.odt=0;38;5;186:*.purs=0;38;5;48:*.h264=0;38;5;208:*.jpeg=0;38;5;208:*.dart=0;38;5;48:*.pptx=0;38;5;186:*.lock=0;38;5;243:*.bash=0;38;5;48:*.rlib=0;38;5;243:*.hgrc=0;38;5;149:*.psm1=0;38;5;48:*.toml=0;38;5;149:*.tbz2=4;38;5;203:*.yaml=0;38;5;149:*.make=0;38;5;149:*.orig=0;38;5;243:*.html=0;38;5;185:*.fish=0;38;5;48:*.diff=0;38;5;48:*.xlsx=0;38;5;186:*.docx=0;38;5;186:*.json=0;38;5;149:*.psd1=0;38;5;48:*.tiff=0;38;5;208:*.flac=0;38;5;208:*.java=0;38;5;48:*.less=0;38;5;48:*.mpeg=0;38;5;208:*.conf=0;38;5;149:*.lisp=0;38;5;48:*.epub=0;38;5;186:*.cabal=0;38;5;48:*.patch=0;38;5;48:*.shtml=0;38;5;185:*.class=0;38;5;243:*.xhtml=0;38;5;185:*.mdown=0;38;5;185:*.dyn_o=0;38;5;243:*.cache=0;38;5;243:*.swift=0;38;5;48:*README=0;38;5;16;48;5;186:*passwd=0;38;5;149:*.ipynb=0;38;5;48:*shadow=0;38;5;149:*.toast=4;38;5;203:*.cmake=0;38;5;149:*.scala=0;38;5;48:*.dyn_hi=0;38;5;243:*.matlab=0;38;5;48:*.config=0;38;5;149:*.gradle=0;38;5;48:*.groovy=0;38;5;48:*.ignore=0;38;5;149:*LICENSE=0;38;5;249:*TODO.md=1:*COPYING=0;38;5;249:*.flake8=0;38;5;149:*INSTALL=0;38;5;16;48;5;186:*setup.py=0;38;5;149:*.gemspec=0;38;5;149:*.desktop=0;38;5;149:*Makefile=0;38;5;149:*Doxyfile=0;38;5;149:*TODO.txt=1:*README.md=0;38;5;16;48;5;186:*.kdevelop=0;38;5;149:*.rgignore=0;38;5;149:*configure=0;38;5;149:*.DS_Store=0;38;5;243:*.fdignore=0;38;5;149:*COPYRIGHT=0;38;5;249:*.markdown=0;38;5;185:*.cmake.in=0;38;5;149:*.gitconfig=0;38;5;149:*INSTALL.md=0;38;5;16;48;5;186:*CODEOWNERS=0;38;5;149:*.gitignore=0;38;5;149:*Dockerfile=0;38;5;149:*SConstruct=0;38;5;149:*.scons_opt=0;38;5;243:*README.txt=0;38;5;16;48;5;186:*SConscript=0;38;5;149:*.localized=0;38;5;243:*.travis.yml=0;38;5;186:*Makefile.in=0;38;5;243:*.gitmodules=0;38;5;149:*LICENSE-MIT=0;38;5;249:*Makefile.am=0;38;5;149:*INSTALL.txt=0;38;5;16;48;5;186:*MANIFEST.in=0;38;5;149:*.synctex.gz=0;38;5;243:*.fdb_latexmk=0;38;5;243:*CONTRIBUTORS=0;38;5;16;48;5;186:*configure.ac=0;38;5;149:*.applescript=0;38;5;48:*appveyor.yml=0;38;5;186:*.clang-format=0;38;5;149:*.gitattributes=0;38;5;149:*LICENSE-APACHE=0;38;5;249:*CMakeCache.txt=0;38;5;243:*CMakeLists.txt=0;38;5;149:*CONTRIBUTORS.md=0;38;5;16;48;5;186:*requirements.txt=0;38;5;149:*CONTRIBUTORS.txt=0;38;5;16;48;5;186:*.sconsign.dblite=0;38;5;243:*package-lock.json=0;38;5;243:*.CFUserTextEncoding=0;38;5;243") } } diff --git a/crates/nu_plugin_custom_values/src/cool_custom_value.rs b/crates/nu_plugin_custom_values/src/cool_custom_value.rs index 6e125784c1..4e81da8f07 100644 --- a/crates/nu_plugin_custom_values/src/cool_custom_value.rs +++ b/crates/nu_plugin_custom_values/src/cool_custom_value.rs @@ -22,15 +22,18 @@ impl CoolCustomValue { pub fn try_from_value(value: &Value) -> Result { match value { - Value::CustomValue { val, span } => match val.as_any().downcast_ref::() { - Some(cool) => Ok(cool.clone()), - None => Err(ShellError::CantConvert( - "cool".into(), - "non-cool".into(), - *span, - None, - )), - }, + Value::CustomValue { val, span } => { + if let Some(cool) = val.as_any().downcast_ref::() { + Ok(cool.clone()) + } else { + Err(ShellError::CantConvert( + "cool".into(), + "non-cool".into(), + *span, + None, + )) + } + } x => Err(ShellError::CantConvert( "cool".into(), x.get_type().to_string(), diff --git a/crates/nu_plugin_example/src/example.rs b/crates/nu_plugin_example/src/example.rs index 18ddf31ad5..bc97c862de 100644 --- a/crates/nu_plugin_example/src/example.rs +++ b/crates/nu_plugin_example/src/example.rs @@ -35,14 +35,16 @@ impl Example { eprintln!("flag: {:}", flag); eprintln!("rest: {:?}", rest); - match opt { - Some(v) => eprintln!("Found optional value opt: {:}", v), - None => eprintln!("No optional value found"), + if let Some(v) = opt { + eprintln!("Found optional value opt: {:}", v) + } else { + eprintln!("No optional value found") } - match named { - Some(v) => eprintln!("Named value: {:?}", v), - None => eprintln!("No named value found"), + if let Some(v) = named { + eprintln!("Named value: {:?}", v) + } else { + eprintln!("No named value found") } Ok(()) diff --git a/crates/nu_plugin_gstat/src/gstat.rs b/crates/nu_plugin_gstat/src/gstat.rs index 1744643b3f..c6333af306 100644 --- a/crates/nu_plugin_gstat/src/gstat.rs +++ b/crates/nu_plugin_gstat/src/gstat.rs @@ -79,24 +79,18 @@ impl GStat { }, }); } - - let metadata = match std::fs::metadata(&a_path.item) { - Ok(md) => md, - Err(e) => { - return Err(LabeledError { - label: "error with metadata".to_string(), - msg: format!( - "unable to get metadata for [{}], error: {}", - &a_path.item, e - ), - span: if using_input_value { - Some(value.span().expect("unable to get value span")) - } else { - Some(a_path.span) - }, - }); - } - }; + let metadata = std::fs::metadata(&a_path.item).map_err(|e| LabeledError { + label: "error with metadata".to_string(), + msg: format!( + "unable to get metadata for [{}], error: {}", + &a_path.item, e + ), + span: if using_input_value { + Some(value.span().expect("unable to get value span")) + } else { + Some(a_path.span) + }, + })?; // This path has to be a directory if !metadata.is_dir() { @@ -417,25 +411,23 @@ impl Stats { /// Read name of the upstream branch fn read_upstream_name(&mut self, repo: &Repository, branch: &str) { // First grab branch from the name - self.remote = match repo.find_branch(branch, BranchType::Local) { - Ok(branch) => { - // Grab the upstream from the branch - match branch.upstream() { - // Grab the name of the upstream if it's valid UTF-8 - Ok(upstream) => { - // While we have the upstream branch, traverse the graph and count - // ahead-behind commits. - self.read_ahead_behind(repo, &branch, &upstream); + self.remote = if let Ok(branch) = repo.find_branch(branch, BranchType::Local) { + // Grab the upstream from the branch + if let Ok(upstream) = branch.upstream() { + // While we have the upstream branch, traverse the graph and count + // ahead-behind commits. + self.read_ahead_behind(repo, &branch, &upstream); - match upstream.name() { - Ok(Some(name)) => name.to_string(), - _ => String::new(), - } - } - _ => String::new(), + if let Ok(Some(name)) = upstream.name() { + name.to_string() + } else { + String::new() } + } else { + String::new() } - _ => String::new(), + } else { + String::new() }; } diff --git a/crates/nu_plugin_inc/src/inc.rs b/crates/nu_plugin_inc/src/inc.rs index 669548bbcb..a8c1c749c9 100644 --- a/crates/nu_plugin_inc/src/inc.rs +++ b/crates/nu_plugin_inc/src/inc.rs @@ -43,10 +43,13 @@ impl Inc { Value::string(ver.to_string(), head) } - Some(Action::Default) | None => match input.parse::() { - Ok(v) => Value::string((v + 1).to_string(), head), - Err(_) => Value::string(input, head), - }, + Some(Action::Default) | None => { + if let Ok(v) = input.parse::() { + Value::string((v + 1).to_string(), head) + } else { + Value::string(input, head) + } + } } } diff --git a/crates/nu_plugin_query/src/query_web.rs b/crates/nu_plugin_query/src/query_web.rs index 224572e274..af35b0b7a4 100644 --- a/crates/nu_plugin_query/src/query_web.rs +++ b/crates/nu_plugin_query/src/query_web.rs @@ -36,14 +36,10 @@ pub fn parse_selector_params(call: &EvaluatedCall, input: &Value) -> Result "".to_string(), }; let as_html = call.has_flag("as-html"); - let attribute: String = match call.get_flag("attribute")? { - Some(a) => a, - None => "".to_string(), - }; - let as_table: Value = match call.get_flag("as-table")? { - Some(v) => v, - None => Value::nothing(head), - }; + let attribute = call.get_flag("attribute")?.unwrap_or_default(); + let as_table: Value = call + .get_flag("as-table")? + .unwrap_or_else(|| Value::nothing(head)); let inspect = call.has_flag("inspect"); @@ -81,23 +77,22 @@ fn begin_selector_query(input_html: String, selector: Selector, span: Span) -> V selector.inspect, span, ); + } else if selector.attribute.is_empty() { + execute_selector_query( + input_html.as_str(), + selector.query.as_str(), + selector.as_html, + selector.inspect, + span, + ) } else { - match selector.attribute.is_empty() { - true => execute_selector_query( - input_html.as_str(), - selector.query.as_str(), - selector.as_html, - selector.inspect, - span, - ), - false => execute_selector_query_with_attribute( - input_html.as_str(), - selector.query.as_str(), - selector.attribute.as_str(), - selector.inspect, - span, - ), - } + execute_selector_query_with_attribute( + input_html.as_str(), + selector.query.as_str(), + selector.attribute.as_str(), + selector.inspect, + span, + ) } } diff --git a/crates/nu_plugin_query/src/query_xml.rs b/crates/nu_plugin_query/src/query_xml.rs index aec6dd907f..33a72c22e2 100644 --- a/crates/nu_plugin_query/src/query_xml.rs +++ b/crates/nu_plugin_query/src/query_xml.rs @@ -104,17 +104,18 @@ pub fn execute_xpath_query( fn build_xpath(xpath_str: &str, span: &Span) -> Result { let factory = Factory::new(); - match factory.build(xpath_str) { - Ok(xpath) => xpath.ok_or_else(|| LabeledError { + if let Ok(xpath) = factory.build(xpath_str) { + xpath.ok_or_else(|| LabeledError { label: "invalid xpath query".to_string(), msg: "invalid xpath query".to_string(), span: Some(*span), - }), - Err(_) => Err(LabeledError { + }) + } else { + Err(LabeledError { label: "expected valid xpath query".to_string(), msg: "expected valid xpath query".to_string(), span: Some(*span), - }), + }) } } diff --git a/src/config_files.rs b/src/config_files.rs index 8560114205..e54fad9825 100644 --- a/src/config_files.rs +++ b/src/config_files.rs @@ -27,14 +27,11 @@ pub(crate) fn read_config_file( let working_set = StateWorkingSet::new(engine_state); let cwd = working_set.get_cwd(); - match canonicalize_with(&file.item, cwd) { - Ok(path) => { - eval_config_contents(path, engine_state, stack); - } - Err(_) => { - let e = ParseError::FileNotFound(file.item, file.span); - report_error(&working_set, &e); - } + if let Ok(path) = canonicalize_with(&file.item, cwd) { + eval_config_contents(path, engine_state, stack); + } else { + let e = ParseError::FileNotFound(file.item, file.span); + report_error(&working_set, &e); } } else if let Some(mut config_path) = nu_path::config_dir() { config_path.push(NUSHELL_FOLDER); @@ -74,9 +71,9 @@ pub(crate) fn read_config_file( }; match answer.to_lowercase().trim() { - "y" | "" => match File::create(&config_path) { - Ok(mut output) => match write!(output, "{}", config_file) { - Ok(_) => { + "y" | "" => { + if let Ok(mut output) = File::create(&config_path) { + if write!(output, "{}", config_file).is_ok() { let config_type = if is_env_config { "Environment config" } else { @@ -87,8 +84,7 @@ pub(crate) fn read_config_file( config_type, config_path.to_string_lossy() ); - } - Err(_) => { + } else { eprintln!( "Unable to write to {}, sourcing default file instead", config_path.to_string_lossy(), @@ -96,8 +92,7 @@ pub(crate) fn read_config_file( eval_default_config(engine_state, stack, config_file, is_env_config); return; } - }, - Err(_) => { + } else { eprintln!( "Unable to create {}, sourcing default file instead", config_file @@ -105,7 +100,7 @@ pub(crate) fn read_config_file( eval_default_config(engine_state, stack, config_file, is_env_config); return; } - }, + } _ => { eval_default_config(engine_state, stack, config_file, is_env_config); return; diff --git a/src/logger.rs b/src/logger.rs index ebbf1cbf37..7ab043a0ae 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -52,18 +52,17 @@ pub fn logger( fn set_write_logger(level: LevelFilter, config: Config, path: &Path) -> Result<(), SetLoggerError> { // Use TermLogger instead if WriteLogger is not available - match File::create(path) { - Ok(file) => WriteLogger::init(level, config, file), - Err(_) => { - let default_logger = - TermLogger::init(level, config, TerminalMode::Stderr, ColorChoice::Auto); + if let Ok(file) = File::create(path) { + WriteLogger::init(level, config, file) + } else { + let default_logger = + TermLogger::init(level, config, TerminalMode::Stderr, ColorChoice::Auto); - if default_logger.is_ok() { - log::warn!("failed to init WriteLogger, use TermLogger instead"); - } - - default_logger + if default_logger.is_ok() { + log::warn!("failed to init WriteLogger, use TermLogger instead"); } + + default_logger } } diff --git a/src/test_bins.rs b/src/test_bins.rs index e39b459241..abae51966e 100644 --- a/src/test_bins.rs +++ b/src/test_bins.rs @@ -154,12 +154,8 @@ pub fn nu_repl() { let mut last_output = String::new(); for (i, line) in source_lines.iter().enumerate() { - let cwd = match nu_engine::env::current_dir(&engine_state, &stack) { - Ok(d) => d, - Err(err) => { - outcome_err(&engine_state, &err); - } - }; + let cwd = nu_engine::env::current_dir(&engine_state, &stack) + .unwrap_or_else(|err| outcome_err(&engine_state, &err)); // Before doing anything, merge the environment from the previous REPL iteration into the // permanent state. @@ -226,10 +222,9 @@ pub fn nu_repl() { } if let Some(cwd) = stack.get_env_var(&engine_state, "PWD") { - let path = match cwd.as_string() { - Ok(p) => p, - Err(err) => outcome_err(&engine_state, &err), - }; + let path = cwd + .as_string() + .unwrap_or_else(|err| outcome_err(&engine_state, &err)); let _ = std::env::set_current_dir(path); engine_state.add_env_var("PWD".into(), cwd); }