Reduce again the number of match calls (#7815)

- Reduce the number of match calls (see commit messages)
- A few miscellaneous improvements
This commit is contained in:
Hofer-Julian 2023-01-24 12:23:42 +01:00 committed by GitHub
parent 0bb2e47c98
commit 41306aa7e0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
49 changed files with 467 additions and 634 deletions

View File

@ -56,13 +56,12 @@ 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(_) => {
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
plugin_path.push(storage_path);

View File

@ -81,13 +81,10 @@ fn convert_to_suggestions(
) -> Vec<Suggestion> {
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")

View File

@ -77,8 +77,7 @@ fn get_prompt_string(
.and_then(|pipeline_data| {
let output = pipeline_data.collect_string("", config).ok();
match output {
Some(mut x) => {
output.map(|mut x| {
// Just remove the very last newline.
if x.ends_with('\n') {
x.pop();
@ -87,10 +86,8 @@ fn get_prompt_string(
if x.ends_with('\r') {
x.pop();
}
Some(x)
}
None => None,
}
x
})
})
}
@ -107,12 +104,13 @@ pub(crate) fn update_prompt<'prompt>(
// Now that we have the prompt string lets ansify it.
// <133 A><prompt><133 B><command><133 C><command output>
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

View File

@ -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_<CHAR: unicode codepoint>".to_string(),
c.to_string(),
keybinding.keycode.span()?,
)),
}?;
));
};
KeyCode::Char(char)
}

View File

@ -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(
io::stdout().write_all(seq.as_bytes()).map_err(|e| {
ShellError::GenericError(
"Error writing ansi sequence".into(),
err.to_string(),
e.to_string(),
Some(Span::unknown()),
None,
Vec::new(),
));
}
};
)
})?;
io::stdout().flush().map_err(|e| {
ShellError::GenericError(
"Error flushing stdio".into(),

View File

@ -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) => {
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)]

View File

@ -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(
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(
end.trim().parse().map_err(|_| {
ShellError::UnsupportedInput(
"could not perform subbytes".to_string(),
"with this range".to_string(),
head,
span,
))
}
}
)
})?
};
Ok((start, end, span))
}

View File

@ -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(),
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(),
),
Err(e) => Err(e),
}
)
}
}

View File

@ -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 {

View File

@ -107,12 +107,7 @@ impl SQLiteDatabase {
}
pub fn open_connection(&self) -> Result<Connection, rusqlite::Error> {
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<Vec<DbTable>, rusqlite::Error> {
@ -582,18 +577,13 @@ mod test {
}
pub fn open_connection_in_memory() -> Result<Connection, ShellError> {
let db = match Connection::open_in_memory() {
Ok(conn) => conn,
Err(err) => {
return Err(ShellError::GenericError(
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(),
))
}
};
Ok(db)
)
})
}

View File

@ -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 {

View File

@ -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 {

View File

@ -71,17 +71,17 @@ pub fn test_dataframe(cmds: Vec<Box<dyn Command + 'static>>) {
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());
)
.unwrap_or_else(|err| panic!("test eval error in `{}`: {:?}", example.example, err))
.into_value(Span::test_data());
println!("input: {}", example.example);
println!("result: {:?}", result);
println!("done: {:?}", start.elapsed());
@ -99,5 +99,3 @@ pub fn test_dataframe(cmds: Vec<Box<dyn Command + 'static>>) {
}
}
}
}
}

View File

@ -306,8 +306,7 @@ mod test_examples {
engine_state: &mut Box<EngineState>,
) -> Option<Value> {
let (mut block, delta) = parse(src, engine_state);
match block.pipelines.len() {
1 => {
if block.pipelines.len() == 1 {
let n_expressions = block.pipelines[0].elements.len();
block.pipelines[0].elements.truncate(&n_expressions - 1);
@ -317,11 +316,9 @@ mod test_examples {
} else {
Some(Value::nothing(Span::test_data()))
}
}
_ => {
} else {
// E.g. multiple semicolon-separated statements
None
}
}
}
}

View File

@ -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(

View File

@ -45,17 +45,14 @@ pub fn sort_value_in_place(
insensitive: bool,
natural: bool,
) -> Result<(), ShellError> {
match val {
Value::List { vals, span } => {
if let Value::List { vals, span } = val {
sort(vals, sort_columns, *span, insensitive, natural)?;
if !ascending {
vals.reverse();
}
}
Ok(())
}
_ => Ok(()),
}
}
pub fn sort(
vec: &mut [Value],
@ -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);
}
}

View File

@ -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(
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);

View File

