Fix more Clippy warnings

cargo clippy -- -W clippy::correctness
This commit is contained in:
Thibaut Brandscheid 2019-12-07 10:34:32 +01:00
parent dfa5173cf4
commit 683f4c35d9
21 changed files with 395 additions and 455 deletions

View File

@ -52,8 +52,7 @@ pub fn build() -> Result<(), Box<dyn std::error::Error>> {
if all_on && !flags.is_empty() {
println!(
"cargo:warning={}",
"Both NUSHELL_ENABLE_ALL_FLAGS and NUSHELL_ENABLE_FLAGS were set. You don't need both."
"cargo:warning=Both NUSHELL_ENABLE_ALL_FLAGS and NUSHELL_ENABLE_FLAGS were set. You don't need both."
);
}

View File

@ -20,12 +20,12 @@ impl PrettyDebug for PositionalType {
fn pretty(&self) -> DebugDocBuilder {
match self {
PositionalType::Mandatory(string, shape) => {
b::description(string) + b::delimit("(", shape.pretty(), ")").as_kind().group()
b::description(string) + b::delimit("(", shape.pretty(), ")").into_kind().group()
}
PositionalType::Optional(string, shape) => {
b::description(string)
+ b::operator("?")
+ b::delimit("(", shape.pretty(), ")").as_kind().group()
+ b::delimit("(", shape.pretty(), ")").into_kind().group()
}
}
}

View File

@ -63,7 +63,7 @@ struct DebugEntry<'a> {
impl<'a> PrettyDebug for DebugEntry<'a> {
fn pretty(&self) -> DebugDocBuilder {
(b::key(self.key.to_string()) + b::equals() + self.value.pretty().as_value()).group()
(b::key(self.key.to_string()) + b::equals() + self.value.pretty().into_value()).group()
}
}

View File

@ -135,7 +135,7 @@ impl DebugDocBuilder {
DebugDocBuilder::styled(string, ShellStyle::Value)
}
pub fn as_value(self) -> DebugDocBuilder {
pub fn into_value(self) -> DebugDocBuilder {
self.inner
.annotate(ShellAnnotation::style(ShellStyle::Value))
.into()
@ -149,7 +149,7 @@ impl DebugDocBuilder {
DebugDocBuilder::styled(string, ShellStyle::Kind)
}
pub fn as_kind(self) -> DebugDocBuilder {
pub fn into_kind(self) -> DebugDocBuilder {
self.inner
.annotate(ShellAnnotation::style(ShellStyle::Kind))
.into()

View File

@ -60,16 +60,14 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel
if context.get_command(&name).is_some() {
trace!("plugin {:?} already loaded.", &name);
} else {
if params.is_filter {
context.add_commands(vec![whole_stream_command(
PluginCommand::new(name, fname, params),
)]);
} else if params.is_filter {
context.add_commands(vec![whole_stream_command(PluginCommand::new(
name, fname, params,
))]);
} else {
context.add_commands(vec![whole_stream_command(PluginSink::new(
name, fname, params,
))]);
};
}
Ok(())
}
@ -482,55 +480,42 @@ fn set_env_from_config() {
let value = config.get("env");
match value {
Some(Value {
if let Some(Value {
value: UntaggedValue::Row(r),
..
}) => {
}) = value
{
for (k, v) in &r.entries {
match v.as_string() {
Ok(value_string) => {
if let Ok(value_string) = v.as_string() {
std::env::set_var(k, value_string);
}
_ => {}
}
}
}
_ => {}
}
}
if config.contains_key("path") {
// Override the path with what they give us from config
let value = config.get("path");
match value {
Some(value) => match value {
Value {
if let Some(Value {
value: UntaggedValue::Table(table),
..
} => {
}) = value
{
let mut paths = vec![];
for val in table {
let path_str = val.as_string();
match path_str {
Err(_) => {}
Ok(path_str) => {
if let Ok(path_str) = path_str {
paths.push(PathBuf::from(path_str));
}
}
}
let path_os_string = std::env::join_paths(&paths);
match path_os_string {
Ok(path_os_string) => {
if let Ok(path_os_string) = path_os_string {
std::env::set_var("PATH", path_os_string);
}
Err(_) => {}
}
}
_ => {}
},
None => {}
}
}
}

View File

@ -171,7 +171,7 @@ fn parse_separated_columns<'a>(
let headers = headers_raw
.split(&separator)
.map(str::trim)
.map(|s| s.to_owned())
.map(str::to_owned)
.filter(|s| !s.is_empty())
.collect();
collect(headers, lines, separator)

View File

@ -50,8 +50,7 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellErr
obj,
path,
Box::new(move |(obj_source, column_path_tried, error)| {
match &obj_source.value {
UntaggedValue::Table(rows) => {
if let UntaggedValue::Table(rows) = &obj_source.value {
let total = rows.len();
let end_tag = match fields
.members()
@ -62,33 +61,32 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellErr
None => column_path_tried.span,
};
return ShellError::labeled_error_with_secondary(
"Row not found",
format!(
let primary_label = format!(
"There isn't a row indexed at {}",
column_path_tried.display()
),
column_path_tried.span,
if total == 1 {
);
let secondary_label = if total == 1 {
"The table only has 1 row".to_owned()
} else {
format!("The table only has {} rows (0 to {})", total, total - 1)
},
};
return ShellError::labeled_error_with_secondary(
"Row not found",
primary_label,
column_path_tried.span,
secondary_label,
end_tag,
);
}
_ => {}
}
match did_you_mean(&obj_source, column_path_tried) {
Some(suggestions) => {
if let Some(suggestions) = did_you_mean(&obj_source, column_path_tried) {
return ShellError::labeled_error(
"Unknown column",
format!("did you mean '{}'?", suggestions[0].1),
span_for_spanned_list(fields.members().iter().map(|p| p.span)),
)
}
None => {}
);
}
error

View File

@ -57,8 +57,7 @@ impl PerItemCommand for Help {
help.push_back(ReturnSuccess::value(short_desc.into_value()));
}
} else {
if let Some(command) = registry.get_command(document) {
} else if let Some(command) = registry.get_command(document) {
let mut long_desc = String::new();
long_desc.push_str(&command.usage());
@ -96,12 +95,10 @@ impl PerItemCommand for Help {
for positional in signature.positional {
match positional.0 {
PositionalType::Mandatory(name, _m) => {
long_desc
.push_str(&format!(" <{}> {}\n", name, positional.1));
long_desc.push_str(&format!(" <{}> {}\n", name, positional.1));
}
PositionalType::Optional(name, _o) => {
long_desc
.push_str(&format!(" ({}) {}\n", name, positional.1));
long_desc.push_str(&format!(" ({}) {}\n", name, positional.1));
}
}
}
@ -155,7 +152,6 @@ impl PerItemCommand for Help {
UntaggedValue::string(long_desc).into_value(tag.clone()),
));
}
}
Ok(help.to_output_stream())
}

View File

@ -43,14 +43,13 @@ pub fn which(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
Value {
value: UntaggedValue::Primitive(Primitive::String(s)),
tag,
} => match which::which(&s) {
Ok(ok) => {
} => {
if let Ok(ok) = which::which(&s) {
which_out.push_back(
UntaggedValue::Primitive(Primitive::Path(ok)).into_value(tag.clone()),
);
}
_ => {}
},
}
Value { tag, .. } => {
return Err(ShellError::labeled_error(
"Expected a filename to find",

View File

@ -132,15 +132,14 @@ pub(crate) fn get_data_by_member(value: &Value, name: &PathMember) -> Result<Val
let mut out = vec![];
for item in l {
match item {
Value {
if let Value {
value: UntaggedValue::Row(o),
..
} => match o.get_data_by_key(string[..].spanned(name.span)) {
Some(v) => out.push(v),
None => {}
},
_ => {}
} = item
{
if let Some(v) = o.get_data_by_key(string[..].spanned(name.span)) {
out.push(v)
}
}
}
@ -221,16 +220,12 @@ pub fn insert_data_at_path(value: &Value, path: &str, new_value: Value) -> Optio
match current.entries.get_mut(split_path[idx]) {
Some(next) => {
if idx == (split_path.len() - 2) {
match &mut next.value {
UntaggedValue::Row(o) => {
if let UntaggedValue::Row(o) = &mut next.value {
o.entries.insert(
split_path[idx + 1].to_string(),
new_value.value.clone().into_value(&value.tag),
);
}
_ => {}
}
return Some(new_obj.clone());
} else {
match next.value {
@ -497,15 +492,14 @@ pub(crate) fn get_mut_data_by_member<'value>(
UntaggedValue::Table(l) => match &name.unspanned {
UnspannedPathMember::String(string) => {
for item in l {
match item {
Value {
if let Value {
value: UntaggedValue::Row(o),
..
} => match o.get_mut_data_by_key(&string) {
Some(v) => return Some(v),
None => {}
},
_ => {}
} = item
{
if let Some(v) = o.get_mut_data_by_key(&string) {
return Some(v);
}
}
}
None

View File

@ -135,7 +135,7 @@ impl PrettyDebug for TypeShape {
(b::key(match key {
Column::String(string) => string.clone(),
Column::Value => "<value>".to_string(),
}) + b::delimit("(", ty.pretty(), ")").as_kind())
}) + b::delimit("(", ty.pretty(), ")").into_kind())
.nest()
}),
b::space(),
@ -197,7 +197,7 @@ impl<'a> PrettyDebug for DebugEntry<'a> {
(b::key(match self.key {
Column::String(string) => string.clone(),
Column::Value => "<value>".to_owned(),
}) + b::delimit("(", self.value.pretty(), ")").as_kind())
}) + b::delimit("(", self.value.pretty(), ")").into_kind())
}
}

View File

@ -11,7 +11,7 @@ struct DebugEntry<'a> {
impl<'a> PrettyDebug for DebugEntry<'a> {
fn pretty(&self) -> DebugDocBuilder {
(b::key(self.key.to_string()) + b::equals() + self.value.pretty().as_value()).group()
(b::key(self.key.to_string()) + b::equals() + self.value.pretty().into_value()).group()
}
}

View File

@ -47,19 +47,16 @@ pub(crate) fn dir_entry_dict(
dict.insert_untagged("size", UntaggedValue::bytes(metadata.len() as u64));
match metadata.created() {
Ok(c) => dict.insert_untagged("created", UntaggedValue::system_date(c)),
Err(_) => {}
if let Ok(c) = metadata.created() {
dict.insert_untagged("created", UntaggedValue::system_date(c));
}
match metadata.accessed() {
Ok(a) => dict.insert_untagged("accessed", UntaggedValue::system_date(a)),
Err(_) => {}
if let Ok(a) = metadata.accessed() {
dict.insert_untagged("accessed", UntaggedValue::system_date(a));
}
match metadata.modified() {
Ok(m) => dict.insert_untagged("modified", UntaggedValue::system_date(m)),
Err(_) => {}
if let Ok(m) = metadata.modified() {
dict.insert_untagged("modified", UntaggedValue::system_date(m));
}
Ok(dict.into_value())

View File

@ -41,14 +41,12 @@ impl<'de> ConfigDeserializer<'de> {
let positional = self.call.args.slice_from(self.position);
self.position += positional.len();
Some(UntaggedValue::Table(positional).into_untagged_value()) // TODO: correct tag
} else {
if self.call.args.has(name) {
} else if self.call.args.has(name) {
self.call.args.get(name).cloned()
} else {
let position = self.position;
self.position += 1;
self.call.args.nth(position).cloned()
}
};
trace!("pushing {:?}", value);

View File

@ -161,14 +161,12 @@ fn evaluate_reference(
}
x if x == "nu:path" => {
let mut table = vec![];
match std::env::var_os("PATH") {
Some(paths) => {
let path = std::env::var_os("PATH");
if let Some(paths) = path {
for path in std::env::split_paths(&paths) {
table.push(UntaggedValue::path(path).into_value(&tag));
}
}
_ => {}
}
Ok(UntaggedValue::table(&table).into_value(tag))
}
x => Ok(scope

View File

@ -153,7 +153,7 @@ fn values_to_entries(values: &[Value], headers: &mut Vec<String>, starting_idx:
entries
}
fn max_per_column(headers: &Vec<String>, entries: &Entries, values_len: usize) -> Vec<usize> {
fn max_per_column(headers: &[String], entries: &Entries, values_len: usize) -> Vec<usize> {
let mut max_per_column = vec![];
for i in 0..headers.len() {
@ -181,13 +181,13 @@ fn maybe_truncate_columns(headers: &mut Vec<String>, entries: &mut Entries, term
if max_num_of_columns < headers.len() {
headers.truncate(max_num_of_columns);
for entry in &mut entries.into_iter() {
for entry in entries.iter_mut() {
entry.truncate(max_num_of_columns);
}
headers.push("...".to_owned());
for entry in &mut entries.into_iter() {
for entry in entries.iter_mut() {
entry.push(("...".to_owned(), "c")); // ellipsis is centred
}
}
@ -304,24 +304,17 @@ fn wrap_cells(
max_naive_column_width: usize,
max_column_width: usize,
) -> TableView {
{
let entries = &mut entries;
for head in 0..headers.len() {
if max_per_column[head] > max_naive_column_width {
headers[head] = fill(&headers[head], max_column_width);
for entry in &mut entries.into_iter() {
for entry in entries.iter_mut() {
entry[head].0 = fill(&entry[head].0, max_column_width);
}
}
}
}
TableView {
headers: headers,
entries: entries,
}
TableView { headers, entries }
}
impl RenderView for TableView {

View File

@ -87,11 +87,11 @@ impl Plugin for Format {
}
fn filter(&mut self, input: Value) -> Result<Vec<ReturnValue>, ShellError> {
match &input {
Value {
if let Value {
value: UntaggedValue::Row(dict),
..
} => {
} = &input
{
let mut output = String::new();
for command in &self.commands {
@ -118,8 +118,6 @@ impl Plugin for Format {
UntaggedValue::string(output).into_untagged_value(),
)]);
}
_ => {}
}
Ok(vec![])
}
}

View File

@ -48,12 +48,9 @@ fn column_names(commands: &[ParseCommand]) -> Vec<String> {
let mut output = vec![];
for command in commands {
match command {
ParseCommand::Column(c) => {
if let ParseCommand::Column(c) = command {
output.push(c.clone());
}
_ => {}
}
}
output

View File

@ -94,9 +94,8 @@ impl Shell for FilesystemShell {
let cwd = self.path();
let mut full_path = PathBuf::from(self.path());
match &pattern {
Some(value) => full_path.push((*value).as_ref()),
_ => {}
if let Some(value) = &pattern {
full_path.push((*value).as_ref())
}
let ctrl_c = context.ctrl_c.clone();
@ -350,8 +349,7 @@ impl Shell for FilesystemShell {
let sources = sources.paths_applying_with(strategy)?;
for (ref src, ref dst) in sources {
if src.is_dir() {
if !dst.exists() {
if src.is_dir() && !dst.exists() {
match std::fs::create_dir_all(dst) {
Err(e) => {
return Err(ShellError::labeled_error(
@ -363,7 +361,6 @@ impl Shell for FilesystemShell {
Ok(o) => o,
};
}
}
if src.is_file() {
match std::fs::copy(src, dst) {
@ -424,8 +421,7 @@ impl Shell for FilesystemShell {
let sources = sources.paths_applying_with(strategy)?;
for (ref src, ref dst) in sources {
if src.is_dir() {
if !dst.exists() {
if src.is_dir() && !dst.exists() {
match std::fs::create_dir_all(dst) {
Err(e) => {
return Err(ShellError::labeled_error(
@ -437,7 +433,6 @@ impl Shell for FilesystemShell {
Ok(o) => o,
};
}
}
if src.is_file() {
match std::fs::copy(src, dst) {
@ -455,8 +450,7 @@ impl Shell for FilesystemShell {
}
}
}
} else {
if destination.exists() {
} else if destination.exists() {
if !sources.iter().all(|x| match x {
Ok(f) => f.is_file(),
Err(_) => false,
@ -517,7 +511,6 @@ impl Shell for FilesystemShell {
dst.tag(),
));
}
}
Ok(OutputStream::empty())
}
@ -545,15 +538,13 @@ impl Shell for FilesystemShell {
loc
};
match std::fs::create_dir_all(create_at) {
Err(reason) => {
let dir_res = std::fs::create_dir_all(create_at);
if let Err(reason) = dir_res {
return Err(ShellError::labeled_error(
reason.to_string(),
reason.to_string(),
dir.tag(),
))
}
Ok(_) => {}
));
}
}
@ -859,8 +850,7 @@ impl Shell for FilesystemShell {
}
}
}
} else {
if destination.exists() {
} else if destination.exists() {
let is_file = |x: &Result<PathBuf, _>| {
x.as_ref().map(|entry| entry.is_file()).unwrap_or_default()
};
@ -965,7 +955,6 @@ impl Shell for FilesystemShell {
dst.tag(),
));
}
}
Ok(OutputStream::empty())
}

View File

@ -79,12 +79,12 @@ impl HelpShell {
for p in full_path.iter() {
match p {
x if x == sep => {}
step => match viewed.get_data_by_key(step.to_str().unwrap().spanned_unknown()) {
Some(v) => {
step => {
let value = viewed.get_data_by_key(step.to_str().unwrap().spanned_unknown());
if let Some(v) = value {
viewed = v.clone();
}
_ => {}
},
}
}
}
match viewed {

View File

@ -43,12 +43,12 @@ impl ValueShell {
for p in full_path.iter() {
match p {
x if x == sep => {}
step => match viewed.get_data_by_key(step.to_str().unwrap().spanned_unknown()) {
Some(v) => {
step => {
let value = viewed.get_data_by_key(step.to_str().unwrap().spanned_unknown());
if let Some(v) = value {
viewed = v.clone();
}
_ => {}
},
}
}
}
match viewed {
@ -96,9 +96,8 @@ impl Shell for ValueShell {
let mut full_path = PathBuf::from(self.path());
let name_tag = context.name.clone();
match &target {
Some(value) => full_path.push(value.as_ref()),
_ => {}
if let Some(value) = &target {
full_path.push(value.as_ref());
}
let mut value_system = ValueStructure::new();