Match cleanup (#2290)

This commit is contained in:
Joseph T. Lyons 2020-08-02 18:34:33 -04:00 committed by GitHub
parent f33da33626
commit c48ea46c4f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 102 additions and 152 deletions

View File

@ -622,17 +622,11 @@ pub fn set_rustyline_configuration() -> (Editor<Helper>, IndexMap<String, Value>
rl.set_completion_type(completion_type); rl.set_completion_type(completion_type);
} }
"completion_prompt_limit" => { "completion_prompt_limit" => {
let completion_prompt_limit = match value.as_u64() { let completion_prompt_limit = value.as_u64().unwrap_or(1) as usize;
Ok(n) => n as usize,
_ => 1 as usize,
};
rl.set_completion_prompt_limit(completion_prompt_limit); rl.set_completion_prompt_limit(completion_prompt_limit);
} }
"keyseq_timeout_ms" => { "keyseq_timeout_ms" => {
let keyseq_timeout_ms = match value.as_u64() { let keyseq_timeout_ms = value.as_u64().unwrap_or(500) as i32;
Ok(n) => n as i32,
_ => 500i32,
};
rl.set_keyseq_timeout(keyseq_timeout_ms); rl.set_keyseq_timeout(keyseq_timeout_ms);
} }
"edit_mode" => { "edit_mode" => {
@ -676,10 +670,7 @@ pub fn set_rustyline_configuration() -> (Editor<Helper>, IndexMap<String, Value>
rl.set_color_mode(color_mode); rl.set_color_mode(color_mode);
} }
"tab_stop" => { "tab_stop" => {
let tab_stop = match value.as_u64() { let tab_stop = value.as_u64().unwrap_or(4) as usize;
Ok(n) => n as usize,
_ => 4 as usize,
};
rl.set_tab_stop(tab_stop); rl.set_tab_stop(tab_stop);
} }
_ => (), _ => (),
@ -1134,18 +1125,15 @@ pub async fn process_line(
let file = futures::io::AllowStdIo::new(std::io::stdin()); let file = futures::io::AllowStdIo::new(std::io::stdin());
let stream = FramedRead::new(file, MaybeTextCodec::default()).map(|line| { let stream = FramedRead::new(file, MaybeTextCodec::default()).map(|line| {
if let Ok(line) = line { if let Ok(line) = line {
match line { let primitive = match line {
StringOrBinary::String(s) => Ok(Value { StringOrBinary::String(s) => Primitive::String(s),
value: UntaggedValue::Primitive(Primitive::String(s)), StringOrBinary::Binary(b) => Primitive::Binary(b.into_iter().collect()),
tag: Tag::unknown(), };
}),
StringOrBinary::Binary(b) => Ok(Value { Ok(Value {
value: UntaggedValue::Primitive(Primitive::Binary( value: UntaggedValue::Primitive(primitive),
b.into_iter().collect(), tag: Tag::unknown(),
)), })
tag: Tag::unknown(),
}),
}
} else { } else {
panic!("Internal error: could not read lines of text from stdin") panic!("Internal error: could not read lines of text from stdin")
} }

View File

@ -64,17 +64,15 @@ async fn benchmark(
) )
.await; .await;
let output = match result { let _ = result?.drain_vec().await;
Ok(mut stream) => { let run_duration: chrono::Duration = Utc::now().signed_duration_since(start_time);
let _ = stream.drain_vec().await;
let run_duration: chrono::Duration = Utc::now().signed_duration_since(start_time); context.clear_errors();
context.clear_errors();
Ok(ReturnSuccess::Value(Value { let output = Ok(ReturnSuccess::Value(Value {
value: UntaggedValue::Primitive(Primitive::from(run_duration)), value: UntaggedValue::Primitive(Primitive::from(run_duration)),
tag: Tag::from(block.span), tag: Tag::from(block.span),
})) }));
}
Err(e) => Err(e),
};
Ok(OutputStream::from(vec![output])) Ok(OutputStream::from(vec![output]))
} }

View File

@ -262,10 +262,10 @@ impl EvaluatedCommandArgs {
/// Get the nth positional argument, error if not possible /// Get the nth positional argument, error if not possible
pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> { pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> {
match self.call_info.args.nth(pos) { self.call_info
None => Err(ShellError::unimplemented("Better error: expect_nth")), .args
Some(item) => Ok(item), .nth(pos)
} .ok_or_else(|| ShellError::unimplemented("Better error: expect_nth"))
} }
pub fn get(&self, name: &str) -> Option<&Value> { pub fn get(&self, name: &str) -> Option<&Value> {

View File

@ -169,7 +169,7 @@ pub async fn group_by(
let values = UntaggedValue::table(&values).into_value(&name); let values = UntaggedValue::table(&values).into_value(&name);
match group_strategy { let group_value = match group_strategy {
Grouper::ByBlock => { Grouper::ByBlock => {
let map = keys.clone(); let map = keys.clone();
@ -179,16 +179,12 @@ pub async fn group_by(
None => as_string(row), None => as_string(row),
}); });
match crate::utils::data::group(&values, &Some(block), &name) { crate::utils::data::group(&values, &Some(block), &name)
Ok(grouped) => Ok(OutputStream::one(ReturnSuccess::value(grouped))),
Err(reason) => Err(reason),
}
} }
Grouper::ByColumn(column_name) => match group(&column_name, &values, name) { Grouper::ByColumn(column_name) => group(&column_name, &values, name),
Ok(grouped) => Ok(OutputStream::one(ReturnSuccess::value(grouped))), };
Err(reason) => Err(reason),
}, Ok(OutputStream::one(ReturnSuccess::value(group_value?)))
}
} }
pub fn suggestions(tried: Tagged<&str>, for_value: &Value) -> ShellError { pub fn suggestions(tried: Tagged<&str>, for_value: &Value) -> ShellError {

View File

@ -106,10 +106,9 @@ pub async fn group_by_date(
} }
(Grouper::ByDate(None), GroupByColumn::Name(Some(column_name))) => { (Grouper::ByDate(None), GroupByColumn::Name(Some(column_name))) => {
let block = Box::new(move |_, row: &Value| { let block = Box::new(move |_, row: &Value| {
let group_key = match row.get_data_by_key(column_name.borrow_spanned()) { let group_key = row
Some(group_key) => Ok(group_key), .get_data_by_key(column_name.borrow_spanned())
None => Err(suggestions(column_name.borrow_tagged(), &row)), .ok_or_else(|| suggestions(column_name.borrow_tagged(), &row));
};
group_key?.format("%Y-%b-%d") group_key?.format("%Y-%b-%d")
}); });
@ -123,10 +122,9 @@ pub async fn group_by_date(
} }
(Grouper::ByDate(Some(fmt)), GroupByColumn::Name(Some(column_name))) => { (Grouper::ByDate(Some(fmt)), GroupByColumn::Name(Some(column_name))) => {
let block = Box::new(move |_, row: &Value| { let block = Box::new(move |_, row: &Value| {
let group_key = match row.get_data_by_key(column_name.borrow_spanned()) { let group_key = row
Some(group_key) => Ok(group_key), .get_data_by_key(column_name.borrow_spanned())
None => Err(suggestions(column_name.borrow_tagged(), &row)), .ok_or_else(|| suggestions(column_name.borrow_tagged(), &row));
};
group_key?.format(&fmt) group_key?.format(&fmt)
}); });

View File

@ -106,14 +106,14 @@ async fn is_empty(
.. ..
} => { } => {
if val.is_empty() { if val.is_empty() {
match obj.replace_data_at_column_path(&field, default.clone()) { obj.replace_data_at_column_path(&field, default.clone())
Some(v) => Ok(v), .ok_or_else(|| {
None => Err(ShellError::labeled_error( ShellError::labeled_error(
"empty? could not find place to check emptiness", "empty? could not find place to check emptiness",
"column name", "column name",
&field.tag, &field.tag,
)), )
} })
} else { } else {
Ok(obj) Ok(obj)
} }

View File

@ -124,12 +124,8 @@ impl WholeStreamCommand for RunExternalCommand {
let result = external_context let result = external_context
.shell_manager .shell_manager
.cd(cd_args, args.call_info.name_tag.clone()); .cd(cd_args, args.call_info.name_tag.clone());
match result {
Ok(stream) => return Ok(stream.to_output_stream()), return Ok(result?.to_output_stream());
Err(e) => {
return Err(e);
}
}
} }
} }

View File

@ -56,10 +56,8 @@ pub async fn split_by(
)); ));
} }
match split(&column_name, &values[0], &name) { let split = split(&column_name, &values[0], &name)?;
Ok(splits) => Ok(OutputStream::one(ReturnSuccess::value(splits))), Ok(OutputStream::one(ReturnSuccess::value(split)))
Err(err) => Err(err),
}
} }
enum Grouper { enum Grouper {

View File

@ -162,17 +162,18 @@ pub fn compare_values(
use std::cmp::Ordering; use std::cmp::Ordering;
let result = match (operator, ordering) { let result = matches!(
(Operator::Equal, Ordering::Equal) => true, (operator, ordering),
(Operator::NotEqual, Ordering::Less) | (Operator::NotEqual, Ordering::Greater) => true, (Operator::Equal, Ordering::Equal)
(Operator::LessThan, Ordering::Less) => true, | (Operator::GreaterThan, Ordering::Greater)
(Operator::GreaterThan, Ordering::Greater) => true, | (Operator::GreaterThanOrEqual, Ordering::Greater)
(Operator::GreaterThanOrEqual, Ordering::Greater) | (Operator::GreaterThanOrEqual, Ordering::Equal)
| (Operator::GreaterThanOrEqual, Ordering::Equal) => true, | (Operator::LessThan, Ordering::Less)
(Operator::LessThanOrEqual, Ordering::Less) | (Operator::LessThanOrEqual, Ordering::Less)
| (Operator::LessThanOrEqual, Ordering::Equal) => true, | (Operator::LessThanOrEqual, Ordering::Equal)
_ => false, | (Operator::NotEqual, Ordering::Greater)
}; | (Operator::NotEqual, Ordering::Less)
);
Ok(result) Ok(result)
} }

View File

@ -41,7 +41,6 @@ pub(crate) async fn evaluate_args(
.await?, .await?,
); );
} }
_ => {} _ => {}
}; };
} }