@ -171,15 +171,8 @@ fn create_help_manual(cmd: &Command) -> HelpManual {
}
fn __create_help_manual(manual: Option<HelpManual>, name: &'static str) -> HelpManual {
match manual {
Some(manual) => manual,
None => HelpManual {
manual.unwrap_or(HelpManual {
name,
description: "",
arguments: Vec::new(),
examples: Vec::new(),
input: Vec::new(),
config_options: Vec::new(),
},
}
..HelpManual::default()
})
}

View File

@ -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 }, ..)) => {
let pipeline = run_nu_command(engine_state, stack, command, pipeline)?;
if let PipelineData::Value(Value::Error { error }, ..) = pipeline {
Err(ShellError::IOError(error.to_string()))
}
Ok(pipeline) => Ok(pipeline),
Err(err) => Err(err),
} else {
Ok(pipeline)
}
}

View File

@ -87,14 +87,9 @@ fn try_build_list(
false,
);
let val = table.draw(table_config, usize::MAX);
match val {
Some(result) => result,
None => {
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)),

View File

@ -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(),
}

View File

@ -35,15 +35,16 @@ impl UIEvents {
pub fn next(&self) -> Result<Option<KeyEvent>> {
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),
}

View File

@ -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,

View File

@ -1119,34 +1119,22 @@ impl Value {
// Reconstruct
let mut hook_cols = vec![];
let mut hook_vals = vec![];
match &config.hooks.pre_prompt {
Some(v) => {
if let Some(ref value) = config.hooks.pre_prompt {
hook_cols.push("pre_prompt".into());
hook_vals.push(v.clone());
hook_vals.push(value.clone());
}
None => (),
};
match &config.hooks.pre_execution {
Some(v) => {
if let Some(ref value) = config.hooks.pre_execution {
hook_cols.push("pre_execution".into());
hook_vals.push(v.clone());
hook_vals.push(value.clone());
}
None => (),
};
match &config.hooks.env_change {
Some(v) => {
if let Some(ref value) = config.hooks.env_change {
hook_cols.push("env_change".into());
hook_vals.push(v.clone());
hook_vals.push(value.clone());
}
None => (),
};
match &config.hooks.display_output {
Some(v) => {
if let Some(ref value) = config.hooks.display_output {
hook_cols.push("display_output".into());
hook_vals.push(v.clone());
hook_vals.push(value.clone());
}
None => (),
};
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<TrimStrategy> {
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<TrimStrategy> {
}
"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<Hooks, ShellError> {
Ok(hooks)
}
v => match v.span() {
Ok(span) => Err(ShellError::UnsupportedConfigValue(
v => Err(ShellError::UnsupportedConfigValue(
"record for 'hooks' config".into(),
"non-record value".into(),
span,
v.span().unwrap_or_else(|_| Span::unknown()),
)),
_ => Err(ShellError::UnsupportedConfigValue(
"record for 'hooks' config".into(),
"non-record value".into(),
Span::unknown(),
)),
},
}
}

View File

@ -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!(
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])
}
}

View File

@ -225,9 +225,10 @@ impl OverlayFrame {
}
pub fn get_decl(&self, name: &[u8], input: &Type) -> Option<DeclId> {
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()
}
}
}

View File

@ -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;

View File

@ -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,8 +634,7 @@ impl PipelineData {
*/
}
match engine_state.find_decl("table".as_bytes(), &[]) {
Some(decl_id) => {
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);
@ -652,10 +643,8 @@ impl PipelineData {
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 => {
} else {
self.write_all_and_flush(engine_state, config, no_newline, to_stderr)?;
}
};
Ok(0)

View File

@ -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<String, ShellError> {
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<Value, ShellError> {
@ -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<Value, ShellError> {
@ -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(

View File

@ -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) => {
self.stream.next().map(|buffer| {
buffer.map(|mut v| {
if !self.leftover.is_empty() {
while let Some(b) = self.leftover.pop() {
for b in self.leftover.drain(..).rev() {
v.insert(0, b);
}
}
Some(Ok(Value::Binary {
Value::Binary {
val: v,
span: self.span,
}))
}
Err(e) => Some(Err(e)),
},
None => None,
}
})
})
} 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,9 +160,8 @@ impl Iterator for RawStream {
}
}
Err(e) => Some(Err(e)),
},
None => {
if !self.leftover.is_empty() {
}
} else if !self.leftover.is_empty() {
let output = Ok(Value::Binary {
val: self.leftover.clone(),
span: self.span,
@ -180,8 +175,6 @@ impl Iterator for RawStream {
}
}
}
}
}
/// A potentially infinite stream of values, optionally with a mean to send a Ctrl-C signal to stop
/// the stream from continuing.

View File

