Run a round of clippy --fix to fix a ton of lints (#7006)

Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>

Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
This commit is contained in:
Alex Saveau 2022-11-04 13:11:17 -07:00 committed by GitHub
parent f1bde69131
commit be5d71ea47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 51 additions and 53 deletions

View File

@ -60,7 +60,7 @@ impl CommandCompletion {
.matches_str(&x.to_string_lossy(), prefix)), .matches_str(&x.to_string_lossy(), prefix)),
Some(true) Some(true)
) )
&& is_executable::is_executable(&item.path()) && is_executable::is_executable(item.path())
{ {
if let Ok(name) = item.file_name().into_string() { if let Ok(name) = item.file_name().into_string() {
executables.push(name); executables.push(name);

View File

@ -30,7 +30,7 @@ pub fn read_plugin_file(
let plugin_path = engine_state.plugin_signatures.clone(); let plugin_path = engine_state.plugin_signatures.clone();
if let Some(plugin_path) = plugin_path { if let Some(plugin_path) = plugin_path {
let plugin_filename = plugin_path.to_string_lossy().to_owned(); let plugin_filename = plugin_path.to_string_lossy();
if let Ok(contents) = std::fs::read(&plugin_path) { if let Ok(contents) = std::fs::read(&plugin_path) {
eval_source( eval_source(
@ -77,7 +77,7 @@ pub fn eval_config_contents(
stack: &mut Stack, stack: &mut Stack,
) { ) {
if config_path.exists() & config_path.is_file() { if config_path.exists() & config_path.is_file() {
let config_filename = config_path.to_string_lossy().to_owned(); let config_filename = config_path.to_string_lossy();
if let Ok(contents) = std::fs::read(&config_path) { if let Ok(contents) = std::fs::read(&config_path) {
eval_source( eval_source(

View File

@ -372,7 +372,7 @@ impl DescriptionMenu {
let description = self let description = self
.get_value() .get_value()
.and_then(|suggestion| suggestion.description) .and_then(|suggestion| suggestion.description)
.unwrap_or_else(|| "".to_string()) .unwrap_or_default()
.lines() .lines()
.skip(self.skipped_rows) .skip(self.skipped_rows)
.take(self.working_details.description_rows) .take(self.working_details.description_rows)
@ -610,7 +610,7 @@ impl Menu for DescriptionMenu {
let description_rows = self let description_rows = self
.get_value() .get_value()
.and_then(|suggestion| suggestion.description) .and_then(|suggestion| suggestion.description)
.unwrap_or_else(|| "".to_string()) .unwrap_or_default()
.lines() .lines()
.count(); .count();

View File

@ -114,7 +114,7 @@ pub(crate) fn add_menus(
let res = eval_block(&engine_state, &mut temp_stack, &block, input, false, false)?; let res = eval_block(&engine_state, &mut temp_stack, &block, input, false, false)?;
if let PipelineData::Value(value, None) = res { if let PipelineData::Value(value, None) = res {
for menu in create_menus(&value, config)? { for menu in create_menus(&value)? {
line_editor = line_editor =
add_menu(line_editor, &menu, engine_state.clone(), stack, config)?; add_menu(line_editor, &menu, engine_state.clone(), stack, config)?;
} }

View File

@ -164,7 +164,7 @@ pub fn action(input: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value {
span, span,
}, },
Value::Bool { val, .. } => Value::Binary { Value::Bool { val, .. } => Value::Binary {
val: int_to_endian(if *val { 1i64 } else { 0 }), val: int_to_endian(i64::from(*val)),
span, span,
}, },
Value::Date { val, .. } => Value::Binary { Value::Date { val, .. } => Value::Binary {

View File

@ -198,7 +198,7 @@ impl Command for Ls {
} else if full_paths || absolute_path { } else if full_paths || absolute_path {
Some(path.to_string_lossy().to_string()) Some(path.to_string_lossy().to_string())
} else if let Some(prefix) = &prefix { } else if let Some(prefix) = &prefix {
if let Ok(remainder) = path.strip_prefix(&prefix) { if let Ok(remainder) = path.strip_prefix(prefix) {
if directory { if directory {
// When the path is the same as the cwd, path_diff should be "." // When the path is the same as the cwd, path_diff should be "."
let path_diff = let path_diff =
@ -215,7 +215,7 @@ impl Command for Ls {
Some(path_diff) Some(path_diff)
} else { } else {
let new_prefix = if let Some(pfx) = diff_paths(&prefix, &cwd) { let new_prefix = if let Some(pfx) = diff_paths(prefix, &cwd) {
pfx pfx
} else { } else {
prefix.to_path_buf() prefix.to_path_buf()

View File

@ -295,7 +295,7 @@ fn move_file(
fn move_item(from: &Path, from_span: Span, to: &Path) -> Result<(), ShellError> { fn move_item(from: &Path, from_span: Span, to: &Path) -> Result<(), ShellError> {
// We first try a rename, which is a quick operation. If that doesn't work, we'll try a copy // We first try a rename, which is a quick operation. If that doesn't work, we'll try a copy
// and remove the old file/folder. This is necessary if we're moving across filesystems or devices. // and remove the old file/folder. This is necessary if we're moving across filesystems or devices.
std::fs::rename(&from, &to).or_else(|_| { std::fs::rename(from, to).or_else(|_| {
match if from.is_file() { match if from.is_file() {
let mut options = fs_extra::file::CopyOptions::new(); let mut options = fs_extra::file::CopyOptions::new();
options.overwrite = true; options.overwrite = true;

View File

@ -97,7 +97,7 @@ impl Command for Open {
let path_no_whitespace = &path.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d')); let path_no_whitespace = &path.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d'));
let path = Path::new(path_no_whitespace); let path = Path::new(path_no_whitespace);
if permission_denied(&path) { if permission_denied(path) {
#[cfg(unix)] #[cfg(unix)]
let error_msg = match path.metadata() { let error_msg = match path.metadata() {
Ok(md) => format!( Ok(md) => format!(

View File

@ -284,8 +284,8 @@ fn rm(
} }
Ok(all_targets Ok(all_targets
.into_iter() .into_keys()
.map(move |(f, _)| { .map(move |f| {
let is_empty = || match f.read_dir() { let is_empty = || match f.read_dir() {
Ok(mut p) => p.next().is_none(), Ok(mut p) => p.next().is_none(),
Err(_) => false, Err(_) => false,

View File

@ -72,7 +72,7 @@ impl Command for Watch {
.item .item
.trim_end_matches(|x| matches!(x, '\x09'..='\x0d')); .trim_end_matches(|x| matches!(x, '\x09'..='\x0d'));
let path = match nu_path::canonicalize_with(path_no_whitespace, &cwd) { let path = match nu_path::canonicalize_with(path_no_whitespace, cwd) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
return Err(ShellError::DirectoryNotFound( return Err(ShellError::DirectoryNotFound(

View File

@ -210,7 +210,7 @@ pub fn data_group(
value.as_string() value.as_string()
}; };
let group = groups.entry(group_key?).or_insert(vec![]); let group = groups.entry(group_key?).or_default();
group.push(value); group.push(value);
} }

View File

@ -141,7 +141,7 @@ fn parse_aligned_columns<'a>(
let parse_without_headers = |ls: Vec<&str>| { let parse_without_headers = |ls: Vec<&str>| {
let mut indices = ls let mut indices = ls
.iter() .iter()
.flat_map(|s| find_indices(*s)) .flat_map(|s| find_indices(s))
.collect::<Vec<usize>>(); .collect::<Vec<usize>>();
indices.sort_unstable(); indices.sort_unstable();

View File

@ -284,9 +284,7 @@ pub fn run_seq(
} }
} }
}; };
if largest_dec > 0 { largest_dec = largest_dec.saturating_sub(1);
largest_dec -= 1;
}
let separator = escape_sequences(&sep[..]); let separator = escape_sequences(&sep[..]);
let terminator = match termy { let terminator = match termy {
Some(term) => escape_sequences(&term[..]), Some(term) => escape_sequences(&term[..]),

View File

@ -96,7 +96,7 @@ pub fn median(values: &[Value], head: &Span) -> Result<Value, ShellError> {
Ok(out.clone()) Ok(out.clone())
} }
Pick::MedianAverage => { Pick::MedianAverage => {
let idx_end = (values.len() / 2) as usize; let idx_end = values.len() / 2;
let idx_start = idx_end - 1; let idx_start = idx_end - 1;
let left = sorted let left = sorted

View File

@ -376,8 +376,8 @@ fn helper(
let headers = args.headers; let headers = args.headers;
let raw = args.raw; let raw = args.raw;
let login = match (user, password) { let login = match (user, password) {
(Some(user), Some(password)) => Some(encode(&format!("{}:{}", user, password))), (Some(user), Some(password)) => Some(encode(format!("{}:{}", user, password))),
(Some(user), _) => Some(encode(&format!("{}:", user))), (Some(user), _) => Some(encode(format!("{}:", user))),
_ => None, _ => None,
}; };

View File

@ -115,7 +115,7 @@ fn action(
} => { } => {
match base64_config.action_type { match base64_config.action_type {
ActionType::Encode => { ActionType::Encode => {
Value::string(encode_config(&val, base64_config_enum), command_span) Value::string(encode_config(val, base64_config_enum), command_span)
} }
ActionType::Decode => { ActionType::Decode => {

View File

@ -548,7 +548,7 @@ impl ExternalCommand {
.to_string_lossy() .to_string_lossy()
.to_string(); .to_string();
let mut process = std::process::Command::new(&head); let mut process = std::process::Command::new(head);
for (arg, arg_keep_raw) in self.args.iter().zip(self.arg_keep_raw.iter()) { for (arg, arg_keep_raw) in self.args.iter().zip(self.arg_keep_raw.iter()) {
// if arg is quoted, like "aa", 'aa', `aa`, or: // if arg is quoted, like "aa", 'aa', `aa`, or:

View File

@ -529,7 +529,7 @@ fn list_directory_contains_invalid_utf8() {
let cwd = dirs.test(); let cwd = dirs.test();
let path = cwd.join(s); let path = cwd.join(s);
std::fs::create_dir_all(&path).expect("failed to create directory"); std::fs::create_dir_all(path).expect("failed to create directory");
let actual = nu!(cwd: cwd, "ls"); let actual = nu!(cwd: cwd, "ls");

View File

@ -279,7 +279,7 @@ pub fn find_in_dirs_env(
for lib_dir in dirs { for lib_dir in dirs {
if let Ok(dir) = lib_dir.as_path() { if let Ok(dir) = lib_dir.as_path() {
// make sure the dir is absolute path // make sure the dir is absolute path
if let Ok(dir_abs) = canonicalize_with(&dir, &cwd) { if let Ok(dir_abs) = canonicalize_with(dir, &cwd) {
if let Ok(path) = canonicalize_with(filename, dir_abs) { if let Ok(path) = canonicalize_with(filename, dir_abs) {
return Ok(Some(path)); return Ok(Some(path));
} }

View File

@ -41,7 +41,7 @@ pub fn glob_from(
} }
(Some(p), path) (Some(p), path)
} else { } else {
let path = if let Ok(p) = canonicalize_with(path, &cwd) { let path = if let Ok(p) = canonicalize_with(path, cwd) {
p p
} else { } else {
return Err(ShellError::DirectoryNotFound(pattern.span, None)); return Err(ShellError::DirectoryNotFound(pattern.span, None));

View File

@ -335,7 +335,7 @@ impl Iterator for Paths {
if let Some(scope) = self.scope.take() { if let Some(scope) = self.scope.take() {
if !self.dir_patterns.is_empty() { if !self.dir_patterns.is_empty() {
// Shouldn't happen, but we're using -1 as a special index. // Shouldn't happen, but we're using -1 as a special index.
assert!(self.dir_patterns.len() < !0 as usize); assert!(self.dir_patterns.len() < !0);
fill_todo(&mut self.todo, &self.dir_patterns, 0, &scope, self.options); fill_todo(&mut self.todo, &self.dir_patterns, 0, &scope, self.options);
} }
@ -357,7 +357,7 @@ impl Iterator for Paths {
// idx -1: was already checked by fill_todo, maybe path was '.' or // idx -1: was already checked by fill_todo, maybe path was '.' or
// '..' that we can't match here because of normalization. // '..' that we can't match here because of normalization.
if idx == !0 as usize { if idx == !0 {
if self.require_dir && !is_dir(&path) { if self.require_dir && !is_dir(&path) {
continue; continue;
} }
@ -771,7 +771,7 @@ fn fill_todo(
// We know it's good, so don't make the iterator match this path // We know it's good, so don't make the iterator match this path
// against the pattern again. In particular, it can't match // against the pattern again. In particular, it can't match
// . or .. globs since these never show up as path components. // . or .. globs since these never show up as path components.
todo.push(Ok((next_path, !0 as usize))); todo.push(Ok((next_path, !0)));
} else { } else {
fill_todo(todo, patterns, idx + 1, &next_path, options); fill_todo(todo, patterns, idx + 1, &next_path, options);
} }
@ -1222,7 +1222,7 @@ mod test {
#[test] #[test]
fn test_path_join() { fn test_path_join() {
let pattern = Path::new("one").join(&Path::new("**/*.rs")); let pattern = Path::new("one").join(Path::new("**/*.rs"));
assert!(Pattern::new(pattern.to_str().unwrap()).is_ok()); assert!(Pattern::new(pattern.to_str().unwrap()).is_ok());
} }
} }

View File

@ -469,7 +469,7 @@ where
let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32)
+ 0x1_0000; + 0x1_0000;
match char::from_u32(n as u32) { match char::from_u32(n) {
Some(c) => c, Some(c) => c,
None => { None => {
return Err(self return Err(self

View File

@ -3252,7 +3252,7 @@ pub fn find_in_dirs(
for lib_dir in dirs { for lib_dir in dirs {
if let Ok(dir) = lib_dir.as_path() { if let Ok(dir) = lib_dir.as_path() {
// make sure the dir is absolute path // make sure the dir is absolute path
if let Ok(dir_abs) = canonicalize_with(&dir, actual_cwd) { if let Ok(dir_abs) = canonicalize_with(dir, actual_cwd) {
if let Ok(path) = canonicalize_with(filename, dir_abs) { if let Ok(path) = canonicalize_with(filename, dir_abs) {
return Some(path); return Some(path);
} }

View File

@ -157,7 +157,7 @@ mod tests {
fn check_expanded(s: &str) { fn check_expanded(s: &str) {
let home = Path::new("/home"); let home = Path::new("/home");
let buf = Some(PathBuf::from(home)); let buf = Some(PathBuf::from(home));
assert!(expand_tilde_with_home(Path::new(s), buf).starts_with(&home)); assert!(expand_tilde_with_home(Path::new(s), buf).starts_with(home));
// Tests the special case in expand_tilde for "/" as home // Tests the special case in expand_tilde for "/" as home
let home = Path::new("/"); let home = Path::new("/");

View File

@ -174,7 +174,7 @@ where
.iter() .iter()
.skip(skip) .skip(skip)
.take(amount) .take(amount)
.map(|&x| x as u8) .copied()
.collect(); .collect();
if cfg.title { if cfg.title {

View File

@ -347,14 +347,14 @@ impl Value {
eprintln!("$config.log_level is not a string") eprintln!("$config.log_level is not a string")
} }
} }
"menus" => match create_menus(value, &config) { "menus" => match create_menus(value) {
Ok(map) => config.menus = map, Ok(map) => config.menus = map,
Err(e) => { Err(e) => {
eprintln!("$config.menus is not a valid list of menus"); eprintln!("$config.menus is not a valid list of menus");
eprintln!("{:?}", e); eprintln!("{:?}", e);
} }
}, },
"keybindings" => match create_keybindings(value, &config) { "keybindings" => match create_keybindings(value) {
Ok(keybindings) => config.keybindings = keybindings, Ok(keybindings) => config.keybindings = keybindings,
Err(e) => { Err(e) => {
eprintln!("$config.keybindings is not a valid keybindings list"); eprintln!("$config.keybindings is not a valid keybindings list");
@ -599,7 +599,7 @@ fn create_hooks(value: &Value) -> Result<Hooks, ShellError> {
} }
// Parses the config object to extract the strings that will compose a keybinding for reedline // Parses the config object to extract the strings that will compose a keybinding for reedline
fn create_keybindings(value: &Value, config: &Config) -> Result<Vec<ParsedKeybinding>, ShellError> { fn create_keybindings(value: &Value) -> Result<Vec<ParsedKeybinding>, ShellError> {
match value { match value {
Value::Record { cols, vals, span } => { Value::Record { cols, vals, span } => {
// Finding the modifier value in the record // Finding the modifier value in the record
@ -621,7 +621,7 @@ fn create_keybindings(value: &Value, config: &Config) -> Result<Vec<ParsedKeybin
Value::List { vals, .. } => { Value::List { vals, .. } => {
let res = vals let res = vals
.iter() .iter()
.map(|inner_value| create_keybindings(inner_value, config)) .map(create_keybindings)
.collect::<Result<Vec<Vec<ParsedKeybinding>>, ShellError>>(); .collect::<Result<Vec<Vec<ParsedKeybinding>>, ShellError>>();
let res = res? let res = res?
@ -636,7 +636,7 @@ fn create_keybindings(value: &Value, config: &Config) -> Result<Vec<ParsedKeybin
} }
// Parses the config object to extract the strings that will compose a keybinding for reedline // Parses the config object to extract the strings that will compose a keybinding for reedline
pub fn create_menus(value: &Value, config: &Config) -> Result<Vec<ParsedMenu>, ShellError> { pub fn create_menus(value: &Value) -> Result<Vec<ParsedMenu>, ShellError> {
match value { match value {
Value::Record { cols, vals, span } => { Value::Record { cols, vals, span } => {
// Finding the modifier value in the record // Finding the modifier value in the record
@ -667,7 +667,7 @@ pub fn create_menus(value: &Value, config: &Config) -> Result<Vec<ParsedMenu>, S
Value::List { vals, .. } => { Value::List { vals, .. } => {
let res = vals let res = vals
.iter() .iter()
.map(|inner_value| create_menus(inner_value, config)) .map(create_menus)
.collect::<Result<Vec<Vec<ParsedMenu>>, ShellError>>(); .collect::<Result<Vec<Vec<ParsedMenu>>, ShellError>>();
let res = res?.into_iter().flatten().collect::<Vec<ParsedMenu>>(); let res = res?.into_iter().flatten().collect::<Vec<ParsedMenu>>();

View File

@ -25,11 +25,11 @@ impl FromValue for Spanned<i64> {
span: *span, span: *span,
}), }),
Value::Filesize { val, span } => Ok(Spanned { Value::Filesize { val, span } => Ok(Spanned {
item: *val as i64, item: *val,
span: *span, span: *span,
}), }),
Value::Duration { val, span } => Ok(Spanned { Value::Duration { val, span } => Ok(Spanned {
item: *val as i64, item: *val,
span: *span, span: *span,
}), }),
@ -47,8 +47,8 @@ impl FromValue for i64 {
fn from_value(v: &Value) -> Result<Self, ShellError> { fn from_value(v: &Value) -> Result<Self, ShellError> {
match v { match v {
Value::Int { val, .. } => Ok(*val), Value::Int { val, .. } => Ok(*val),
Value::Filesize { val, .. } => Ok(*val as i64), Value::Filesize { val, .. } => Ok(*val),
Value::Duration { val, .. } => Ok(*val as i64), Value::Duration { val, .. } => Ok(*val),
v => Err(ShellError::CantConvert( v => Err(ShellError::CantConvert(
"integer".into(), "integer".into(),

View File

@ -157,7 +157,7 @@ impl ProcessInfo {
pub fn command(&self) -> String { pub fn command(&self) -> String {
if let Ok(cmd) = &self.curr_proc.cmdline() { if let Ok(cmd) = &self.curr_proc.cmdline() {
if !cmd.is_empty() { if !cmd.is_empty() {
cmd.join(" ").replace('\n', " ").replace('\t', " ") cmd.join(" ").replace(['\n', '\t'], " ")
} else { } else {
match self.curr_proc.stat() { match self.curr_proc.stat() {
Ok(p) => p.comm, Ok(p) => p.comm,
@ -200,8 +200,8 @@ impl ProcessInfo {
let curr_time = cs.utime + cs.stime; let curr_time = cs.utime + cs.stime;
let prev_time = ps.utime + ps.stime; let prev_time = ps.utime + ps.stime;
let usage_ms = (curr_time - prev_time) * 1000 let usage_ms =
/ procfs::ticks_per_second().unwrap_or(100) as u64; (curr_time - prev_time) * 1000 / procfs::ticks_per_second().unwrap_or(100);
let interval_ms = let interval_ms =
self.interval.as_secs() * 1000 + u64::from(self.interval.subsec_millis()); self.interval.as_secs() * 1000 + u64::from(self.interval.subsec_millis());
usage_ms as f64 * 100.0 / interval_ms as f64 usage_ms as f64 * 100.0 / interval_ms as f64

View File

@ -230,7 +230,7 @@ fn override_alignments(
index_present: bool, index_present: bool,
alignments: Alignments, alignments: Alignments,
) { ) {
let offset = if header_present { 1 } else { 0 }; let offset = usize::from(header_present);
let (count_rows, count_columns) = table.shape(); let (count_rows, count_columns) = table.shape();
for row in offset..count_rows { for row in offset..count_rows {
for col in 0..count_columns { for col in 0..count_columns {

View File

@ -131,7 +131,7 @@ pub struct Cell {
impl From<String> for Cell { impl From<String> for Cell {
fn from(string: String) -> Self { fn from(string: String) -> Self {
Self { Self {
width: unicode_width_strip_ansi(&*string), width: unicode_width_strip_ansi(&string),
contents: string, contents: string,
alignment: Alignment::Left, alignment: Alignment::Left,
} }

View File

@ -74,7 +74,7 @@ impl NuProcess {
} }
pub fn construct(&self) -> Command { pub fn construct(&self) -> Command {
let mut command = Command::new(&executable_path()); let mut command = Command::new(executable_path());
if let Some(cwd) = self.get_cwd() { if let Some(cwd) = self.get_cwd() {
command.current_dir(cwd); command.current_dir(cwd);
@ -84,7 +84,7 @@ impl NuProcess {
let paths = vec![test_bins_path()]; let paths = vec![test_bins_path()];
let paths_joined = match std::env::join_paths(&paths) { let paths_joined = match std::env::join_paths(paths) {
Ok(all) => all, Ok(all) => all,
Err(_) => panic!("Couldn't join paths for PATH var."), Err(_) => panic!("Couldn't join paths for PATH var."),
}; };

View File

@ -32,7 +32,7 @@ fn expand_path_no_change() {
let path = "/foo/bar"; let path = "/foo/bar";
let cwd = std::env::current_dir().expect("Could not get current directory"); let cwd = std::env::current_dir().expect("Could not get current directory");
let actual = expand_path_with(&path, cwd); let actual = expand_path_with(path, cwd);
assert_eq!(actual, PathBuf::from(path)); assert_eq!(actual, PathBuf::from(path));
} }