View File

@ -893,27 +893,25 @@ macro_rules! ranged_int {
impl CoerceInto<$ty> for nu_source::Tagged<BigInt> { impl CoerceInto<$ty> for nu_source::Tagged<BigInt> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> { fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() { self.$op().ok_or_else(|| {
Some(v) => Ok(v), ShellError::range_error(
None => Err(ShellError::range_error(
$ty::to_expected_range(), $ty::to_expected_range(),
&self.item.spanned(self.tag.span), &self.item.spanned(self.tag.span),
operation.into(), operation.into(),
)), )
} })
} }
} }
impl CoerceInto<$ty> for nu_source::Tagged<&BigInt> { impl CoerceInto<$ty> for nu_source::Tagged<&BigInt> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> { fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() { self.$op().ok_or_else(|| {
Some(v) => Ok(v), ShellError::range_error(
None => Err(ShellError::range_error(
$ty::to_expected_range(), $ty::to_expected_range(),
&self.item.spanned(self.tag.span), &self.item.spanned(self.tag.span),
operation.into(), operation.into(),
)), )
} })
} }
} }
}; };
@ -938,27 +936,25 @@ macro_rules! ranged_decimal {
impl CoerceInto<$ty> for nu_source::Tagged<BigDecimal> { impl CoerceInto<$ty> for nu_source::Tagged<BigDecimal> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> { fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() { self.$op().ok_or_else(|| {
Some(v) => Ok(v), ShellError::range_error(
None => Err(ShellError::range_error(
$ty::to_expected_range(), $ty::to_expected_range(),
&self.item.spanned(self.tag.span), &self.item.spanned(self.tag.span),
operation.into(), operation.into(),
)), )
} })
} }
} }
impl CoerceInto<$ty> for nu_source::Tagged<&BigDecimal> { impl CoerceInto<$ty> for nu_source::Tagged<&BigDecimal> {
fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> { fn coerce_into(self, operation: impl Into<String>) -> Result<$ty, ShellError> {
match self.$op() { self.$op().ok_or_else(|| {
Some(v) => Ok(v), ShellError::range_error(
None => Err(ShellError::range_error(
$ty::to_expected_range(), $ty::to_expected_range(),
&self.item.spanned(self.tag.span), &self.item.spanned(self.tag.span),
operation.into(), operation.into(),
)), )
} })
} }
} }
}; };