@ -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 {

View File

@ -12,10 +12,7 @@ pub enum ProcessTask {
impl ProcessTask {
pub fn stat(&self) -> Result<Stat, ProcError> {
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<Vec<FDInfo>, 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<ProcessInfo>
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()
}
}

View File

@ -194,18 +194,6 @@ pub fn collect_proc(interval: Duration, _with_thread: bool) -> Vec<ProcessInfo>
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<String> {
fn get_cmd_line_old<T: RtlUserProcessParameters>(params: &T, handle: HANDLE) -> Vec<String> {
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<T: RtlUserProcessParameters>(params: &T, handle: HANDLE) -> Vec<
}
result
}
Err(_e) => {
// sysinfo_debug!("get_proc_env failed to get data: {}", _e);
Vec::new()
}
Err(_e) => Vec::new(),
}
}

View File

@ -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;

View File

@ -574,15 +574,14 @@ impl Peaker for PriorityMax {
fn peak(&mut self, _: &[usize], widths: &[usize]) -> Option<usize> {
let col = (0..widths.len()).rev().max_by_key(|&i| widths[i]);
match col {
Some(col) => {
if let Some(col) = col {
if widths[col] == 0 {
None
} else {
Some(col)
}
}
None => None,
} else {
None
}
}
}

View File

@ -36,9 +36,5 @@ pub fn with_locale_override<T>(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))
}

View File

@ -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()

View File

@ -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!(

View File

@ -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,
_ => {
Locale::from_name(&locale_string).unwrap_or_else(|_| {
let all = num_format::Locale::available_names();
let locale_prefix = &locale_string.split('-').collect::<Vec<&str>>();
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
}
}
}
})
}
#[cfg(debug_assertions)]

File diff suppressed because one or more lines are too long

View File

@ -22,15 +22,18 @@ impl CoolCustomValue {
pub fn try_from_value(value: &Value) -> Result<Self, ShellError> {
match value {
Value::CustomValue { val, span } => match val.as_any().downcast_ref::<Self>() {
Some(cool) => Ok(cool.clone()),
None => Err(ShellError::CantConvert(
Value::CustomValue { val, span } => {
if let Some(cool) = val.as_any().downcast_ref::<Self>() {
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(),

View File

@ -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(())

View File

@ -79,11 +79,7 @@ impl GStat {
},
});
}
let metadata = match std::fs::metadata(&a_path.item) {
Ok(md) => md,
Err(e) => {
return Err(LabeledError {
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: {}",
@ -94,9 +90,7 @@ impl GStat {
} 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) => {
self.remote = if let Ok(branch) = repo.find_branch(branch, BranchType::Local) {
// Grab the upstream from the branch
match branch.upstream() {
// Grab the name of the upstream if it's valid UTF-8
Ok(upstream) => {
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(),
if let Ok(Some(name)) = upstream.name() {
name.to_string()
} else {
String::new()
}
} else {
String::new()
}
_ => String::new(),
}
}
_ => String::new(),
} else {
String::new()
};
}

View File

@ -43,10 +43,13 @@ impl Inc {
Value::string(ver.to_string(), head)
}
Some(Action::Default) | None => match input.parse::<u64>() {
Ok(v) => Value::string((v + 1).to_string(), head),
Err(_) => Value::string(input, head),
},
Some(Action::Default) | None => {
if let Ok(v) = input.parse::<u64>() {
Value::string((v + 1).to_string(), head)
} else {
Value::string(input, head)
}
}
}
}

View File

@ -36,14 +36,10 @@ pub fn parse_selector_params(call: &EvaluatedCall, input: &Value) -> Result<Valu
None => "".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 {
match selector.attribute.is_empty() {
true => execute_selector_query(
} else if selector.attribute.is_empty() {
execute_selector_query(
input_html.as_str(),
selector.query.as_str(),
selector.as_html,
selector.inspect,
span,
),
false => execute_selector_query_with_attribute(
)
} else {
execute_selector_query_with_attribute(
input_html.as_str(),
selector.query.as_str(),
selector.attribute.as_str(),
selector.inspect,
span,
),
}
)
}
}

View File

@ -104,17 +104,18 @@ pub fn execute_xpath_query(
fn build_xpath(xpath_str: &str, span: &Span) -> Result<sxd_xpath::XPath, LabeledError> {
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),
}),
})
}
}

View File

@ -27,15 +27,12 @@ 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) => {
if let Ok(path) = canonicalize_with(&file.item, cwd) {
eval_config_contents(path, engine_state, stack);
}
Err(_) => {
} 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;

View File

@ -52,9 +52,9 @@ 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(_) => {
if let Ok(file) = File::create(path) {
WriteLogger::init(level, config, file)
} else {
let default_logger =
TermLogger::init(level, config, TerminalMode::Stderr, ColorChoice::Auto);
@ -65,7 +65,6 @@ fn set_write_logger(level: LevelFilter, config: Config, path: &Path) -> Result<(
default_logger
}
}
}
pub fn configure(
level: &str,

View File

@ -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);
}