Merge pull request #1061 from thibran/fix-most-clippy-warnings

Fix most Clippy performance warnings
This commit is contained in:
Jonathan Turner 2019-12-06 19:26:20 -08:00 committed by GitHub
commit 9dfb6c023f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
57 changed files with 320 additions and 350 deletions

View file

@ -38,7 +38,7 @@ impl Spanned<String> {
pub fn items<'a, U>( pub fn items<'a, U>(
items: impl Iterator<Item = &'a Spanned<String>>, items: impl Iterator<Item = &'a Spanned<String>>,
) -> impl Iterator<Item = &'a str> { ) -> impl Iterator<Item = &'a str> {
items.into_iter().map(|item| &item.item[..]) items.map(|item| &item.item[..])
} }
} }
@ -156,7 +156,7 @@ impl<T> Tagged<T> {
Tagged { Tagged {
item: self.item, item: self.item,
tag: tag, tag,
} }
} }

View file

@ -316,7 +316,7 @@ impl DebugDocBuilder {
result = result + item; result = result + item;
} }
result.into() result
} }
fn styled(string: impl std::fmt::Display, style: ShellStyle) -> DebugDocBuilder { fn styled(string: impl std::fmt::Display, style: ShellStyle) -> DebugDocBuilder {

View file

@ -38,7 +38,7 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel
let request = JsonRpc::new("config", Vec::<Value>::new()); let request = JsonRpc::new("config", Vec::<Value>::new());
let request_raw = serde_json::to_string(&request)?; let request_raw = serde_json::to_string(&request)?;
stdin.write(format!("{}\n", request_raw).as_bytes())?; stdin.write_all(format!("{}\n", request_raw).as_bytes())?;
let path = dunce::canonicalize(path)?; let path = dunce::canonicalize(path)?;
let mut input = String::new(); let mut input = String::new();
@ -58,7 +58,7 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel
let name = params.name.clone(); let name = params.name.clone();
let fname = fname.to_string(); let fname = fname.to_string();
if let Some(_) = context.get_command(&name) { if context.get_command(&name).is_some() {
trace!("plugin {:?} already loaded.", &name); trace!("plugin {:?} already loaded.", &name);
} else { } else {
if params.is_filter { if params.is_filter {
@ -222,7 +222,7 @@ impl History {
p.push(FNAME); p.push(FNAME);
p p
}) })
.unwrap_or(PathBuf::from(FNAME)) .unwrap_or_else(|_| PathBuf::from(FNAME))
} }
} }
@ -609,8 +609,8 @@ fn classify_pipeline(
context: &Context, context: &Context,
source: &Text, source: &Text,
) -> Result<ClassifiedPipeline, ShellError> { ) -> Result<ClassifiedPipeline, ShellError> {
let mut pipeline_list = vec![pipeline.clone()]; let pipeline_list = vec![pipeline.clone()];
let mut iterator = TokensIterator::all(&mut pipeline_list, source.clone(), pipeline.span()); let mut iterator = TokensIterator::all(&pipeline_list, source.clone(), pipeline.span());
let result = expand_syntax( let result = expand_syntax(
&PipelineShape, &PipelineShape,

View file

@ -68,7 +68,7 @@ pub(crate) async fn run_external_command(
trace!(target: "nu::run::external", "-> {}", command.name); trace!(target: "nu::run::external", "-> {}", command.name);
trace!(target: "nu::run::external", "inputs = {:?}", inputs); trace!(target: "nu::run::external", "inputs = {:?}", inputs);
let mut arg_string = format!("{}", command.name); let mut arg_string = command.name.to_owned();
for arg in command.args.iter() { for arg in command.args.iter() {
arg_string.push_str(&arg); arg_string.push_str(&arg);
} }
@ -170,11 +170,11 @@ pub(crate) async fn run_external_command(
if let Ok(mut popen) = popen { if let Ok(mut popen) = popen {
match stream_next { match stream_next {
StreamNext::Last => { StreamNext::Last => {
let _ = popen.detach(); popen.detach();
loop { loop {
match popen.poll() { match popen.poll() {
None => { None => {
let _ = std::thread::sleep(std::time::Duration::new(0, 100000000)); std::thread::sleep(std::time::Duration::new(0, 100_000_000));
} }
_ => { _ => {
let _ = popen.terminate(); let _ = popen.terminate();
@ -185,12 +185,12 @@ pub(crate) async fn run_external_command(
Ok(ClassifiedInputStream::new()) Ok(ClassifiedInputStream::new())
} }
StreamNext::External => { StreamNext::External => {
let _ = popen.detach(); popen.detach();
let stdout = popen.stdout.take().unwrap(); let stdout = popen.stdout.take().unwrap();
Ok(ClassifiedInputStream::from_stdout(stdout)) Ok(ClassifiedInputStream::from_stdout(stdout))
} }
StreamNext::Internal => { StreamNext::Internal => {
let _ = popen.detach(); popen.detach();
let stdout = popen.stdout.take().unwrap(); let stdout = popen.stdout.take().unwrap();
let file = futures::io::AllowStdIo::new(stdout); let file = futures::io::AllowStdIo::new(stdout);
let stream = Framed::new(file, LinesCodec {}); let stream = Framed::new(file, LinesCodec {});
@ -201,10 +201,10 @@ pub(crate) async fn run_external_command(
} }
} }
} else { } else {
return Err(ShellError::labeled_error( Err(ShellError::labeled_error(
"Command not found", "Command not found",
"command not found", "command not found",
name_tag, name_tag,
)); ))
} }
} }

View file

@ -566,7 +566,7 @@ impl WholeStreamCommand for FnFilterCommand {
); );
match func(args) { match func(args) {
Err(err) => return OutputStream::from(vec![Err(err)]).values, Err(err) => OutputStream::from(vec![Err(err)]).values,
Ok(stream) => stream.values, Ok(stream) => stream.values,
} }
}); });

View file

@ -47,7 +47,7 @@ impl PerItemCommand for Enter {
let tag_clone = tag.clone(); let tag_clone = tag.clone();
if location.starts_with("help") { if location.starts_with("help") {
let spec = location_string.split(":").collect::<Vec<&str>>(); let spec = location_string.split(':').collect::<Vec<&str>>();
let (_, command) = (spec[0], spec[1]); let (_, command) = (spec[0], spec[1]);

View file

@ -94,7 +94,7 @@ pub fn evaluate(
.. ..
} => { } => {
let datasets: Vec<_> = datasets let datasets: Vec<_> = datasets
.into_iter() .iter()
.map(|subsets| match subsets { .map(|subsets| match subsets {
Value { Value {
value: UntaggedValue::Table(subsets), value: UntaggedValue::Table(subsets),

View file

@ -129,7 +129,7 @@ pub async fn fetch(
location: &str, location: &str,
span: Span, span: Span,
) -> Result<(Option<String>, UntaggedValue, Tag), ShellError> { ) -> Result<(Option<String>, UntaggedValue, Tag), ShellError> {
if let Err(_) = url::Url::parse(location) { if url::Url::parse(location).is_err() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"Incomplete or incorrect url", "Incomplete or incorrect url",
"expected a full url", "expected a full url",
@ -275,19 +275,17 @@ pub async fn fetch(
} }
None => Ok(( None => Ok((
None, None,
UntaggedValue::string(format!("No content type found")), UntaggedValue::string("No content type found".to_owned()),
Tag { Tag {
span, span,
anchor: Some(AnchorLocation::Url(location.to_string())), anchor: Some(AnchorLocation::Url(location.to_string())),
}, },
)), )),
}, },
Err(_) => { Err(_) => Err(ShellError::labeled_error(
return Err(ShellError::labeled_error( "URL could not be opened",
"URL could not be opened", "url not found",
"url not found", span,
span, )),
));
}
} }
} }

View file

@ -30,7 +30,7 @@ impl WholeStreamCommand for FromBSON {
} }
} }
fn bson_array(input: &Vec<Bson>, tag: Tag) -> Result<Vec<Value>, ShellError> { fn bson_array(input: &[Bson], tag: Tag) -> Result<Vec<Value>, ShellError> {
let mut out = vec![]; let mut out = vec![];
for value in input { for value in input {
@ -81,7 +81,7 @@ fn convert_bson_value_to_nu_value(v: &Bson, tag: impl Into<Tag>) -> Result<Value
ShellError::range_error( ShellError::range_error(
ExpectedRange::BigDecimal, ExpectedRange::BigDecimal,
&n.spanned(span), &n.spanned(span),
format!("converting BSON Decimal128 to BigDecimal"), "converting BSON Decimal128 to BigDecimal".to_owned(),
) )
})?; })?;
UntaggedValue::Primitive(Primitive::Decimal(decimal)).into_value(&tag) UntaggedValue::Primitive(Primitive::Decimal(decimal)).into_value(&tag)

View file

@ -31,7 +31,7 @@ impl WholeStreamCommand for FromINI {
fn convert_ini_second_to_nu_value(v: &HashMap<String, String>, tag: impl Into<Tag>) -> Value { fn convert_ini_second_to_nu_value(v: &HashMap<String, String>, tag: impl Into<Tag>) -> Value {
let mut second = TaggedDictBuilder::new(tag); let mut second = TaggedDictBuilder::new(tag);
for (key, value) in v.into_iter() { for (key, value) in v.iter() {
second.insert_untagged(key.clone(), Primitive::String(value.clone())); second.insert_untagged(key.clone(), Primitive::String(value.clone()));
} }

View file

@ -97,7 +97,7 @@ fn convert_sqlite_row_to_nu_value(
convert_sqlite_value_to_nu_value(row.get_raw(i), tag.clone()), convert_sqlite_value_to_nu_value(row.get_raw(i), tag.clone()),
); );
} }
return Ok(collected.into_value()); Ok(collected.into_value())
} }
fn convert_sqlite_value_to_nu_value(value: ValueRef, tag: impl Into<Tag> + Clone) -> Value { fn convert_sqlite_value_to_nu_value(value: ValueRef, tag: impl Into<Tag> + Clone) -> Value {

View file

@ -45,11 +45,7 @@ fn from_node_to_value<'a, 'd>(n: &roxmltree::Node<'a, 'd>, tag: impl Into<Tag>)
value: UntaggedValue::Primitive(Primitive::String(f)), value: UntaggedValue::Primitive(Primitive::String(f)),
.. ..
} => { } => {
if f.trim() == "" { !f.trim().is_empty() // non-whitespace characters?
false
} else {
true
}
} }
_ => true, _ => true,
}) })

View file

@ -70,7 +70,7 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellErr
), ),
column_path_tried.span, column_path_tried.span,
if total == 1 { if total == 1 {
format!("The table only has 1 row") "The table only has 1 row".to_owned()
} else { } else {
format!("The table only has {} rows (0 to {})", total, total - 1) format!("The table only has {} rows (0 to {})", total, total - 1)
}, },
@ -91,7 +91,7 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellErr
None => {} None => {}
} }
return error; error
}), }),
) )
} }
@ -100,7 +100,7 @@ pub fn get(
GetArgs { rest: mut fields }: GetArgs, GetArgs { rest: mut fields }: GetArgs,
RunnableContext { input, .. }: RunnableContext, RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
if fields.len() == 0 { if fields.is_empty() {
let stream = async_stream! { let stream = async_stream! {
let values = input.values; let values = input.values;
pin_mut!(values); pin_mut!(values);

View file

@ -84,7 +84,7 @@ pub fn group(
possible_matches.sort(); possible_matches.sort();
if possible_matches.len() > 0 { if !possible_matches.is_empty() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"Unknown column", "Unknown column",
format!("did you mean '{}'?", possible_matches[0].1), format!("did you mean '{}'?", possible_matches[0].1),

View file

@ -82,16 +82,16 @@ impl PerItemCommand for Help {
} }
if signature.rest_positional.is_some() { if signature.rest_positional.is_some() {
one_liner.push_str(&format!(" ...args",)); one_liner.push_str(" ...args");
} }
if signature.named.len() > 0 { if !signature.named.is_empty() {
one_liner.push_str("{flags} "); one_liner.push_str("{flags} ");
} }
long_desc.push_str(&format!("\nUsage:\n > {}\n", one_liner)); long_desc.push_str(&format!("\nUsage:\n > {}\n", one_liner));
if signature.positional.len() > 0 || signature.rest_positional.is_some() { if !signature.positional.is_empty() || signature.rest_positional.is_some() {
long_desc.push_str("\nparameters:\n"); long_desc.push_str("\nparameters:\n");
for positional in signature.positional { for positional in signature.positional {
match positional.0 { match positional.0 {
@ -117,7 +117,7 @@ impl PerItemCommand for Help {
)); ));
} }
} }
if signature.named.len() > 0 { if !signature.named.is_empty() {
long_desc.push_str("\nflags:\n"); long_desc.push_str("\nflags:\n");
for (flag, ty) in signature.named { for (flag, ty) in signature.named {
match ty.0 { match ty.0 {
@ -125,7 +125,7 @@ impl PerItemCommand for Help {
long_desc.push_str(&format!( long_desc.push_str(&format!(
" --{}{} {}\n", " --{}{} {}\n",
flag, flag,
if ty.1.len() > 0 { ":" } else { "" }, if !ty.1.is_empty() { ":" } else { "" },
ty.1 ty.1
)); ));
} }
@ -134,7 +134,7 @@ impl PerItemCommand for Help {
" --{} <{}> (required parameter){} {}\n", " --{} <{}> (required parameter){} {}\n",
flag, flag,
m.display(), m.display(),
if ty.1.len() > 0 { ":" } else { "" }, if !ty.1.is_empty() { ":" } else { "" },
ty.1 ty.1
)); ));
} }
@ -143,7 +143,7 @@ impl PerItemCommand for Help {
" --{} <{}>{} {}\n", " --{} <{}>{} {}\n",
flag, flag,
o.display(), o.display(),
if ty.1.len() > 0 { ":" } else { "" }, if !ty.1.is_empty() { ":" } else { "" },
ty.1 ty.1
)); ));
} }

