From 97d12d6e3c7b8afcde13555e34e35545b7f0a96a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Reto=20Habl=C3=BCtzel?= Date: Sun, 11 Apr 2021 16:05:25 +0200 Subject: [PATCH] fix trivial warnings without features --- src/uu/basename/src/basename.rs | 10 +-- src/uu/cp/src/cp.rs | 16 ++--- src/uu/cut/src/cut.rs | 66 +++++++++---------- src/uu/du/src/du.rs | 2 +- src/uu/expr/src/expr.rs | 2 +- src/uu/expr/src/syntax_tree.rs | 36 +++++----- src/uu/fmt/src/parasplit.rs | 2 +- src/uu/fold/src/fold.rs | 2 +- src/uu/head/src/head.rs | 2 +- src/uu/ln/src/ln.rs | 14 ++-- src/uu/ls/src/ls.rs | 8 +-- src/uu/mv/src/mv.rs | 16 ++--- src/uu/od/src/od.rs | 2 +- src/uu/od/src/parse_inputs.rs | 6 +- .../num_format/formatters/base_conv/mod.rs | 6 +- src/uu/readlink/src/readlink.rs | 6 +- src/uu/realpath/src/realpath.rs | 4 +- src/uu/rm/src/rm.rs | 2 +- src/uu/seq/src/seq.rs | 8 +-- src/uu/shred/src/shred.rs | 10 ++- src/uu/sum/src/sum.rs | 2 +- src/uu/tac/src/tac.rs | 2 +- src/uu/test/src/test.rs | 24 +++---- src/uu/tr/src/expand.rs | 2 +- src/uu/tsort/src/tsort.rs | 17 +++-- src/uu/wc/src/count_bytes.rs | 31 ++++----- src/uu/wc/src/wc.rs | 19 +++--- 27 files changed, 151 insertions(+), 166 deletions(-) diff --git a/src/uu/basename/src/basename.rs b/src/uu/basename/src/basename.rs index 84521bdd1..b7f99af27 100644 --- a/src/uu/basename/src/basename.rs +++ b/src/uu/basename/src/basename.rs @@ -113,12 +113,8 @@ fn basename(fullname: &str, suffix: &str) -> String { fn strip_suffix(name: &str, suffix: &str) -> String { if name == suffix { - return name.to_owned(); + name.to_owned() + } else { + name.strip_suffix(suffix).unwrap_or(name).to_owned() } - - if name.ends_with(suffix) { - return name[..name.len() - suffix.len()].to_owned(); - } - - name.to_owned() } diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 569ee78bc..60484a79a 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -547,14 +547,13 @@ impl FromStr for Attribute { } fn add_all_attributes() -> Vec { - let mut attr = Vec::new(); + use Attribute::*; + + let mut attr = vec![Ownership, Timestamps, Context, Xattr, Links]; + #[cfg(unix)] - attr.push(Attribute::Mode); - attr.push(Attribute::Ownership); - attr.push(Attribute::Timestamps); - attr.push(Attribute::Context); - attr.push(Attribute::Xattr); - attr.push(Attribute::Links); + attr.insert(0, Mode); + attr } @@ -714,7 +713,7 @@ fn parse_path_args(path_args: &[String], options: &Options) -> CopyResult<(Vec, - source: &std::path::PathBuf, + source: &std::path::Path, dest: std::path::PathBuf, found_hard_link: &mut bool, ) -> CopyResult<()> { @@ -1068,6 +1067,7 @@ fn copy_attribute(source: &Path, dest: &Path, attribute: &Attribute) -> CopyResu } #[cfg(not(windows))] +#[allow(clippy::unnecessary_wraps)] // needed for windows version fn symlink_file(source: &Path, dest: &Path, context: &str) -> CopyResult<()> { match std::os::unix::fs::symlink(source, dest).context(context) { Ok(_) => Ok(()), diff --git a/src/uu/cut/src/cut.rs b/src/uu/cut/src/cut.rs index 6b09b91d9..5bf310daa 100644 --- a/src/uu/cut/src/cut.rs +++ b/src/uu/cut/src/cut.rs @@ -406,7 +406,7 @@ fn cut_files(mut filenames: Vec, mode: Mode) -> i32 { continue; } - if !path.metadata().is_ok() { + if path.metadata().is_err() { show_error!("{}: No such file or directory", filename); continue; } @@ -487,7 +487,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { .help("filter field columns from the input source") .takes_value(true) .allow_hyphen_values(true) - .value_name("LIST") + .value_name("LIST") .display_order(4), ) .arg( @@ -535,40 +535,36 @@ pub fn uumain(args: impl uucore::Args) -> i32 { matches.value_of(options::CHARACTERS), matches.value_of(options::FIELDS), ) { - (Some(byte_ranges), None, None) => { - list_to_ranges(&byte_ranges[..], complement).map(|ranges| { - Mode::Bytes( - ranges, - Options { - out_delim: Some( - matches - .value_of(options::OUTPUT_DELIMITER) - .unwrap_or_default() - .to_owned(), - ), - zero_terminated: matches.is_present(options::ZERO_TERMINATED), - }, - ) - }) - } - (None, Some(char_ranges), None) => { - list_to_ranges(&char_ranges[..], complement).map(|ranges| { - Mode::Characters( - ranges, - Options { - out_delim: Some( - matches - .value_of(options::OUTPUT_DELIMITER) - .unwrap_or_default() - .to_owned(), - ), - zero_terminated: matches.is_present(options::ZERO_TERMINATED), - }, - ) - }) - } + (Some(byte_ranges), None, None) => list_to_ranges(byte_ranges, complement).map(|ranges| { + Mode::Bytes( + ranges, + Options { + out_delim: Some( + matches + .value_of(options::OUTPUT_DELIMITER) + .unwrap_or_default() + .to_owned(), + ), + zero_terminated: matches.is_present(options::ZERO_TERMINATED), + }, + ) + }), + (None, Some(char_ranges), None) => list_to_ranges(char_ranges, complement).map(|ranges| { + Mode::Characters( + ranges, + Options { + out_delim: Some( + matches + .value_of(options::OUTPUT_DELIMITER) + .unwrap_or_default() + .to_owned(), + ), + zero_terminated: matches.is_present(options::ZERO_TERMINATED), + }, + ) + }), (None, None, Some(field_ranges)) => { - list_to_ranges(&field_ranges[..], complement).and_then(|ranges| { + list_to_ranges(field_ranges, complement).and_then(|ranges| { let out_delim = match matches.value_of(options::OUTPUT_DELIMITER) { Some(s) => { if s.is_empty() { diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index 615b66a4e..07635881a 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -322,7 +322,7 @@ fn convert_size_human(size: u64, multiplier: u64, _block_size: u64) -> String { } } if size == 0 { - return format!("0"); + return "0".to_string(); } format!("{}B", size) } diff --git a/src/uu/expr/src/expr.rs b/src/uu/expr/src/expr.rs index fee85dfe1..4a13812d3 100644 --- a/src/uu/expr/src/expr.rs +++ b/src/uu/expr/src/expr.rs @@ -51,7 +51,7 @@ fn print_expr_error(expr_error: &str) -> ! { crash!(2, "{}", expr_error) } -fn evaluate_ast(maybe_ast: Result, String>) -> Result { +fn evaluate_ast(maybe_ast: Result, String>) -> Result { if maybe_ast.is_err() { Err(maybe_ast.err().unwrap()) } else { diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index 3381c29bd..c81adf0c8 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -17,10 +17,10 @@ use onig::{Regex, RegexOptions, Syntax}; use crate::tokens::Token; type TokenStack = Vec<(usize, Token)>; -pub type OperandsList = Vec>; +pub type OperandsList = Vec>; #[derive(Debug)] -pub enum ASTNode { +pub enum AstNode { Leaf { token_idx: usize, value: String, @@ -31,7 +31,7 @@ pub enum ASTNode { operands: OperandsList, }, } -impl ASTNode { +impl AstNode { fn debug_dump(&self) { self.debug_dump_impl(1); } @@ -40,7 +40,7 @@ impl ASTNode { print!("\t",); } match *self { - ASTNode::Leaf { + AstNode::Leaf { ref token_idx, ref value, } => println!( @@ -49,7 +49,7 @@ impl ASTNode { token_idx, self.evaluate() ), - ASTNode::Node { + AstNode::Node { ref token_idx, ref op_type, ref operands, @@ -67,23 +67,23 @@ impl ASTNode { } } - fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box { - Box::new(ASTNode::Node { + fn new_node(token_idx: usize, op_type: &str, operands: OperandsList) -> Box { + Box::new(AstNode::Node { token_idx, op_type: op_type.into(), operands, }) } - fn new_leaf(token_idx: usize, value: &str) -> Box { - Box::new(ASTNode::Leaf { + fn new_leaf(token_idx: usize, value: &str) -> Box { + Box::new(AstNode::Leaf { token_idx, value: value.into(), }) } pub fn evaluate(&self) -> Result { match *self { - ASTNode::Leaf { ref value, .. } => Ok(value.clone()), - ASTNode::Node { ref op_type, .. } => match self.operand_values() { + AstNode::Leaf { ref value, .. } => Ok(value.clone()), + AstNode::Node { ref op_type, .. } => match self.operand_values() { Err(reason) => Err(reason), Ok(operand_values) => match op_type.as_ref() { "+" => infix_operator_two_ints( @@ -161,7 +161,7 @@ impl ASTNode { } } pub fn operand_values(&self) -> Result, String> { - if let ASTNode::Node { ref operands, .. } = *self { + if let AstNode::Node { ref operands, .. } = *self { let mut out = Vec::with_capacity(operands.len()); for operand in operands { match operand.evaluate() { @@ -178,7 +178,7 @@ impl ASTNode { pub fn tokens_to_ast( maybe_tokens: Result, String>, -) -> Result, String> { +) -> Result, String> { if maybe_tokens.is_err() { Err(maybe_tokens.err().unwrap()) } else { @@ -212,7 +212,7 @@ pub fn tokens_to_ast( } } -fn maybe_dump_ast(result: &Result, String>) { +fn maybe_dump_ast(result: &Result, String>) { use std::env; if let Ok(debug_var) = env::var("EXPR_DEBUG_AST") { if debug_var == "1" { @@ -238,11 +238,11 @@ fn maybe_dump_rpn(rpn: &TokenStack) { } } -fn ast_from_rpn(rpn: &mut TokenStack) -> Result, String> { +fn ast_from_rpn(rpn: &mut TokenStack) -> Result, String> { match rpn.pop() { None => Err("syntax error (premature end of expression)".to_owned()), - Some((token_idx, Token::Value { value })) => Ok(ASTNode::new_leaf(token_idx, &value)), + Some((token_idx, Token::Value { value })) => Ok(AstNode::new_leaf(token_idx, &value)), Some((token_idx, Token::InfixOp { value, .. })) => { maybe_ast_node(token_idx, &value, 2, rpn) @@ -262,7 +262,7 @@ fn maybe_ast_node( op_type: &str, arity: usize, rpn: &mut TokenStack, -) -> Result, String> { +) -> Result, String> { let mut operands = Vec::with_capacity(arity); for _ in 0..arity { match ast_from_rpn(rpn) { @@ -271,7 +271,7 @@ fn maybe_ast_node( } } operands.reverse(); - Ok(ASTNode::new_node(token_idx, op_type, operands)) + Ok(AstNode::new_node(token_idx, op_type, operands)) } fn move_rest_of_ops_to_out( diff --git a/src/uu/fmt/src/parasplit.rs b/src/uu/fmt/src/parasplit.rs index f74a25413..950b3f66d 100644 --- a/src/uu/fmt/src/parasplit.rs +++ b/src/uu/fmt/src/parasplit.rs @@ -267,7 +267,7 @@ impl<'a> ParagraphStream<'a> { #[allow(clippy::match_like_matches_macro)] // `matches!(...)` macro not stabilized until rust v1.42 l_slice[..colon_posn].chars().all(|x| match x as usize { - y if y < 33 || y > 126 => false, + y if !(33..=126).contains(&y) => false, _ => true, }) } diff --git a/src/uu/fold/src/fold.rs b/src/uu/fold/src/fold.rs index c35e996f2..fa703eade 100644 --- a/src/uu/fold/src/fold.rs +++ b/src/uu/fold/src/fold.rs @@ -66,7 +66,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { .takes_value(true), ) .arg(Arg::with_name(options::FILE).hidden(true).multiple(true)) - .get_matches_from(args.clone()); + .get_matches_from(args); let bytes = matches.is_present(options::BYTES); let spaces = matches.is_present(options::SPACES); diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index 3500af544..807d04314 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -625,7 +625,7 @@ mod tests { assert_eq!(arg_outputs("head"), Ok("head".to_owned())); } #[test] - #[cfg(linux)] + #[cfg(target_os = "linux")] fn test_arg_iterate_bad_encoding() { let invalid = unsafe { std::str::from_utf8_unchecked(b"\x80\x81") }; // this arises from a conversion from OsString to &str diff --git a/src/uu/ln/src/ln.rs b/src/uu/ln/src/ln.rs index 96a0df813..04358a415 100644 --- a/src/uu/ln/src/ln.rs +++ b/src/uu/ln/src/ln.rs @@ -303,7 +303,7 @@ fn exec(files: &[PathBuf], settings: &Settings) -> i32 { } } -fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Settings) -> i32 { +fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings) -> i32 { if !target_dir.is_dir() { show_error!("target '{}' is not a directory", target_dir.display()); return 1; @@ -329,7 +329,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting }; } } - target_dir.clone() + target_dir.to_path_buf() } else { match srcpath.as_os_str().to_str() { Some(name) => { @@ -370,7 +370,7 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting } } -fn relative_path<'a>(src: &PathBuf, dst: &PathBuf) -> Result> { +fn relative_path<'a>(src: &Path, dst: &Path) -> Result> { let abssrc = canonicalize(src, CanonicalizeMode::Normal)?; let absdst = canonicalize(dst, CanonicalizeMode::Normal)?; let suffix_pos = abssrc @@ -390,7 +390,7 @@ fn relative_path<'a>(src: &PathBuf, dst: &PathBuf) -> Result> { Ok(result.into()) } -fn link(src: &PathBuf, dst: &PathBuf, settings: &Settings) -> Result<()> { +fn link(src: &Path, dst: &Path, settings: &Settings) -> Result<()> { let mut backup_path = None; let source: Cow<'_, Path> = if settings.relative { relative_path(&src, dst)? @@ -453,13 +453,13 @@ fn read_yes() -> bool { } } -fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { +fn simple_backup_path(path: &Path, suffix: &str) -> PathBuf { let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); PathBuf::from(p) } -fn numbered_backup_path(path: &PathBuf) -> PathBuf { +fn numbered_backup_path(path: &Path) -> PathBuf { let mut i: u64 = 1; loop { let new_path = simple_backup_path(path, &format!(".~{}~", i)); @@ -470,7 +470,7 @@ fn numbered_backup_path(path: &PathBuf) -> PathBuf { } } -fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { +fn existing_backup_path(path: &Path, suffix: &str) -> PathBuf { let test_path = simple_backup_path(path, &".~1~".to_owned()); if test_path.exists() { return numbered_backup_path(path); diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index fdc11144a..4024328b5 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -1076,7 +1076,7 @@ fn should_display(entry: &DirEntry, config: &Config) -> bool { true } -fn enter_directory(dir: &PathBuf, config: &Config) { +fn enter_directory(dir: &Path, config: &Config) { let mut entries: Vec<_> = safe_unwrap!(fs::read_dir(dir).and_then(Iterator::collect)); entries.retain(|e| should_display(e, config)); @@ -1101,7 +1101,7 @@ fn enter_directory(dir: &PathBuf, config: &Config) { } } -fn get_metadata(entry: &PathBuf, config: &Config) -> std::io::Result { +fn get_metadata(entry: &Path, config: &Config) -> std::io::Result { if config.dereference { entry.metadata().or_else(|_| entry.symlink_metadata()) } else { @@ -1109,7 +1109,7 @@ fn get_metadata(entry: &PathBuf, config: &Config) -> std::io::Result { } } -fn display_dir_entry_size(entry: &PathBuf, config: &Config) -> (usize, usize) { +fn display_dir_entry_size(entry: &Path, config: &Config) -> (usize, usize) { if let Ok(md) = get_metadata(entry, config) { ( display_symlink_count(&md).len(), @@ -1204,7 +1204,7 @@ fn display_grid(names: impl Iterator, width: u16, direction: Direct use uucore::fs::display_permissions; fn display_item_long( - item: &PathBuf, + item: &Path, strip: Option<&Path>, max_links: usize, max_size: usize, diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index b481aeebc..f57178a09 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -335,7 +335,7 @@ fn exec(files: &[PathBuf], b: Behavior) -> i32 { 0 } -fn move_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behavior) -> i32 { +fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, b: &Behavior) -> i32 { if !target_dir.is_dir() { show_error!("target ‘{}’ is not a directory", target_dir.display()); return 1; @@ -373,7 +373,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behavior) -> } } -fn rename(from: &PathBuf, to: &PathBuf, b: &Behavior) -> io::Result<()> { +fn rename(from: &Path, to: &Path, b: &Behavior) -> io::Result<()> { let mut backup_path = None; if to.exists() { @@ -429,7 +429,7 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behavior) -> io::Result<()> { /// A wrapper around `fs::rename`, so that if it fails, we try falling back on /// copying and removing. -fn rename_with_fallback(from: &PathBuf, to: &PathBuf) -> io::Result<()> { +fn rename_with_fallback(from: &Path, to: &Path) -> io::Result<()> { if fs::rename(from, to).is_err() { // Get metadata without following symlinks let metadata = from.symlink_metadata()?; @@ -464,7 +464,7 @@ fn rename_with_fallback(from: &PathBuf, to: &PathBuf) -> io::Result<()> { /// Move the given symlink to the given destination. On Windows, dangling /// symlinks return an error. #[inline] -fn rename_symlink_fallback(from: &PathBuf, to: &PathBuf) -> io::Result<()> { +fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { let path_symlink_points_to = fs::read_link(from)?; #[cfg(unix)] { @@ -507,20 +507,20 @@ fn read_yes() -> bool { } } -fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { +fn simple_backup_path(path: &Path, suffix: &str) -> PathBuf { let mut p = path.to_string_lossy().into_owned(); p.push_str(suffix); PathBuf::from(p) } -fn numbered_backup_path(path: &PathBuf) -> PathBuf { +fn numbered_backup_path(path: &Path) -> PathBuf { (1_u64..) .map(|i| path.with_extension(format!("~{}~", i))) .find(|p| !p.exists()) .expect("cannot create backup") } -fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { +fn existing_backup_path(path: &Path, suffix: &str) -> PathBuf { let test_path = path.with_extension("~1~"); if test_path.exists() { numbered_backup_path(path) @@ -529,7 +529,7 @@ fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { } } -fn is_empty_dir(path: &PathBuf) -> bool { +fn is_empty_dir(path: &Path) -> bool { match fs::read_dir(path) { Ok(contents) => contents.peekable().peek().is_none(), Err(_e) => false, diff --git a/src/uu/od/src/od.rs b/src/uu/od/src/od.rs index c3b39fca1..36eae66ab 100644 --- a/src/uu/od/src/od.rs +++ b/src/uu/od/src/od.rs @@ -118,7 +118,7 @@ struct OdOptions { } impl OdOptions { - fn new<'a>(matches: ArgMatches<'a>, args: Vec) -> Result { + fn new(matches: ArgMatches, args: Vec) -> Result { let byte_order = match matches.value_of(options::ENDIAN) { None => ByteOrder::Native, Some("little") => ByteOrder::Little, diff --git a/src/uu/od/src/parse_inputs.rs b/src/uu/od/src/parse_inputs.rs index 915aa1d92..533f4f106 100644 --- a/src/uu/od/src/parse_inputs.rs +++ b/src/uu/od/src/parse_inputs.rs @@ -63,7 +63,7 @@ pub fn parse_inputs(matches: &dyn CommandLineOpts) -> Result) -> Result Ok(CommandLineInputs::FileAndOffset(( - input_strings[0].clone().to_owned(), + input_strings[0].to_string(), m, None, ))), @@ -118,7 +118,7 @@ pub fn parse_inputs_traditional(input_strings: Vec<&str>) -> Result Ok(CommandLineInputs::FileAndOffset(( - input_strings[0].clone().to_owned(), + input_strings[0].to_string(), n, Some(m), ))), diff --git a/src/uu/printf/src/tokenize/num_format/formatters/base_conv/mod.rs b/src/uu/printf/src/tokenize/num_format/formatters/base_conv/mod.rs index 79af9abd5..04d33b52c 100644 --- a/src/uu/printf/src/tokenize/num_format/formatters/base_conv/mod.rs +++ b/src/uu/printf/src/tokenize/num_format/formatters/base_conv/mod.rs @@ -199,8 +199,7 @@ pub fn arrnum_int_add(arrnum: &[u8], basenum: u8, base_ten_int_term: u8) -> Vec< } pub fn base_conv_vec(src: &[u8], radix_src: u8, radix_dest: u8) -> Vec { - let mut result: Vec = Vec::new(); - result.push(0); + let mut result = vec![0]; for i in src { result = arrnum_int_mult(&result, radix_dest, radix_src); result = arrnum_int_add(&result, radix_dest, *i); @@ -226,8 +225,7 @@ pub fn base_conv_float(src: &[u8], radix_src: u8, radix_dest: u8) -> f64 { // to implement this for arbitrary string input. // until then, the below operates as an outline // of how it would work. - let mut result: Vec = Vec::new(); - result.push(0); + let result: Vec = vec![0]; let mut factor: f64 = 1_f64; let radix_src_float: f64 = f64::from(radix_src); let mut r: f64 = 0_f64; diff --git a/src/uu/readlink/src/readlink.rs b/src/uu/readlink/src/readlink.rs index 727c2cce5..43a4ca656 100644 --- a/src/uu/readlink/src/readlink.rs +++ b/src/uu/readlink/src/readlink.rs @@ -13,7 +13,7 @@ extern crate uucore; use clap::{App, Arg}; use std::fs; use std::io::{stdout, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use uucore::fs::{canonicalize, CanonicalizeMode}; const NAME: &str = "readlink"; @@ -160,8 +160,8 @@ pub fn uumain(args: impl uucore::Args) -> i32 { 0 } -fn show(path: &PathBuf, no_newline: bool, use_zero: bool) { - let path = path.as_path().to_str().unwrap(); +fn show(path: &Path, no_newline: bool, use_zero: bool) { + let path = path.to_str().unwrap(); if use_zero { print!("{}\0", path); } else if no_newline { diff --git a/src/uu/realpath/src/realpath.rs b/src/uu/realpath/src/realpath.rs index 5cc8f3d9a..37ff70fb2 100644 --- a/src/uu/realpath/src/realpath.rs +++ b/src/uu/realpath/src/realpath.rs @@ -12,7 +12,7 @@ extern crate uucore; use clap::{App, Arg}; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use uucore::fs::{canonicalize, CanonicalizeMode}; static ABOUT: &str = "print the resolved path"; @@ -82,7 +82,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { retcode } -fn resolve_path(p: &PathBuf, strip: bool, zero: bool, quiet: bool) -> bool { +fn resolve_path(p: &Path, strip: bool, zero: bool, quiet: bool) -> bool { let abs = canonicalize(p, CanonicalizeMode::Normal).unwrap(); if strip { diff --git a/src/uu/rm/src/rm.rs b/src/uu/rm/src/rm.rs index 09671768b..94626b4e7 100644 --- a/src/uu/rm/src/rm.rs +++ b/src/uu/rm/src/rm.rs @@ -176,7 +176,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { } else if matches.is_present(OPT_PROMPT_MORE) { InteractiveMode::Once } else if matches.is_present(OPT_INTERACTIVE) { - match &matches.value_of(OPT_INTERACTIVE).unwrap()[..] { + match matches.value_of(OPT_INTERACTIVE).unwrap() { "none" => InteractiveMode::None, "once" => InteractiveMode::Once, "always" => InteractiveMode::Always, diff --git a/src/uu/seq/src/seq.rs b/src/uu/seq/src/seq.rs index 671dd7e1c..c3bba1c78 100644 --- a/src/uu/seq/src/seq.rs +++ b/src/uu/seq/src/seq.rs @@ -102,7 +102,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { let mut largest_dec = 0; let mut padding = 0; let first = if numbers.len() > 1 { - let slice = &numbers[0][..]; + let slice = numbers[0]; let len = slice.len(); let dec = slice.find('.').unwrap_or(len); largest_dec = len - dec; @@ -118,7 +118,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 { 1.0 }; let increment = if numbers.len() > 2 { - let slice = &numbers[1][..]; + let slice = numbers[1]; let len = slice.len(); let dec = slice.find('.').unwrap_or(len); largest_dec = cmp::max(largest_dec, len - dec); @@ -134,11 +134,11 @@ pub fn uumain(args: impl uucore::Args) -> i32 { 1.0 }; if increment == 0.0 { - show_error!("increment value: '{}'", &numbers[1][..]); + show_error!("increment value: '{}'", numbers[1]); return 1; } let last = { - let slice = &numbers[numbers.len() - 1][..]; + let slice = numbers[numbers.len() - 1]; padding = cmp::max(padding, slice.find('.').unwrap_or_else(|| slice.len())); match parse_float(slice) { Ok(n) => n, diff --git a/src/uu/shred/src/shred.rs b/src/uu/shred/src/shred.rs index 7e0e77184..c56f14280 100644 --- a/src/uu/shred/src/shred.rs +++ b/src/uu/shred/src/shred.rs @@ -439,6 +439,7 @@ fn pass_name(pass_type: PassType) -> String { } } +#[allow(clippy::too_many_arguments)] fn wipe_file( path_str: &str, n_passes: usize, @@ -472,12 +473,9 @@ fn wipe_file( let mut perms = metadata.permissions(); perms.set_readonly(false); - match fs::set_permissions(path, perms) { - Err(e) => { - show_error!("{}", e); - return; - } - _ => {} + if let Err(e) = fs::set_permissions(path, perms) { + show_error!("{}", e); + return; } } diff --git a/src/uu/sum/src/sum.rs b/src/uu/sum/src/sum.rs index ed5655a3d..d0fbc7c0d 100644 --- a/src/uu/sum/src/sum.rs +++ b/src/uu/sum/src/sum.rs @@ -75,7 +75,7 @@ fn open(name: &str) -> Result> { "Is a directory", )); }; - if !path.metadata().is_ok() { + if path.metadata().is_err() { return Err(std::io::Error::new( std::io::ErrorKind::NotFound, "No such file or directory", diff --git a/src/uu/tac/src/tac.rs b/src/uu/tac/src/tac.rs index 68dae94e2..666ba3384 100644 --- a/src/uu/tac/src/tac.rs +++ b/src/uu/tac/src/tac.rs @@ -90,7 +90,7 @@ fn tac(filenames: Vec, before: bool, _: bool, separator: &str) -> i32 { Box::new(stdin()) as Box } else { let path = Path::new(filename); - if path.is_dir() || !path.metadata().is_ok() { + if path.is_dir() || path.metadata().is_err() { show_error!( "failed to open '{}' for reading: No such file or directory", filename diff --git a/src/uu/test/src/test.rs b/src/uu/test/src/test.rs index 4394e4a8e..f882ff5ae 100644 --- a/src/uu/test/src/test.rs +++ b/src/uu/test/src/test.rs @@ -55,16 +55,16 @@ fn two(args: &[&[u8]], error: &mut bool) -> bool { b"-d" => path(args[1], PathCondition::Directory), b"-e" => path(args[1], PathCondition::Exists), b"-f" => path(args[1], PathCondition::Regular), - b"-g" => path(args[1], PathCondition::GroupIDFlag), + b"-g" => path(args[1], PathCondition::GroupIdFlag), b"-h" => path(args[1], PathCondition::SymLink), b"-L" => path(args[1], PathCondition::SymLink), b"-n" => one(&args[1..]), - b"-p" => path(args[1], PathCondition::FIFO), + b"-p" => path(args[1], PathCondition::Fifo), b"-r" => path(args[1], PathCondition::Readable), b"-S" => path(args[1], PathCondition::Socket), b"-s" => path(args[1], PathCondition::NonEmpty), b"-t" => isatty(args[1]), - b"-u" => path(args[1], PathCondition::UserIDFlag), + b"-u" => path(args[1], PathCondition::UserIdFlag), b"-w" => path(args[1], PathCondition::Writable), b"-x" => path(args[1], PathCondition::Executable), b"-z" => !one(&args[1..]), @@ -322,13 +322,13 @@ enum PathCondition { Directory, Exists, Regular, - GroupIDFlag, + GroupIdFlag, SymLink, - FIFO, + Fifo, Readable, Socket, NonEmpty, - UserIDFlag, + UserIdFlag, Writable, Executable, } @@ -390,13 +390,13 @@ fn path(path: &[u8], cond: PathCondition) -> bool { PathCondition::Directory => file_type.is_dir(), PathCondition::Exists => true, PathCondition::Regular => file_type.is_file(), - PathCondition::GroupIDFlag => metadata.mode() & S_ISGID != 0, + PathCondition::GroupIdFlag => metadata.mode() & S_ISGID != 0, PathCondition::SymLink => metadata.file_type().is_symlink(), - PathCondition::FIFO => file_type.is_fifo(), + PathCondition::Fifo => file_type.is_fifo(), PathCondition::Readable => perm(metadata, Permission::Read), PathCondition::Socket => file_type.is_socket(), PathCondition::NonEmpty => metadata.size() > 0, - PathCondition::UserIDFlag => metadata.mode() & S_ISUID != 0, + PathCondition::UserIdFlag => metadata.mode() & S_ISUID != 0, PathCondition::Writable => perm(metadata, Permission::Write), PathCondition::Executable => perm(metadata, Permission::Execute), } @@ -416,13 +416,13 @@ fn path(path: &[u8], cond: PathCondition) -> bool { PathCondition::Directory => stat.is_dir(), PathCondition::Exists => true, PathCondition::Regular => stat.is_file(), - PathCondition::GroupIDFlag => false, + PathCondition::GroupIdFlag => false, PathCondition::SymLink => false, - PathCondition::FIFO => false, + PathCondition::Fifo => false, PathCondition::Readable => false, // TODO PathCondition::Socket => false, PathCondition::NonEmpty => stat.len() > 0, - PathCondition::UserIDFlag => false, + PathCondition::UserIdFlag => false, PathCondition::Writable => false, // TODO PathCondition::Executable => false, // TODO } diff --git a/src/uu/tr/src/expand.rs b/src/uu/tr/src/expand.rs index e71cf262c..73612a065 100644 --- a/src/uu/tr/src/expand.rs +++ b/src/uu/tr/src/expand.rs @@ -24,7 +24,7 @@ use std::ops::RangeInclusive; fn parse_sequence(s: &str) -> (char, usize) { let c = s.chars().next().expect("invalid escape: empty string"); - if '0' <= c && c <= '7' { + if ('0'..='7').contains(&c) { let mut v = c.to_digit(8).unwrap(); let mut consumed = 1; let bits_per_digit = 3; diff --git a/src/uu/tsort/src/tsort.rs b/src/uu/tsort/src/tsort.rs index 3440972a2..967a9514a 100644 --- a/src/uu/tsort/src/tsort.rs +++ b/src/uu/tsort/src/tsort.rs @@ -16,8 +16,8 @@ use std::io::{stdin, BufRead, BufReader, Read}; use std::path::Path; static VERSION: &str = env!("CARGO_PKG_VERSION"); -static SUMMARY: &str = "Topological sort the strings in FILE. -Strings are defined as any sequence of tokens separated by whitespace (tab, space, or newline). +static SUMMARY: &str = "Topological sort the strings in FILE. +Strings are defined as any sequence of tokens separated by whitespace (tab, space, or newline). If FILE is not passed in, stdin is used instead."; static USAGE: &str = "tsort [OPTIONS] FILE"; @@ -32,13 +32,16 @@ pub fn uumain(args: impl uucore::Args) -> i32 { .version(VERSION) .usage(USAGE) .about(SUMMARY) - .arg(Arg::with_name(options::FILE).hidden(true)) + .arg( + Arg::with_name(options::FILE) + .default_value("-") + .hidden(true), + ) .get_matches_from(args); - let input = match matches.value_of(options::FILE) { - Some(v) => v, - None => "-", - }; + let input = matches + .value_of(options::FILE) + .expect("Value is required by clap"); let mut stdin_buf; let mut file_buf; diff --git a/src/uu/wc/src/count_bytes.rs b/src/uu/wc/src/count_bytes.rs index 0c3b5edb7..7f06f8171 100644 --- a/src/uu/wc/src/count_bytes.rs +++ b/src/uu/wc/src/count_bytes.rs @@ -72,30 +72,27 @@ pub(crate) fn count_bytes_fast(handle: &mut T) -> WcResult { - // If the file is regular, then the `st_size` should hold - // the file's size in bytes. - if (stat.st_mode & S_IFREG) != 0 { - return Ok(stat.st_size as usize); - } - #[cfg(any(target_os = "linux", target_os = "android"))] - { - // Else, if we're on Linux and our file is a FIFO pipe - // (or stdin), we use splice to count the number of bytes. - if (stat.st_mode & S_IFIFO) != 0 { - if let Ok(n) = count_bytes_using_splice(fd) { - return Ok(n); - } + if let Ok(stat) = fstat(fd) { + // If the file is regular, then the `st_size` should hold + // the file's size in bytes. + if (stat.st_mode & S_IFREG) != 0 { + return Ok(stat.st_size as usize); + } + #[cfg(any(target_os = "linux", target_os = "android"))] + { + // Else, if we're on Linux and our file is a FIFO pipe + // (or stdin), we use splice to count the number of bytes. + if (stat.st_mode & S_IFIFO) != 0 { + if let Ok(n) = count_bytes_using_splice(fd) { + return Ok(n); } } } - _ => {} } } // Fall back on `read`, but without the overhead of counting words and lines. - let mut buf = [0 as u8; BUF_SIZE]; + let mut buf = [0_u8; BUF_SIZE]; let mut byte_count = 0; loop { match handle.read(&mut buf) { diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index 22463caa4..59ca10141 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -138,11 +138,8 @@ impl AddAssign for WordCount { } impl WordCount { - fn with_title<'a>(self, title: &'a str) -> TitledWordCount<'a> { - return TitledWordCount { - title: title, - count: self, - }; + fn with_title(self, title: &str) -> TitledWordCount { + TitledWordCount { title, count: self } } } @@ -251,7 +248,7 @@ fn is_word_separator(byte: u8) -> bool { fn word_count_from_reader( mut reader: T, settings: &Settings, - path: &String, + path: &str, ) -> WcResult { let only_count_bytes = settings.show_bytes && (!(settings.show_chars @@ -333,18 +330,18 @@ fn word_count_from_reader( }) } -fn word_count_from_path(path: &String, settings: &Settings) -> WcResult { +fn word_count_from_path(path: &str, settings: &Settings) -> WcResult { if path == "-" { let stdin = io::stdin(); let stdin_lock = stdin.lock(); - return Ok(word_count_from_reader(stdin_lock, settings, path)?); + word_count_from_reader(stdin_lock, settings, path) } else { let path_obj = Path::new(path); if path_obj.is_dir() { - return Err(WcError::IsDirectory(path.clone())); + Err(WcError::IsDirectory(path.to_owned())) } else { let file = File::open(path)?; - return Ok(word_count_from_reader(file, settings, path)?); + word_count_from_reader(file, settings, path) } } } @@ -425,7 +422,7 @@ fn print_stats( } if result.title == "-" { - writeln!(stdout_lock, "")?; + writeln!(stdout_lock)?; } else { writeln!(stdout_lock, " {}", result.title)?; }