View File

@ -40,18 +40,10 @@ impl<'a, T: Plugin> PluginTest<'a, T> {
pub fn test(&mut self) -> Result<Vec<ReturnValue>, ShellError> { pub fn test(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
let return_values = self.plugin.filter(self.input.clone()); let return_values = self.plugin.filter(self.input.clone());
let mut return_values = return_values?;
let mut return_values = match return_values {
Ok(filtered) => filtered,
Err(reason) => return Err(reason),
};
let end = self.plugin.end_filter(); let end = self.plugin.end_filter();
match end { return_values.extend(end?);
Ok(filter_ended) => return_values.extend(filter_ended),
Err(reason) => return Err(reason),
}
self.plugin.quit(); self.plugin.quit();
Ok(return_values) Ok(return_values)

View File

@ -65,14 +65,13 @@ impl Primitive {
/// Converts a primitive value to a u64, if possible. Uses a span to build an error if the conversion isn't possible. /// Converts a primitive value to a u64, if possible. Uses a span to build an error if the conversion isn't possible.
pub fn as_u64(&self, span: Span) -> Result<u64, ShellError> { pub fn as_u64(&self, span: Span) -> Result<u64, ShellError> {
match self { match self {
Primitive::Int(int) => match int.to_u64() { Primitive::Int(int) => int.to_u64().ok_or_else(|| {
None => Err(ShellError::range_error( ShellError::range_error(
ExpectedRange::U64, ExpectedRange::U64,
&format!("{}", int).spanned(span), &format!("{}", int).spanned(span),
"converting an integer into a 64-bit integer", "converting an integer into a 64-bit integer",
)), )
Some(num) => Ok(num), }),
},
other => Err(ShellError::type_error( other => Err(ShellError::type_error(
"integer", "integer",
other.type_name().spanned(span), other.type_name().spanned(span),
@ -102,10 +101,9 @@ impl Primitive {
}; };
let nanos = chrono::Duration::nanoseconds(nanos); let nanos = chrono::Duration::nanoseconds(nanos);
// This should also never fail since we are adding less than NANOS_PER_SEC. // This should also never fail since we are adding less than NANOS_PER_SEC.
match chrono::Duration::seconds(secs).checked_add(&nanos) { chrono::Duration::seconds(secs)
Some(duration) => Ok(duration), .checked_add(&nanos)
None => Err(ShellError::unexpected("Unexpected duration overflow")), .ok_or_else(|| ShellError::unexpected("Unexpected duration overflow"))
}
} }
other => Err(ShellError::type_error( other => Err(ShellError::type_error(
"duration", "duration",

View File

@ -352,14 +352,11 @@ pub fn swap_data_by_column_path(
let to_replace = to_replace?; let to_replace = to_replace?;
let replacement = callback(&to_replace)?; let replacement = callback(&to_replace)?;
match value.replace_data_at_column_path(&path, replacement) { value
Some(replaced) => Ok(replaced), .replace_data_at_column_path(&path, replacement)
None => Err(ShellError::labeled_error( .ok_or_else(|| {
"missing column-path", ShellError::labeled_error("missing column-path", "missing column-path", value.tag.span)
"missing column-path", })
value.tag.span,
)),
}
} }
pub fn insert_data_at_path(value: &Value, path: &str, new_value: Value) -> Option<Value> { pub fn insert_data_at_path(value: &Value, path: &str, new_value: Value) -> Option<Value> {

View File

@ -121,16 +121,15 @@ impl Inc {
let got = replace_for?; let got = replace_for?;
let replacement = self.inc(got)?; let replacement = self.inc(got)?;
match value value
.replace_data_at_column_path(&f, replacement.value.into_untagged_value()) .replace_data_at_column_path(&f, replacement.value.into_untagged_value())
{ .ok_or_else(|| {
Some(v) => Ok(v), ShellError::labeled_error(
None => Err(ShellError::labeled_error( "inc could not find field to replace",
"inc could not find field to replace", "column name",
"column name", value.tag(),
value.tag(), )
)), })
}
} }
None => Err(ShellError::untagged_runtime_error( None => Err(ShellError::untagged_runtime_error(
"inc needs a field when incrementing a column in a table", "inc needs a field when incrementing a column in a table",

View File

@ -37,16 +37,10 @@ pub fn view_text_value(value: &Value) {
for (idx, value) in batvars.row_entries() { for (idx, value) in batvars.row_entries() {
match idx.as_ref() { match idx.as_ref() {
"term_width" => { "term_width" => {
term_width = match value.as_u64() { term_width = value.as_u64().unwrap_or(term_width as u64) as usize;
Ok(n) => n as usize,
_ => term_width as usize,
}
} }
"tab_width" => { "tab_width" => {
tab_width = match value.as_u64() { tab_width = value.as_u64().unwrap_or(4 as u64);
Ok(n) => n,
_ => 4u64,
}
} }
"colored_output" => colored_output = value.as_bool().unwrap_or(true), "colored_output" => colored_output = value.as_bool().unwrap_or(true),
"true_color" => true_color = value.as_bool().unwrap_or(true), "true_color" => true_color = value.as_bool().unwrap_or(true),