View file

@ -88,7 +88,7 @@ pub fn histogram(
let column = (*column_name).clone(); let column = (*column_name).clone();
if let Value { value: UntaggedValue::Table(start), .. } = datasets.get(0).unwrap() { if let Value { value: UntaggedValue::Table(start), .. } = datasets.get(0).unwrap() {
for percentage in start.into_iter() { for percentage in start.iter() {
let mut fact = TaggedDictBuilder::new(&name); let mut fact = TaggedDictBuilder::new(&name);
let value: Tagged<String> = group_labels.get(idx).unwrap().clone(); let value: Tagged<String> = group_labels.get(idx).unwrap().clone();
@ -99,7 +99,7 @@ pub fn histogram(
fact.insert_untagged(&frequency_column_name, UntaggedValue::string(string)); fact.insert_untagged(&frequency_column_name, UntaggedValue::string(string));
} }
idx = idx + 1; idx += 1;
yield ReturnSuccess::value(fact.into_value()); yield ReturnSuccess::value(fact.into_value());
} }
@ -121,14 +121,14 @@ fn percentages(values: &Value, max: Value, tag: impl Into<Tag>) -> Result<Value,
.. ..
} => { } => {
let datasets: Vec<_> = datasets let datasets: Vec<_> = datasets
.into_iter() .iter()
.map(|subsets| match subsets { .map(|subsets| match subsets {
Value { Value {
value: UntaggedValue::Table(data), value: UntaggedValue::Table(data),
.. ..
} => { } => {
let data = let data =
data.into_iter() data.iter()
.map(|d| match d { .map(|d| match d {
Value { Value {
value: UntaggedValue::Primitive(Primitive::Int(n)), value: UntaggedValue::Primitive(Primitive::Int(n)),

View file

@ -84,13 +84,13 @@ pub fn map_max(
.. ..
} => { } => {
let datasets: Vec<_> = datasets let datasets: Vec<_> = datasets
.into_iter() .iter()
.map(|subsets| match subsets { .map(|subsets| match subsets {
Value { Value {
value: UntaggedValue::Table(data), value: UntaggedValue::Table(data),
.. ..
} => { } => {
let data = data.into_iter().fold(0, |acc, value| match value { let data = data.iter().fold(0, |acc, value| match value {
Value { Value {
value: UntaggedValue::Primitive(Primitive::Int(n)), value: UntaggedValue::Primitive(Primitive::Int(n)),
.. ..

View file

@ -44,7 +44,7 @@ fn run(
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let shell_manager = &raw_args.shell_manager; let shell_manager = &raw_args.shell_manager;
let cwd = PathBuf::from(shell_manager.path()); let cwd = PathBuf::from(shell_manager.path());
let full_path = PathBuf::from(cwd); let full_path = cwd;
let path = call_info.args.nth(0).ok_or_else(|| { let path = call_info.args.nth(0).ok_or_else(|| {
ShellError::labeled_error( ShellError::labeled_error(
@ -243,20 +243,18 @@ pub async fn fetch(
} }
} }
}, },
Err(_) => { Err(_) => Err(ShellError::labeled_error(
return Err(ShellError::labeled_error( "File could not be opened",
"File could not be opened", "file not found",
"file not found", span,
span, )),
));
}
} }
} else { } else {
return Err(ShellError::labeled_error( Err(ShellError::labeled_error(
"File could not be opened", "File could not be opened",
"file not found", "file not found",
span, span,
)); ))
} }
} }

View file

@ -39,7 +39,7 @@ fn pick(
PickArgs { rest: fields }: PickArgs, PickArgs { rest: fields }: PickArgs,
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
if fields.len() == 0 { if fields.is_empty() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"Pick requires columns to pick", "Pick requires columns to pick",
"needs parameter", "needs parameter",

View file

@ -92,7 +92,7 @@ pub fn pivot(args: PivotArgs, context: RunnableContext) -> Result<OutputStream,
} }
} }
} else { } else {
for i in 0..input.len()+1 { for i in 0..=input.len() {
if let Some(name) = args.rest.get(i) { if let Some(name) = args.rest.get(i) {
headers.push(name.to_string()) headers.push(name.to_string())
} else { } else {

View file

@ -214,7 +214,7 @@ pub async fn post(
body: &Value, body: &Value,
user: Option<String>, user: Option<String>,
password: Option<String>, password: Option<String>,
headers: &Vec<HeaderKind>, headers: &[HeaderKind],
tag: Tag, tag: Tag,
registry: &CommandRegistry, registry: &CommandRegistry,
raw_args: &RawCommandArgs, raw_args: &RawCommandArgs,
@ -435,20 +435,18 @@ pub async fn post(
} }
None => Ok(( None => Ok((
None, None,
UntaggedValue::string(format!("No content type found")), UntaggedValue::string("No content type found".to_owned()),
Tag { Tag {
anchor: Some(AnchorLocation::Url(location.to_string())), anchor: Some(AnchorLocation::Url(location.to_string())),
span: tag.span, span: tag.span,
}, },
)), )),
}, },
Err(_) => { Err(_) => Err(ShellError::labeled_error(
return Err(ShellError::labeled_error( "URL could not be opened",
"URL could not be opened", "url not found",
"url not found", tag,
tag, )),
));
}
} }
} else { } else {
Err(ShellError::labeled_error( Err(ShellError::labeled_error(

View file

@ -42,7 +42,7 @@ fn range(
RangeArgs { area: rows }: RangeArgs, RangeArgs { area: rows }: RangeArgs,
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
match rows.item.find(".") { match rows.item.find('.') {
Some(value) => { Some(value) => {
let (first, last) = rows.item.split_at(value); let (first, last) = rows.item.split_at(value);
let first = match first.parse::<u64>() { let first = match first.parse::<u64>() {
@ -59,7 +59,7 @@ fn range(
} }
} }
}; };
let last = match last.trim_start_matches(".").parse::<u64>() { let last = match last.trim_start_matches('.').parse::<u64>() {
Ok(postion) => postion, Ok(postion) => postion,
Err(_) => { Err(_) => {
if last == ".." { if last == ".." {
@ -73,16 +73,14 @@ fn range(
} }
} }
}; };
return Ok(OutputStream::from_input( Ok(OutputStream::from_input(
input.values.skip(first).take(last - first + 1), input.values.skip(first).take(last - first + 1),
)); ))
}
None => {
return Err(ShellError::labeled_error(
"No correct formatted range found",
"format: <from>..<to>",
name,
));
} }
None => Err(ShellError::labeled_error(
"No correct formatted range found",
"format: <from>..<to>",
name,
)),
} }
} }

View file

@ -118,7 +118,7 @@ pub fn reduce(
.. ..
} => { } => {
let datasets: Vec<_> = datasets let datasets: Vec<_> = datasets
.into_iter() .iter()
.map(|subsets| { .map(|subsets| {
let mut acc = 0; let mut acc = 0;
match subsets { match subsets {
@ -127,7 +127,7 @@ pub fn reduce(
.. ..
} => { } => {
let data = data let data = data
.into_iter() .iter()
.map(|d| { .map(|d| {
if let Value { if let Value {
value: UntaggedValue::Table(x), value: UntaggedValue::Table(x),

View file

@ -38,7 +38,7 @@ fn reject(
RejectArgs { rest: fields }: RejectArgs, RejectArgs { rest: fields }: RejectArgs,
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
if fields.len() == 0 { if fields.is_empty() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"Reject requires fields", "Reject requires fields",
"needs parameter", "needs parameter",

View file

@ -226,10 +226,10 @@ fn save(
Ok(OutputStream::new(stream)) Ok(OutputStream::new(stream))
} }
fn string_from(input: &Vec<Value>) -> String { fn string_from(input: &[Value]) -> String {
let mut save_data = String::new(); let mut save_data = String::new();
if input.len() > 0 { if !input.is_empty() {
let mut first = true; let mut first = true;
for i in input.iter() { for i in input.iter() {
if !first { if !first {

View file

@ -74,7 +74,7 @@ fn split_column(
let positional: Vec<_> = rest.iter().map(|f| f.item.clone()).collect(); let positional: Vec<_> = rest.iter().map(|f| f.item.clone()).collect();
// If they didn't provide column names, make up our own // If they didn't provide column names, make up our own
if positional.len() == 0 { if positional.is_empty() {
let mut gen_columns = vec![]; let mut gen_columns = vec![];
for i in 0..split_result.len() { for i in 0..split_result.len() {
gen_columns.push(format!("Column{}", i + 1)); gen_columns.push(format!("Column{}", i + 1));
@ -85,15 +85,6 @@ fn split_column(
dict.insert_untagged(v.clone(), Primitive::String(k.into())); dict.insert_untagged(v.clone(), Primitive::String(k.into()));
} }
ReturnSuccess::value(dict.into_value())
} else if split_result.len() == positional.len() {
let mut dict = TaggedDictBuilder::new(&v.tag);
for (&k, v) in split_result.iter().zip(positional.iter()) {
dict.insert_untagged(
v,
UntaggedValue::Primitive(Primitive::String(k.into())),
);
}
ReturnSuccess::value(dict.into_value()) ReturnSuccess::value(dict.into_value())
} else { } else {
let mut dict = TaggedDictBuilder::new(&v.tag); let mut dict = TaggedDictBuilder::new(&v.tag);

View file

@ -128,7 +128,7 @@ pub fn columns_sorted(
keys.into_iter().map(|k| k.tagged(&origin_tag)).collect() keys.into_iter().map(|k| k.tagged(&origin_tag)).collect()
} }
_ => vec![format!("default").tagged(&origin_tag)], _ => vec!["default".to_owned().tagged(&origin_tag)],
} }
} }
@ -197,12 +197,12 @@ pub fn t_sort(
outer.push_value(UntaggedValue::Table(i).into_value(&origin_tag)); outer.push_value(UntaggedValue::Table(i).into_value(&origin_tag));
} }
return Ok(UntaggedValue::Table(outer.list).into_value(&origin_tag)); Ok(UntaggedValue::Table(outer.list).into_value(&origin_tag))
} }
Some(_) => return Ok(UntaggedValue::nothing().into_value(&origin_tag)), Some(_) => Ok(UntaggedValue::nothing().into_value(&origin_tag)),
} }
} }
None => return Ok(UntaggedValue::nothing().into_value(&origin_tag)), None => Ok(UntaggedValue::nothing().into_value(&origin_tag)),
} }
} }
#[cfg(test)] #[cfg(test)]

View file

@ -94,10 +94,9 @@ fn object_value_to_bson(o: &Dictionary) -> Result<Bson, ShellError> {
Some((options, tagged_opts_value)) if options == "$options" => { Some((options, tagged_opts_value)) if options == "$options" => {
let r: Result<String, _> = tagged_regex_value.try_into(); let r: Result<String, _> = tagged_regex_value.try_into();
let opts: Result<String, _> = tagged_opts_value.try_into(); let opts: Result<String, _> = tagged_opts_value.try_into();
if r.is_err() || opts.is_err() { match (r, opts) {
generic_object_value_to_bson(o) (Ok(r), Ok(opts)) => Ok(Bson::RegExp(r, opts)),
} else { _ => generic_object_value_to_bson(o),
Ok(Bson::RegExp(r.unwrap(), opts.unwrap()))
} }
} }
_ => generic_object_value_to_bson(o), _ => generic_object_value_to_bson(o),
@ -107,14 +106,16 @@ fn object_value_to_bson(o: &Dictionary) -> Result<Bson, ShellError> {
Some((scope, tagged_scope_value)) if scope == "$scope" => { Some((scope, tagged_scope_value)) if scope == "$scope" => {
let js: Result<String, _> = tagged_javascript_value.try_into(); let js: Result<String, _> = tagged_javascript_value.try_into();
let s: Result<&Dictionary, _> = tagged_scope_value.try_into(); let s: Result<&Dictionary, _> = tagged_scope_value.try_into();
if js.is_err() || s.is_err() {
generic_object_value_to_bson(o) match (js, s) {
} else { (Ok(js), Ok(s)) => {
if let Bson::Document(doc) = object_value_to_bson(s.unwrap())? { if let Bson::Document(doc) = object_value_to_bson(s)? {
Ok(Bson::JavaScriptCodeWithScope(js.unwrap(), doc)) Ok(Bson::JavaScriptCodeWithScope(js, doc))
} else { } else {
generic_object_value_to_bson(o) generic_object_value_to_bson(o)
}
} }
_ => generic_object_value_to_bson(o),
} }
} }
None => { None => {
@ -130,10 +131,10 @@ fn object_value_to_bson(o: &Dictionary) -> Result<Bson, ShellError> {
} }
Some((timestamp, tagged_timestamp_value)) if timestamp == "$timestamp" => { Some((timestamp, tagged_timestamp_value)) if timestamp == "$timestamp" => {
let ts: Result<i64, _> = tagged_timestamp_value.try_into(); let ts: Result<i64, _> = tagged_timestamp_value.try_into();
if ts.is_err() { if let Ok(ts) = ts {
generic_object_value_to_bson(o) Ok(Bson::TimeStamp(ts))
} else { } else {
Ok(Bson::TimeStamp(ts.unwrap())) generic_object_value_to_bson(o)
} }
} }
Some((binary_subtype, tagged_binary_subtype_value)) Some((binary_subtype, tagged_binary_subtype_value))
@ -154,30 +155,32 @@ fn object_value_to_bson(o: &Dictionary) -> Result<Bson, ShellError> {
} }
Some((object_id, tagged_object_id_value)) if object_id == "$object_id" => { Some((object_id, tagged_object_id_value)) if object_id == "$object_id" => {
let obj_id: Result<String, _> = tagged_object_id_value.try_into(); let obj_id: Result<String, _> = tagged_object_id_value.try_into();
if obj_id.is_err() {
generic_object_value_to_bson(o) if let Ok(obj_id) = obj_id {
} else { let obj_id = ObjectId::with_string(&obj_id);
let obj_id = ObjectId::with_string(&obj_id.unwrap());
if obj_id.is_err() { if let Ok(obj_id) = obj_id {
generic_object_value_to_bson(o) Ok(Bson::ObjectId(obj_id))
} else { } else {
Ok(Bson::ObjectId(obj_id.unwrap())) generic_object_value_to_bson(o)
} }
} else {
generic_object_value_to_bson(o)
} }
} }
Some((symbol, tagged_symbol_value)) if symbol == "$symbol" => { Some((symbol, tagged_symbol_value)) if symbol == "$symbol" => {
let sym: Result<String, _> = tagged_symbol_value.try_into(); let sym: Result<String, _> = tagged_symbol_value.try_into();
if sym.is_err() { if let Ok(sym) = sym {
generic_object_value_to_bson(o) Ok(Bson::Symbol(sym))
} else { } else {
Ok(Bson::Symbol(sym.unwrap())) generic_object_value_to_bson(o)
} }
} }
_ => generic_object_value_to_bson(o), _ => generic_object_value_to_bson(o),
} }
} }
fn get_binary_subtype<'a>(tagged_value: &'a Value) -> Result<BinarySubtype, ShellError> { fn get_binary_subtype(tagged_value: &Value) -> Result<BinarySubtype, ShellError> {
match &tagged_value.value { match &tagged_value.value {
UntaggedValue::Primitive(Primitive::String(s)) => Ok(match s.as_ref() { UntaggedValue::Primitive(Primitive::String(s)) => Ok(match s.as_ref() {
"generic" => BinarySubtype::Generic, "generic" => BinarySubtype::Generic,

View file

@ -29,7 +29,7 @@ fn from_value_to_delimited_string(
wtr.write_record(fields).expect("can not write."); wtr.write_record(fields).expect("can not write.");
wtr.write_record(values).expect("can not write."); wtr.write_record(values).expect("can not write.");
return Ok(String::from_utf8(wtr.into_inner().map_err(|_| { let v = String::from_utf8(wtr.into_inner().map_err(|_| {
ShellError::labeled_error( ShellError::labeled_error(
"Could not convert record", "Could not convert record",
"original value", "original value",
@ -42,7 +42,8 @@ fn from_value_to_delimited_string(
"original value", "original value",
&tagged_value.tag, &tagged_value.tag,
) )
})?); })?;
Ok(v)
} }
UntaggedValue::Table(list) => { UntaggedValue::Table(list) => {
let mut wtr = WriterBuilder::new() let mut wtr = WriterBuilder::new()
@ -68,8 +69,7 @@ fn from_value_to_delimited_string(
} }
wtr.write_record(&row).expect("can not write"); wtr.write_record(&row).expect("can not write");
} }
let v = String::from_utf8(wtr.into_inner().map_err(|_| {
return Ok(String::from_utf8(wtr.into_inner().map_err(|_| {
ShellError::labeled_error( ShellError::labeled_error(
"Could not convert record", "Could not convert record",
"original value", "original value",
@ -82,9 +82,10 @@ fn from_value_to_delimited_string(
"original value", "original value",
&tagged_value.tag, &tagged_value.tag,
) )
})?); })?;
Ok(v)
} }
_ => return to_string_tagged_value(tagged_value), _ => to_string_tagged_value(tagged_value),
} }
} }
@ -98,7 +99,7 @@ pub fn clone_tagged_value(v: &Value) -> Value {
UntaggedValue::Primitive(Primitive::Nothing) UntaggedValue::Primitive(Primitive::Nothing)
} }
UntaggedValue::Primitive(Primitive::Boolean(b)) => { UntaggedValue::Primitive(Primitive::Boolean(b)) => {
UntaggedValue::Primitive(Primitive::Boolean(b.clone())) UntaggedValue::Primitive(Primitive::Boolean(*b))
} }
UntaggedValue::Primitive(Primitive::Decimal(f)) => { UntaggedValue::Primitive(Primitive::Decimal(f)) => {
UntaggedValue::Primitive(Primitive::Decimal(f.clone())) UntaggedValue::Primitive(Primitive::Decimal(f.clone()))
@ -110,10 +111,10 @@ pub fn clone_tagged_value(v: &Value) -> Value {
UntaggedValue::Primitive(Primitive::Path(x.clone())) UntaggedValue::Primitive(Primitive::Path(x.clone()))
} }
UntaggedValue::Primitive(Primitive::Bytes(b)) => { UntaggedValue::Primitive(Primitive::Bytes(b)) => {
UntaggedValue::Primitive(Primitive::Bytes(b.clone())) UntaggedValue::Primitive(Primitive::Bytes(*b))
} }
UntaggedValue::Primitive(Primitive::Date(d)) => { UntaggedValue::Primitive(Primitive::Date(d)) => {
UntaggedValue::Primitive(Primitive::Date(d.clone())) UntaggedValue::Primitive(Primitive::Date(*d))
} }
UntaggedValue::Row(o) => UntaggedValue::Row(o.clone()), UntaggedValue::Row(o) => UntaggedValue::Row(o.clone()),
UntaggedValue::Table(l) => UntaggedValue::Table(l.clone()), UntaggedValue::Table(l) => UntaggedValue::Table(l.clone()),
@ -135,17 +136,15 @@ fn to_string_tagged_value(v: &Value) -> Result<String, ShellError> {
UntaggedValue::Primitive(Primitive::Decimal(_)) => Ok(v.as_string()?.to_string()), UntaggedValue::Primitive(Primitive::Decimal(_)) => Ok(v.as_string()?.to_string()),
UntaggedValue::Primitive(Primitive::Int(_)) => Ok(v.as_string()?.to_string()), UntaggedValue::Primitive(Primitive::Int(_)) => Ok(v.as_string()?.to_string()),
UntaggedValue::Primitive(Primitive::Path(_)) => Ok(v.as_string()?.to_string()), UntaggedValue::Primitive(Primitive::Path(_)) => Ok(v.as_string()?.to_string()),
UntaggedValue::Table(_) => return Ok(String::from("[Table]")), UntaggedValue::Table(_) => Ok(String::from("[Table]")),
UntaggedValue::Row(_) => return Ok(String::from("[Row]")), UntaggedValue::Row(_) => Ok(String::from("[Row]")),
UntaggedValue::Primitive(Primitive::Line(s)) => return Ok(s.to_string()), UntaggedValue::Primitive(Primitive::Line(s)) => Ok(s.to_string()),
UntaggedValue::Primitive(Primitive::String(s)) => return Ok(s.to_string()), UntaggedValue::Primitive(Primitive::String(s)) => Ok(s.to_string()),
_ => { _ => Err(ShellError::labeled_error(
return Err(ShellError::labeled_error( "Unexpected value",
"Unexpected value", "",
"", v.tag.clone(),
v.tag.clone(), )),
))
}
} }
} }

View file

@ -94,7 +94,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
}) })
} }
fn json_list(input: &Vec<Value>) -> Result<Vec<serde_json::Value>, ShellError> { fn json_list(input: &[Value]) -> Result<Vec<serde_json::Value>, ShellError> {
let mut out = vec![]; let mut out = vec![];
for value in input { for value in input {

View file

@ -70,7 +70,7 @@ fn comma_concat(acc: String, current: String) -> String {
} }
} }
fn get_columns(rows: &Vec<Value>) -> Result<String, std::io::Error> { fn get_columns(rows: &[Value]) -> Result<String, std::io::Error> {
match &rows[0].value { match &rows[0].value {
UntaggedValue::Row(d) => Ok(d UntaggedValue::Row(d) => Ok(d
.entries .entries

View file

@ -82,7 +82,7 @@ pub fn value_to_toml_value(v: &Value) -> Result<toml::Value, ShellError> {
}) })
} }
fn collect_values(input: &Vec<Value>) -> Result<Vec<toml::Value>, ShellError> { fn collect_values(input: &[Value]) -> Result<Vec<toml::Value>, ShellError> {
let mut out = vec![]; let mut out = vec![];
for value in input { for value in input {

View file

@ -38,7 +38,7 @@ pub fn which(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
let tag = args.call_info.name_tag.clone(); let tag = args.call_info.name_tag.clone();
if let Some(v) = &args.call_info.args.positional { if let Some(v) = &args.call_info.args.positional {
if v.len() > 0 { if !v.is_empty() {
match &v[0] { match &v[0] {
Value { Value {
value: UntaggedValue::Primitive(Primitive::String(s)), value: UntaggedValue::Primitive(Primitive::String(s)),

View file

@ -45,7 +45,7 @@ impl CommandRegistry {
pub(crate) fn get_command(&self, name: &str) -> Option<Arc<Command>> { pub(crate) fn get_command(&self, name: &str) -> Option<Arc<Command>> {
let registry = self.registry.lock().unwrap(); let registry = self.registry.lock().unwrap();
registry.get(name).map(|c| c.clone()) registry.get(name).cloned()
} }
pub(crate) fn expect_command(&self, name: &str) -> Arc<Command> { pub(crate) fn expect_command(&self, name: &str) -> Arc<Command> {
@ -175,7 +175,7 @@ impl Context {
self.registry.expect_command(name) self.registry.expect_command(name)
} }
pub(crate) fn run_command<'a>( pub(crate) fn run_command(
&mut self, &mut self,
command: Arc<Command>, command: Arc<Command>,
name_tag: Tag, name_tag: Tag,

View file

@ -40,7 +40,7 @@ interfaces!(Block: dyn ObjectHash);
#[typetag::serde] #[typetag::serde]
impl EvaluateTrait for Block { impl EvaluateTrait for Block {
fn invoke(&self, scope: &Scope) -> Result<Value, ShellError> { fn invoke(&self, scope: &Scope) -> Result<Value, ShellError> {
if self.expressions.len() == 0 { if self.expressions.is_empty() {
return Ok(UntaggedValue::nothing().into_value(&self.tag)); return Ok(UntaggedValue::nothing().into_value(&self.tag));
} }
@ -189,8 +189,8 @@ fn coerce_compare_primitive(
(Line(left), String(right)) => CompareValues::String(left.clone(), right.clone()), (Line(left), String(right)) => CompareValues::String(left.clone(), right.clone()),
(String(left), Line(right)) => CompareValues::String(left.clone(), right.clone()), (String(left), Line(right)) => CompareValues::String(left.clone(), right.clone()),
(Line(left), Line(right)) => CompareValues::String(left.clone(), right.clone()), (Line(left), Line(right)) => CompareValues::String(left.clone(), right.clone()),
(Date(left), Date(right)) => CompareValues::Date(left.clone(), right.clone()), (Date(left), Date(right)) => CompareValues::Date(*left, *right),
(Date(left), Duration(right)) => CompareValues::DateDuration(left.clone(), right.clone()), (Date(left), Duration(right)) => CompareValues::DateDuration(*left, *right),
_ => return Err((left.type_name(), right.type_name())), _ => return Err((left.type_name(), right.type_name())),
}) })
} }

View file

@ -144,7 +144,7 @@ pub(crate) fn get_data_by_member(value: &Value, name: &PathMember) -> Result<Val
} }
} }
if out.len() == 0 { if out.is_empty() {
Err(ShellError::missing_property( Err(ShellError::missing_property(
"table".spanned(value.tag.span), "table".spanned(value.tag.span),
string.spanned(name.span), string.spanned(name.span),
@ -203,7 +203,7 @@ pub fn get_data_by_column_path(
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> {
let mut new_obj = value.clone(); let mut new_obj = value.clone();
let split_path: Vec<_> = path.split(".").collect(); let split_path: Vec<_> = path.split('.').collect();
if let UntaggedValue::Row(ref mut o) = new_obj.value { if let UntaggedValue::Row(ref mut o) = new_obj.value {
let mut current = o; let mut current = o;
@ -256,9 +256,10 @@ pub fn insert_data_at_member(
) -> Result<(), ShellError> { ) -> Result<(), ShellError> {
match &mut value.value { match &mut value.value {
UntaggedValue::Row(dict) => match &member.unspanned { UntaggedValue::Row(dict) => match &member.unspanned {
UnspannedPathMember::String(key) => Ok({ UnspannedPathMember::String(key) => {
dict.insert_data_at_key(key, new_value); dict.insert_data_at_key(key, new_value);
}), Ok(())
}
UnspannedPathMember::Int(_) => Err(ShellError::type_error( UnspannedPathMember::Int(_) => Err(ShellError::type_error(
"column name", "column name",
"integer".spanned(member.span), "integer".spanned(member.span),
@ -269,7 +270,7 @@ pub fn insert_data_at_member(
"list index", "list index",
"string".spanned(member.span), "string".spanned(member.span),
)), )),
UnspannedPathMember::Int(int) => Ok({ UnspannedPathMember::Int(int) => {
let int = int.to_usize().ok_or_else(|| { let int = int.to_usize().ok_or_else(|| {
ShellError::range_error( ShellError::range_error(
ExpectedRange::Usize, ExpectedRange::Usize,
@ -279,7 +280,8 @@ pub fn insert_data_at_member(
})?; })?;
insert_data_at_index(array, int.tagged(member.span), new_value.clone())?; insert_data_at_index(array, int.tagged(member.span), new_value.clone())?;
}), Ok(())
}
}, },
other => match &member.unspanned { other => match &member.unspanned {
UnspannedPathMember::String(_) => Err(ShellError::type_error( UnspannedPathMember::String(_) => Err(ShellError::type_error(
@ -473,7 +475,7 @@ pub(crate) fn get_data_by_key(value: &Value, name: Spanned<&str>) -> Option<Valu
} }
} }
if out.len() > 0 { if !out.is_empty() {
Some(UntaggedValue::Table(out).into_value(name.span)) Some(UntaggedValue::Table(out).into_value(name.span))
} else { } else {
None None

View file

@ -196,7 +196,7 @@ impl<'a> PrettyDebug for DebugEntry<'a> {
fn pretty(&self) -> DebugDocBuilder { fn pretty(&self) -> DebugDocBuilder {
(b::key(match self.key { (b::key(match self.key {
Column::String(string) => string.clone(), Column::String(string) => string.clone(),
Column::Value => format!("<value>"), Column::Value => "<value>".to_owned(),
}) + b::delimit("(", self.value.pretty(), ")").as_kind()) }) + b::delimit("(", self.value.pretty(), ")").as_kind())
} }
} }
@ -251,7 +251,7 @@ impl InlineShape {
Primitive::ColumnPath(path) => InlineShape::ColumnPath(path.clone()), Primitive::ColumnPath(path) => InlineShape::ColumnPath(path.clone()),
Primitive::Pattern(pattern) => InlineShape::Pattern(pattern.clone()), Primitive::Pattern(pattern) => InlineShape::Pattern(pattern.clone()),
Primitive::Boolean(boolean) => InlineShape::Boolean(*boolean), Primitive::Boolean(boolean) => InlineShape::Boolean(*boolean),
Primitive::Date(date) => InlineShape::Date(date.clone()), Primitive::Date(date) => InlineShape::Date(*date),
Primitive::Duration(duration) => InlineShape::Duration(*duration), Primitive::Duration(duration) => InlineShape::Duration(*duration),
Primitive::Path(path) => InlineShape::Path(path.clone()), Primitive::Path(path) => InlineShape::Path(path.clone()),
Primitive::Binary(_) => InlineShape::Binary, Primitive::Binary(_) => InlineShape::Binary,
@ -329,23 +329,26 @@ impl PrettyDebug for FormatInlineShape {
(b::primitive(format!("{}", byte.get_value())) + b::space() + b::kind("B")) (b::primitive(format!("{}", byte.get_value())) + b::space() + b::kind("B"))
.group() .group()
} }
_ => b::primitive(format!("{}", byte.format(1))), _ => b::primitive(byte.format(1).to_string()),
} }
} }
InlineShape::String(string) => b::primitive(format!("{}", string)), InlineShape::String(string) => b::primitive(string),
InlineShape::Line(string) => b::primitive(format!("{}", string)), InlineShape::Line(string) => b::primitive(string),
InlineShape::ColumnPath(path) => { InlineShape::ColumnPath(path) => {
b::intersperse(path.iter().map(|member| member.pretty()), b::keyword(".")) b::intersperse(path.iter().map(|member| member.pretty()), b::keyword("."))
} }
InlineShape::Pattern(pattern) => b::primitive(pattern), InlineShape::Pattern(pattern) => b::primitive(pattern),
InlineShape::Boolean(boolean) => b::primitive(match (boolean, column) { InlineShape::Boolean(boolean) => b::primitive(
(true, None) => format!("Yes"), match (boolean, column) {
(false, None) => format!("No"), (true, None) => "Yes",
(true, Some(Column::String(s))) if !s.is_empty() => format!("{}", s), (false, None) => "No",
(false, Some(Column::String(s))) if !s.is_empty() => format!(""), (true, Some(Column::String(s))) if !s.is_empty() => s,
(true, Some(_)) => format!("Yes"), (false, Some(Column::String(s))) if !s.is_empty() => "",
(false, Some(_)) => format!("No"), (true, Some(_)) => "Yes",
}), (false, Some(_)) => "No",
}
.to_owned(),
),
InlineShape::Date(date) => b::primitive(date.humanize()), InlineShape::Date(date) => b::primitive(date.humanize()),
InlineShape::Duration(duration) => { InlineShape::Duration(duration) => {
b::description(format_primitive(&Primitive::Duration(*duration), None)) b::description(format_primitive(&Primitive::Duration(*duration), None))
@ -443,12 +446,12 @@ where
None => { None => {
self.values.insert(key, { self.values.insert(key, {
let mut group = G::new(); let mut group = G::new();
group.merge(value.into()); group.merge(value);
group group
}); });
} }
Some(group) => { Some(group) => {
group.merge(value.into()); group.merge(value);
} }
} }
} }
@ -514,7 +517,7 @@ impl Shape {
d.iter() d.iter()
.map(|c| match c { .map(|c| match c {
Column::String(s) => s.clone(), Column::String(s) => s.clone(),
Column::Value => format!("<value>"), Column::Value => "<value>".to_owned(),
}) })
.join(", ") .join(", ")
), ),

View file

@ -53,7 +53,7 @@ fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {
sig.push_value(for_spec(arg.0.name(), "argument", is_required, &tag)); sig.push_value(for_spec(arg.0.name(), "argument", is_required, &tag));
} }
if let Some(_) = signature.rest_positional { if signature.rest_positional.is_some() {
let is_required = false; let is_required = false;
sig.push_value(for_spec("rest", "argument", is_required, &tag)); sig.push_value(for_spec("rest", "argument", is_required, &tag));
} }

View file

@ -16,7 +16,7 @@ impl<'a> PrettyDebug for DebugEntry<'a> {
} }
pub trait DictionaryExt { pub trait DictionaryExt {
fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value>; fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value>;
fn keys(&self) -> indexmap::map::Keys<String, Value>; fn keys(&self) -> indexmap::map::Keys<String, Value>;
fn get_data_by_key(&self, name: Spanned<&str>) -> Option<Value>; fn get_data_by_key(&self, name: Spanned<&str>) -> Option<Value>;
@ -25,7 +25,7 @@ pub trait DictionaryExt {
} }
impl DictionaryExt for Dictionary { impl DictionaryExt for Dictionary {
fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value> { fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value> {
match self.entries.get(desc) { match self.entries.get(desc) {
Some(v) => MaybeOwned::Borrowed(v), Some(v) => MaybeOwned::Borrowed(v),
None => MaybeOwned::Owned( None => MaybeOwned::Owned(

View file

@ -29,15 +29,15 @@ pub fn format_primitive(primitive: &Primitive, field_name: Option<&String>) -> S
match byte.get_unit() { match byte.get_unit() {
byte_unit::ByteUnit::B => format!("{} B ", byte.get_value()), byte_unit::ByteUnit::B => format!("{} B ", byte.get_value()),
_ => format!("{}", byte.format(1)), _ => byte.format(1).to_string(),
} }
} }
Primitive::Duration(sec) => format_duration(*sec), Primitive::Duration(sec) => format_duration(*sec),
Primitive::Int(i) => format!("{}", i), Primitive::Int(i) => i.to_string(),
Primitive::Decimal(decimal) => format!("{}", decimal), Primitive::Decimal(decimal) => decimal.to_string(),
Primitive::Pattern(s) => format!("{}", s), Primitive::Pattern(s) => s.to_string(),
Primitive::String(s) => format!("{}", s), Primitive::String(s) => s.to_owned(),
Primitive::Line(s) => format!("{}", s), Primitive::Line(s) => s.to_owned(),
Primitive::ColumnPath(p) => { Primitive::ColumnPath(p) => {
let mut members = p.iter(); let mut members = p.iter();
let mut f = String::new(); let mut f = String::new();
@ -57,15 +57,16 @@ pub fn format_primitive(primitive: &Primitive, field_name: Option<&String>) -> S
f f
} }
Primitive::Boolean(b) => match (b, field_name) { Primitive::Boolean(b) => match (b, field_name) {
(true, None) => format!("Yes"), (true, None) => "Yes",
(false, None) => format!("No"), (false, None) => "No",
(true, Some(s)) if !s.is_empty() => format!("{}", s), (true, Some(s)) if !s.is_empty() => s,
(false, Some(s)) if !s.is_empty() => format!(""), (false, Some(s)) if !s.is_empty() => "",
(true, Some(_)) => format!("Yes"), (true, Some(_)) => "Yes",
(false, Some(_)) => format!("No"), (false, Some(_)) => "No",
}, }
Primitive::Binary(_) => format!("<binary>"), .to_owned(),
Primitive::Date(d) => format!("{}", d.humanize()), Primitive::Binary(_) => "<binary>".to_owned(),
Primitive::Date(d) => d.humanize().to_string(),
} }
} }
@ -83,7 +84,7 @@ fn format_duration(sec: u64) -> String {
let (days, hours) = (hours / 24, hours % 24); let (days, hours) = (hours / 24, hours % 24);
match (days, hours, minutes, seconds) { match (days, hours, minutes, seconds) {
(0, 0, 0, 1) => format!("1 sec"), (0, 0, 0, 1) => "1 sec".to_owned(),
(0, 0, 0, s) => format!("{} secs", s), (0, 0, 0, s) => format!("{} secs", s),
(0, 0, m, s) => format!("{}:{:02}", m, s), (0, 0, m, s) => format!("{}:{:02}", m, s),
(0, h, m, s) => format!("{}:{:02}:{:02}", h, m, s), (0, h, m, s) => format!("{}:{:02}:{:02}", h, m, s),

View file

@ -22,7 +22,7 @@ pub fn date_from_str(s: Tagged<&str>) -> Result<UntaggedValue, ShellError> {
} }
pub fn compare_values( pub fn compare_values(
operator: &Operator, operator: Operator,
left: &UntaggedValue, left: &UntaggedValue,
right: &UntaggedValue, right: &UntaggedValue,
) -> Result<bool, (&'static str, &'static str)> { ) -> Result<bool, (&'static str, &'static str)> {

View file

@ -43,11 +43,11 @@ impl<'de> ConfigDeserializer<'de> {
Some(UntaggedValue::Table(positional).into_untagged_value()) // TODO: correct tag Some(UntaggedValue::Table(positional).into_untagged_value()) // TODO: correct tag
} else { } else {
if self.call.args.has(name) { if self.call.args.has(name) {
self.call.args.get(name).map(|x| x.clone()) self.call.args.get(name).cloned()
} else { } else {
let position = self.position; let position = self.position;
self.position += 1; self.position += 1;
self.call.args.nth(position).map(|x| x.clone()) self.call.args.nth(position).cloned()
} }
}; };
@ -316,7 +316,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut ConfigDeserializer<'de> {
let json_cursor = std::io::Cursor::new(json.into_bytes()); let json_cursor = std::io::Cursor::new(json.into_bytes());
let mut json_de = serde_json::Deserializer::from_reader(json_cursor); let mut json_de = serde_json::Deserializer::from_reader(json_cursor);
let r = json_de.deserialize_struct(name, fields, visitor)?; let r = json_de.deserialize_struct(name, fields, visitor)?;
return Ok(r); Ok(r)
} }
trace!( trace!(
@ -409,12 +409,10 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut ConfigDeserializer<'de> {
.. ..
} => visit::<Tagged<String>, _>(string.tagged(tag), name, fields, visitor), } => visit::<Tagged<String>, _>(string.tagged(tag), name, fields, visitor),
other => { other => Err(ShellError::type_error(
return Err(ShellError::type_error( name,
name, other.type_name().spanned(other.span()),
other.type_name().spanned(other.span()), )),
))
}
} }
} }
fn deserialize_enum<V>( fn deserialize_enum<V>(
@ -471,7 +469,7 @@ impl<'a, 'de: 'a, I: Iterator<Item = Value>> de::SeqAccess<'de> for SeqDeseriali
} }
fn size_hint(&self) -> Option<usize> { fn size_hint(&self) -> Option<usize> {
return self.vals.size_hint().1; self.vals.size_hint().1
} }
} }
@ -493,7 +491,7 @@ impl<'a, 'de: 'a> de::SeqAccess<'de> for StructDeserializer<'a, 'de> {
where where
T: de::DeserializeSeed<'de>, T: de::DeserializeSeed<'de>,
{ {
if self.fields.len() == 0 { if self.fields.is_empty() {
return Ok(None); return Ok(None);
} }
@ -505,7 +503,7 @@ impl<'a, 'de: 'a> de::SeqAccess<'de> for StructDeserializer<'a, 'de> {
} }
fn size_hint(&self) -> Option<usize> { fn size_hint(&self) -> Option<usize> {
return Some(self.fields.len()); Some(self.fields.len())
} }
} }

View file

@ -40,7 +40,7 @@ pub(crate) fn evaluate_baseline_expr(
trace!("left={:?} right={:?}", left.value, right.value); trace!("left={:?} right={:?}", left.value, right.value);
match apply_operator(binary.op(), &left, &right) { match apply_operator(**binary.op(), &left, &right) {
Ok(result) => Ok(result.into_value(tag)), Ok(result) => Ok(result.into_value(tag)),
Err((left_type, right_type)) => Err(ShellError::coerce_error( Err((left_type, right_type)) => Err(ShellError::coerce_error(
left_type.spanned(binary.left().span), left_type.spanned(binary.left().span),
@ -83,7 +83,7 @@ pub(crate) fn evaluate_baseline_expr(
possible_matches.sort(); possible_matches.sort();
if possible_matches.len() > 0 { if !possible_matches.is_empty() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"Unknown column", "Unknown column",
format!("did you mean '{}'?", possible_matches[0].1), format!("did you mean '{}'?", possible_matches[0].1),
@ -174,7 +174,7 @@ fn evaluate_reference(
x => Ok(scope x => Ok(scope
.vars .vars
.get(x) .get(x)
.map(|v| v.clone()) .cloned()
.unwrap_or_else(|| UntaggedValue::nothing().into_value(tag))), .unwrap_or_else(|| UntaggedValue::nothing().into_value(tag))),
}, },
} }

View file

@ -4,11 +4,11 @@ use nu_protocol::{Primitive, ShellTypeName, UntaggedValue, Value};
use std::ops::Not; use std::ops::Not;
pub fn apply_operator( pub fn apply_operator(
op: &Operator, op: Operator,
left: &Value, left: &Value,
right: &Value, right: &Value,
) -> Result<UntaggedValue, (&'static str, &'static str)> { ) -> Result<UntaggedValue, (&'static str, &'static str)> {
match *op { match op {
Operator::Equal Operator::Equal
| Operator::NotEqual | Operator::NotEqual
| Operator::LessThan | Operator::LessThan

View file

@ -35,7 +35,7 @@ impl EntriesView {
impl RenderView for EntriesView { impl RenderView for EntriesView {
fn render_view(&self, _host: &mut dyn Host) -> Result<(), ShellError> { fn render_view(&self, _host: &mut dyn Host) -> Result<(), ShellError> {
if self.entries.len() == 0 { if self.entries.is_empty() {
return Ok(()); return Ok(());
} }

View file

@ -16,7 +16,10 @@ impl RenderView for GenericView<'_> {
fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> { fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> {
let tag = &self.value.tag; let tag = &self.value.tag;
match &self.value.value { match &self.value.value {
UntaggedValue::Primitive(p) => Ok(host.stdout(&format_primitive(p, None))), UntaggedValue::Primitive(p) => {
host.stdout(&format_primitive(p, None));
Ok(())
}
UntaggedValue::Table(l) => { UntaggedValue::Table(l) => {
let view = TableView::from_list(l, 0); let view = TableView::from_list(l, 0);

View file

@ -30,7 +30,7 @@ impl TableView {
for value in values { for value in values {
let descs = value.data_descriptors(); let descs = value.data_descriptors();
if descs.len() == 0 { if descs.is_empty() {
if !ret.contains(&value_column) { if !ret.contains(&value_column) {
ret.push("<value>".to_string()); ret.push("<value>".to_string());
} }
@ -46,13 +46,13 @@ impl TableView {
} }
pub fn from_list(values: &[Value], starting_idx: usize) -> Option<TableView> { pub fn from_list(values: &[Value], starting_idx: usize) -> Option<TableView> {
if values.len() == 0 { if values.is_empty() {
return None; return None;
} }
let mut headers = TableView::merge_descriptors(values); let mut headers = TableView::merge_descriptors(values);
if headers.len() == 0 { if headers.is_empty() {
headers.push("<value>".to_string()); headers.push("<value>".to_string());
} }
@ -68,10 +68,10 @@ impl TableView {
value: UntaggedValue::Row(..), value: UntaggedValue::Row(..),
.. ..
} => ( } => (
format_leaf(&UntaggedValue::nothing()).plain_string(100000), format_leaf(&UntaggedValue::nothing()).plain_string(100_000),
style_leaf(&UntaggedValue::nothing()), style_leaf(&UntaggedValue::nothing()),
), ),
_ => (format_leaf(value).plain_string(100000), style_leaf(value)), _ => (format_leaf(value).plain_string(100_000), style_leaf(value)),
} }
} else { } else {
match value { match value {
@ -81,12 +81,12 @@ impl TableView {
} => { } => {
let data = value.get_data(d); let data = value.get_data(d);
( (
format_leaf(data.borrow()).plain_string(100000), format_leaf(data.borrow()).plain_string(100_000),
style_leaf(data.borrow()), style_leaf(data.borrow()),
) )
} }
_ => ( _ => (
format_leaf(&UntaggedValue::nothing()).plain_string(100000), format_leaf(&UntaggedValue::nothing()).plain_string(100_000),
style_leaf(&UntaggedValue::nothing()), style_leaf(&UntaggedValue::nothing()),
), ),
} }
@ -96,7 +96,7 @@ impl TableView {
if values.len() > 1 { if values.len() > 1 {
// Indices are black, bold, right-aligned: // Indices are black, bold, right-aligned:
row.insert(0, (format!("{}", (starting_idx + idx).to_string()), "Fdbr")); row.insert(0, ((starting_idx + idx).to_string(), "Fdbr"));
} }
entries.push(row); entries.push(row);
@ -105,22 +105,21 @@ impl TableView {
let mut max_per_column = vec![]; let mut max_per_column = vec![];
if values.len() > 1 { if values.len() > 1 {
headers.insert(0, format!("#")); headers.insert(0, "#".to_owned());
} }
for head in 0..headers.len() { for i in 0..headers.len() {
let mut current_col_max = 0; let mut current_col_max = 0;
for row in 0..values.len() { let iter = entries.iter().take(values.len());
let value_length = entries[row][head].0.chars().count();
for entry in iter {
let value_length = entry[i].0.chars().count();
if value_length > current_col_max { if value_length > current_col_max {
current_col_max = value_length; current_col_max = value_length;
} }
} }
max_per_column.push(std::cmp::max( max_per_column.push(std::cmp::max(current_col_max, headers[i].chars().count()));
current_col_max,
headers[head].chars().count(),
));
} }
// Different platforms want different amounts of buffer, not sure why // Different platforms want different amounts of buffer, not sure why
@ -132,13 +131,14 @@ impl TableView {
// If we have too many columns, truncate the table // If we have too many columns, truncate the table
if max_num_of_columns < headers.len() { if max_num_of_columns < headers.len() {
headers.truncate(max_num_of_columns); headers.truncate(max_num_of_columns);
for row in 0..entries.len() {
entries[row].truncate(max_num_of_columns); for entry in &mut entries {
entry.truncate(max_num_of_columns);
} }
headers.push("...".to_string()); headers.push("...".to_owned());
for row in 0..entries.len() { for entry in &mut entries {
entries[row].push(("...".to_string(), "c")); // ellipsis is centred entry.push(("...".to_owned(), "c")); // ellipsis is centred
} }
} }
@ -149,22 +149,23 @@ impl TableView {
let mut num_overages = 0; let mut num_overages = 0;
let mut underage_sum = 0; let mut underage_sum = 0;
let mut overage_separator_sum = 0; let mut overage_separator_sum = 0;
for idx in 0..headers.len() { let iter = max_per_column.iter().enumerate().take(headers.len());
if max_per_column[idx] > max_naive_column_width { for (i, &column_max) in iter {
if column_max > max_naive_column_width {
num_overages += 1; num_overages += 1;
if idx != (headers.len() - 1) { if i != (headers.len() - 1) {
overage_separator_sum += 3; overage_separator_sum += 3;
} }
if idx == 0 { if i == 0 {
overage_separator_sum += 1; overage_separator_sum += 1;
} }
} else { } else {
underage_sum += max_per_column[idx]; underage_sum += column_max;
// if column isn't last, add 3 for its separator // if column isn't last, add 3 for its separator
if idx != (headers.len() - 1) { if i != (headers.len() - 1) {
underage_sum += 3; underage_sum += 3;
} }
if idx == 0 { if i == 0 {
underage_sum += 1; underage_sum += 1;
} }
} }
@ -180,24 +181,25 @@ impl TableView {
// This width isn't quite right, as we're rounding off some of our space // This width isn't quite right, as we're rounding off some of our space
num_overages = 0; num_overages = 0;
overage_separator_sum = 0; overage_separator_sum = 0;
for idx in 0..headers.len() { let iter = max_per_column.iter().enumerate().take(headers.len());
if max_per_column[idx] > max_naive_column_width { for (i, &column_max) in iter {
if max_per_column[idx] <= max_column_width { if column_max > max_naive_column_width {
underage_sum += max_per_column[idx]; if column_max <= max_column_width {
underage_sum += column_max;
// if column isn't last, add 3 for its separator // if column isn't last, add 3 for its separator
if idx != (headers.len() - 1) { if i != (headers.len() - 1) {
underage_sum += 3; underage_sum += 3;
} }
if idx == 0 { if i == 0 {
underage_sum += 1; underage_sum += 1;
} }
} else { } else {
// Column is still too large, so let's count it // Column is still too large, so let's count it
num_overages += 1; num_overages += 1;
if idx != (headers.len() - 1) { if i != (headers.len() - 1) {
overage_separator_sum += 3; overage_separator_sum += 3;
} }
if idx == 0 { if i == 0 {
overage_separator_sum += 1; overage_separator_sum += 1;
} }
} }
@ -214,8 +216,9 @@ impl TableView {
for head in 0..headers.len() { for head in 0..headers.len() {
if max_per_column[head] > max_naive_column_width { if max_per_column[head] > max_naive_column_width {
headers[head] = fill(&headers[head], max_column_width); headers[head] = fill(&headers[head], max_column_width);
for row in 0..entries.len() {
entries[row][head].0 = fill(&entries[row][head].0, max_column_width); for entry in &mut entries {
entry[head].0 = fill(&entry[head].0, max_column_width);
} }
} }
} }
@ -226,7 +229,7 @@ impl TableView {
impl RenderView for TableView { impl RenderView for TableView {
fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> { fn render_view(&self, host: &mut dyn Host) -> Result<(), ShellError> {
if self.entries.len() == 0 { if self.entries.is_empty() {
return Ok(()); return Ok(());
} }

View file

@ -21,7 +21,7 @@ fn format(input: &str) -> IResult<&str, Vec<FormatCommand>> {
let mut loop_input = input; let mut loop_input = input;
loop { loop {
let (input, before) = take_while(|c| c != '{')(loop_input)?; let (input, before) = take_while(|c| c != '{')(loop_input)?;
if before.len() > 0 { if !before.is_empty() {
output.push(FormatCommand::Text(before.to_string())); output.push(FormatCommand::Text(before.to_string()));
} }
if input != "" { if input != "" {

View file

@ -90,13 +90,13 @@ impl Inc {
} }
UntaggedValue::Table(values) => { UntaggedValue::Table(values) => {
if values.len() == 1 { if values.len() == 1 {
return Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?]) Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?])
.into_value(value.tag())); .into_value(value.tag()))
} else { } else {
return Err(ShellError::type_error( Err(ShellError::type_error(
"incrementable value", "incrementable value",
value.type_name().spanned(value.span()), value.type_name().spanned(value.span()),
)); ))
} }
} }
@ -108,20 +108,16 @@ impl Inc {
&f, &f,
Box::new(move |(obj_source, column_path_tried, _)| { Box::new(move |(obj_source, column_path_tried, _)| {
match did_you_mean(&obj_source, &column_path_tried) { match did_you_mean(&obj_source, &column_path_tried) {
Some(suggestions) => { Some(suggestions) => ShellError::labeled_error(
return ShellError::labeled_error( "Unknown column",
"Unknown column", format!("did you mean '{}'?", suggestions[0].1),
format!("did you mean '{}'?", suggestions[0].1), span_for_spanned_list(fields.iter().map(|p| p.span)),
span_for_spanned_list(fields.iter().map(|p| p.span)), ),
) None => ShellError::labeled_error(
} "Unknown column",
None => { "row does not contain this column",
return ShellError::labeled_error( span_for_spanned_list(fields.iter().map(|p| p.span)),
"Unknown column", ),
"row does not contain this column",
span_for_spanned_list(fields.iter().map(|p| p.span)),
)
}
} }
}), }),
); );
@ -133,14 +129,12 @@ impl Inc {
&f, &f,
replacement.value.clone().into_untagged_value(), replacement.value.clone().into_untagged_value(),
) { ) {
Some(v) => return Ok(v), Some(v) => Ok(v),
None => { None => Err(ShellError::labeled_error(
return 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(
@ -201,13 +195,11 @@ impl Plugin for Inc {
} }
match &self.error { match &self.error {
Some(reason) => { Some(reason) => Err(ShellError::untagged_runtime_error(format!(
return Err(ShellError::untagged_runtime_error(format!( "{}: {}",
"{}: {}", reason,
reason, Inc::usage()
Inc::usage() ))),
)))
}
None => Ok(vec![]), None => Ok(vec![]),
} }
} }

View file

@ -22,7 +22,7 @@ fn parse(input: &str) -> IResult<&str, Vec<ParseCommand>> {
let mut loop_input = input; let mut loop_input = input;
loop { loop {
let (input, before) = take_while(|c| c != '{')(loop_input)?; let (input, before) = take_while(|c| c != '{')(loop_input)?;
if before.len() > 0 { if !before.is_empty() {
output.push(ParseCommand::Text(before.to_string())); output.push(ParseCommand::Text(before.to_string()));
} }
if input != "" { if input != "" {
@ -73,7 +73,7 @@ fn build_regex(commands: &[ParseCommand]) -> String {
} }
} }
return output; output
} }
struct Parse { struct Parse {
regex: Regex, regex: Regex,

View file

@ -126,7 +126,7 @@ impl Str {
_ => v[0].trim().parse().unwrap(), _ => v[0].trim().parse().unwrap(),
}; };
let end: usize = match v[1] { let end: usize = match v[1] {
"" => usize::max_value().clone(), "" => usize::max_value(),
_ => v[1].trim().parse().unwrap(), _ => v[1].trim().parse().unwrap(),
}; };
if start > end { if start > end {
@ -169,14 +169,12 @@ impl Str {
&f, &f,
Box::new(move |(obj_source, column_path_tried, error)| { Box::new(move |(obj_source, column_path_tried, error)| {
match did_you_mean(&obj_source, &column_path_tried) { match did_you_mean(&obj_source, &column_path_tried) {
Some(suggestions) => { Some(suggestions) => ShellError::labeled_error(
return ShellError::labeled_error( "Unknown column",
"Unknown column", format!("did you mean '{}'?", suggestions[0].1),
format!("did you mean '{}'?", suggestions[0].1), span_for_spanned_list(fields.iter().map(|p| p.span)),
span_for_spanned_list(fields.iter().map(|p| p.span)), ),
) None => error,
}
None => return error,
} }
}), }),
); );
@ -188,7 +186,7 @@ impl Str {
&f, &f,
replacement.value.clone().into_untagged_value(), replacement.value.clone().into_untagged_value(),
) { ) {
Some(v) => return Ok(v), Some(v) => Ok(v),
None => Err(ShellError::labeled_error( None => Err(ShellError::labeled_error(
"str could not find field to replace", "str could not find field to replace",
"column name", "column name",
@ -293,13 +291,11 @@ impl Plugin for Str {
} }
match &self.error { match &self.error {
Some(reason) => { Some(reason) => Err(ShellError::untagged_runtime_error(format!(
return Err(ShellError::untagged_runtime_error(format!( "{}: {}",
"{}: {}", reason,
reason, Str::usage()
Str::usage() ))),
)))
}
None => Ok(vec![]), None => Ok(vec![]),
} }
} }

View file

@ -28,11 +28,11 @@ impl NuCompleter {
completion.replacement = completion.replacement.replace("\\(", "("); completion.replacement = completion.replacement.replace("\\(", "(");
} }
if completion.replacement.contains(" ") || completion.replacement.contains("(") { if completion.replacement.contains(' ') || completion.replacement.contains('(') {
if !completion.replacement.starts_with("\"") { if !completion.replacement.starts_with('\"') {
completion.replacement = format!("\"{}", completion.replacement); completion.replacement = format!("\"{}", completion.replacement);
} }
if !completion.replacement.ends_with("\"") { if !completion.replacement.ends_with('\"') {
completion.replacement = format!("{}\"", completion.replacement); completion.replacement = format!("{}\"", completion.replacement);
} }
} }

View file

@ -104,7 +104,7 @@ impl Shell for FilesystemShell {
//If it's not a glob, try to display the contents of the entry if it's a directory //If it's not a glob, try to display the contents of the entry if it's a directory
let lossy_path = full_path.to_string_lossy(); let lossy_path = full_path.to_string_lossy();
if !lossy_path.contains("*") && !lossy_path.contains("?") { if !lossy_path.contains('*') && !lossy_path.contains('?') {
let entry = Path::new(&full_path); let entry = Path::new(&full_path);
if entry.is_dir() { if entry.is_dir() {
let entries = std::fs::read_dir(&entry); let entries = std::fs::read_dir(&entry);
@ -344,7 +344,7 @@ impl Shell for FilesystemShell {
new_dst.push(fragment); new_dst.push(fragment);
} }
Ok((PathBuf::from(&source_file), PathBuf::from(new_dst))) Ok((PathBuf::from(&source_file), new_dst))
}; };
let sources = sources.paths_applying_with(strategy)?; let sources = sources.paths_applying_with(strategy)?;
@ -418,7 +418,7 @@ impl Shell for FilesystemShell {
new_dst.push(fragment); new_dst.push(fragment);
} }
Ok((PathBuf::from(&source_file), PathBuf::from(new_dst))) Ok((PathBuf::from(&source_file), new_dst))
}; };
let sources = sources.paths_applying_with(strategy)?; let sources = sources.paths_applying_with(strategy)?;
@ -530,7 +530,7 @@ impl Shell for FilesystemShell {
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let full_path = PathBuf::from(path); let full_path = PathBuf::from(path);
if directories.len() == 0 { if directories.is_empty() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"mkdir requires directory paths", "mkdir requires directory paths",
"needs parameter", "needs parameter",
@ -861,13 +861,11 @@ impl Shell for FilesystemShell {
} }
} else { } else {
if destination.exists() { if destination.exists() {
if !sources.iter().all(|x| { let is_file = |x: &Result<PathBuf, _>| {
if let Ok(entry) = x.as_ref() { x.as_ref().map(|entry| entry.is_file()).unwrap_or_default()
entry.is_file() };
} else {
false if !sources.iter().all(is_file) {
}
}) {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
"Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)", "Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)",
"Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)", "Rename aborted (directories found). Renaming in patterns not supported yet (try moving the directory directly)",

View file

@ -108,13 +108,11 @@ impl HelpShell {
impl Shell for HelpShell { impl Shell for HelpShell {
fn name(&self) -> String { fn name(&self) -> String {
let anchor_name = self.value.anchor_name(); let anchor_name = self.value.anchor_name();
format!(
"{}", match anchor_name {
match anchor_name { Some(x) => format!("{{{}}}", x),
Some(x) => format!("{{{}}}", x), None => format!("<{}>", self.value.type_name()),
None => format!("<{}>", self.value.type_name()), }
}
)
} }
fn homedir(&self) -> Option<PathBuf> { fn homedir(&self) -> Option<PathBuf> {
@ -140,10 +138,7 @@ impl Shell for HelpShell {
_context: &RunnableContext, _context: &RunnableContext,
_full: bool, _full: bool,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
Ok(self Ok(self.commands().map(ReturnSuccess::value).to_output_stream())
.commands()
.map(|x| ReturnSuccess::value(x))
.to_output_stream())
} }
fn cd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<OutputStream, ShellError> { fn cd(&self, args: EvaluatedWholeStreamCommandArgs) -> Result<OutputStream, ShellError> {

View file

@ -76,13 +76,11 @@ impl ValueShell {
impl Shell for ValueShell { impl Shell for ValueShell {
fn name(&self) -> String { fn name(&self) -> String {
let anchor_name = self.value.anchor_name(); let anchor_name = self.value.anchor_name();
format!(
"{}", match anchor_name {
match anchor_name { Some(x) => format!("{{{}}}", x),
Some(x) => format!("{{{}}}", x), None => format!("<{}>", self.value.type_name()),
None => format!("<{}>", self.value.type_name()), }
}
)
} }
fn homedir(&self) -> Option<PathBuf> { fn homedir(&self) -> Option<PathBuf> {
@ -124,7 +122,7 @@ impl Shell for ValueShell {
Ok(self Ok(self
.members_under(full_path.as_path()) .members_under(full_path.as_path())
.map(|x| ReturnSuccess::value(x)) .map(ReturnSuccess::value)
.to_output_stream()) .to_output_stream())
} }

View file

@ -142,7 +142,7 @@ impl From<VecDeque<Value>> for OutputStream {
OutputStream { OutputStream {
values: input values: input
.into_iter() .into_iter()
.map(|i| ReturnSuccess::value(i)) .map(ReturnSuccess::value)
.collect::<VecDeque<ReturnValue>>() .collect::<VecDeque<ReturnValue>>()
.boxed(), .boxed(),
} }

View file

@ -22,7 +22,7 @@ pub fn did_you_mean(obj_source: &Value, field_tried: &PathMember) -> Option<Vec<
}) })
.collect(); .collect();
if possible_matches.len() > 0 { if !possible_matches.is_empty() {
possible_matches.sort(); possible_matches.sort();
Some(possible_matches) Some(possible_matches)
} else { } else {
@ -96,7 +96,7 @@ impl Div<&str> for &AbsolutePath {
type Output = AbsolutePath; type Output = AbsolutePath;
fn div(self, rhs: &str) -> Self::Output { fn div(self, rhs: &str) -> Self::Output {
let parts = rhs.split("/"); let parts = rhs.split('/');
let mut result = self.inner.clone(); let mut result = self.inner.clone();
for part in parts { for part in parts {
@ -133,7 +133,7 @@ impl<T: AsRef<str>> Div<T> for &RelativePath {
type Output = RelativePath; type Output = RelativePath;
fn div(self, rhs: T) -> Self::Output { fn div(self, rhs: T) -> Self::Output {
let parts = rhs.as_ref().split("/"); let parts = rhs.as_ref().split('/');
let mut result = self.inner.clone(); let mut result = self.inner.clone();
for part in parts { for part in parts {
@ -276,7 +276,7 @@ impl FileStructure {
} }
pub fn contains_files(&self) -> bool { pub fn contains_files(&self) -> bool {
self.resources.len() > 0 !self.resources.is_empty()
} }
pub fn paths_applying_with<F>( pub fn paths_applying_with<F>(