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

View File

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

View File

@ -262,10 +262,10 @@ impl EvaluatedCommandArgs {
/// Get the nth positional argument, error if not possible
pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> {
match self.call_info.args.nth(pos) {
None => Err(ShellError::unimplemented("Better error: expect_nth")),
Some(item) => Ok(item),
}
self.call_info
.args
.nth(pos)
.ok_or_else(|| ShellError::unimplemented("Better error: expect_nth"))
}
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);
match group_strategy {
let group_value = match group_strategy {
Grouper::ByBlock => {
let map = keys.clone();
@ -179,16 +179,12 @@ pub async fn group_by(
None => as_string(row),
});
match crate::utils::data::group(&values, &Some(block), &name) {
Ok(grouped) => Ok(OutputStream::one(ReturnSuccess::value(grouped))),
Err(reason) => Err(reason),
}
crate::utils::data::group(&values, &Some(block), &name)
}
Grouper::ByColumn(column_name) => match group(&column_name, &values, name) {
Ok(grouped) => Ok(OutputStream::one(ReturnSuccess::value(grouped))),
Err(reason) => Err(reason),
},
}
Grouper::ByColumn(column_name) => group(&column_name, &values, name),
};
Ok(OutputStream::one(ReturnSuccess::value(group_value?)))
}
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))) => {
let block = Box::new(move |_, row: &Value| {
let group_key = match row.get_data_by_key(column_name.borrow_spanned()) {
Some(group_key) => Ok(group_key),
None => Err(suggestions(column_name.borrow_tagged(), &row)),
};
let group_key = row
.get_data_by_key(column_name.borrow_spanned())
.ok_or_else(|| suggestions(column_name.borrow_tagged(), &row));
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))) => {
let block = Box::new(move |_, row: &Value| {
let group_key = match row.get_data_by_key(column_name.borrow_spanned()) {
Some(group_key) => Ok(group_key),
None => Err(suggestions(column_name.borrow_tagged(), &row)),
};
let group_key = row
.get_data_by_key(column_name.borrow_spanned())
.ok_or_else(|| suggestions(column_name.borrow_tagged(), &row));
group_key?.format(&fmt)
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -40,18 +40,10 @@ impl<'a, T: Plugin> PluginTest<'a, T> {
pub fn test(&mut self) -> Result<Vec<ReturnValue>, ShellError> {
let return_values = self.plugin.filter(self.input.clone());
let mut return_values = match return_values {
Ok(filtered) => filtered,
Err(reason) => return Err(reason),
};
let mut return_values = return_values?;
let end = self.plugin.end_filter();
match end {
Ok(filter_ended) => return_values.extend(filter_ended),
Err(reason) => return Err(reason),
}
return_values.extend(end?);
self.plugin.quit();
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.
pub fn as_u64(&self, span: Span) -> Result<u64, ShellError> {
match self {
Primitive::Int(int) => match int.to_u64() {
None => Err(ShellError::range_error(
Primitive::Int(int) => int.to_u64().ok_or_else(|| {
ShellError::range_error(
ExpectedRange::U64,
&format!("{}", int).spanned(span),
"converting an integer into a 64-bit integer",
)),
Some(num) => Ok(num),
},
)
}),
other => Err(ShellError::type_error(
"integer",
other.type_name().spanned(span),
@ -102,10 +101,9 @@ impl Primitive {
};
let nanos = chrono::Duration::nanoseconds(nanos);
// This should also never fail since we are adding less than NANOS_PER_SEC.
match chrono::Duration::seconds(secs).checked_add(&nanos) {
Some(duration) => Ok(duration),
None => Err(ShellError::unexpected("Unexpected duration overflow")),
}
chrono::Duration::seconds(secs)
.checked_add(&nanos)
.ok_or_else(|| ShellError::unexpected("Unexpected duration overflow"))
}
other => Err(ShellError::type_error(
"duration",

View File

@ -352,14 +352,11 @@ pub fn swap_data_by_column_path(
let to_replace = to_replace?;
let replacement = callback(&to_replace)?;
match value.replace_data_at_column_path(&path, replacement) {
Some(replaced) => Ok(replaced),
None => Err(ShellError::labeled_error(
"missing column-path",
"missing column-path",
value.tag.span,
)),
}
value
.replace_data_at_column_path(&path, replacement)
.ok_or_else(|| {
ShellError::labeled_error("missing column-path", "missing column-path", value.tag.span)
})
}
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 replacement = self.inc(got)?;
match value
value
.replace_data_at_column_path(&f, replacement.value.into_untagged_value())
{
Some(v) => Ok(v),
None => Err(ShellError::labeled_error(
"inc could not find field to replace",
"column name",
value.tag(),
)),
}
.ok_or_else(|| {
ShellError::labeled_error(
"inc could not find field to replace",
"column name",
value.tag(),
)
})
}
None => Err(ShellError::untagged_runtime_error(
"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() {
match idx.as_ref() {
"term_width" => {
term_width = match value.as_u64() {
Ok(n) => n as usize,
_ => term_width as usize,
}
term_width = value.as_u64().unwrap_or(term_width as u64) as usize;
}
"tab_width" => {
tab_width = match value.as_u64() {
Ok(n) => n,
_ => 4u64,
}
tab_width = value.as_u64().unwrap_or(4 as u64);
}
"colored_output" => colored_output = value.as_bool().unwrap_or(true),
"true_color" => true_color = value.as_bool().unwrap_or(true),