Fix some clippy warnings

This commit is contained in:
John Eckersberg 2021-03-09 16:23:48 -05:00
parent 476a3d42da
commit 08eb56f120
16 changed files with 60 additions and 63 deletions

View file

@ -1238,15 +1238,13 @@ fn copy_helper(source: &Path, dest: &Path, options: &Options) -> CopyResult<()>
dest.into()
};
symlink_file(&link, &dest, &*context_for(&link, &dest))?;
} else if source.to_string_lossy() == "/dev/null" {
/* workaround a limitation of fs::copy
* https://github.com/rust-lang/rust/issues/79390
*/
File::create(dest)?;
} else {
if source.to_string_lossy() == "/dev/null" {
/* workaround a limitation of fs::copy
* https://github.com/rust-lang/rust/issues/79390
*/
File::create(dest)?;
} else {
fs::copy(source, dest).context(&*context_for(source, dest))?;
}
fs::copy(source, dest).context(&*context_for(source, dest))?;
}
Ok(())

View file

@ -478,7 +478,7 @@ where
/// Shrink the buffer so that its length is equal to the set size, returning an iterator for
/// the elements that were too much.
fn shrink_buffer_to_size<'a>(&'a mut self) -> impl Iterator<Item = String> + 'a {
fn shrink_buffer_to_size(&mut self) -> impl Iterator<Item = String> + '_ {
let mut shrink_offset = 0;
if self.buffer.len() > self.size {
shrink_offset = self.buffer.len() - self.size;
@ -489,7 +489,7 @@ where
}
/// Drain the content of the buffer.
fn drain_buffer<'a>(&'a mut self) -> impl Iterator<Item = String> + 'a {
fn drain_buffer(&mut self) -> impl Iterator<Item = String> + '_ {
self.buffer.drain(..).map(|(_, line)| line.unwrap())
}

View file

@ -207,7 +207,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
let paths: Vec<PathBuf> = matches
.values_of(ARG_FILES)
.unwrap()
.map(|path| PathBuf::from(path))
.map(PathBuf::from)
.collect();
let overwrite_mode = if matches.is_present(OPT_FORCE) {
@ -316,9 +316,8 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting
// We need to clean the target
if is_symlink(target_dir) {
if target_dir.is_file() {
match fs::remove_file(target_dir) {
Err(e) => show_error!("Could not update {}: {}", target_dir.display(), e),
_ => (),
if let Err(e) = fs::remove_file(target_dir) {
show_error!("Could not update {}: {}", target_dir.display(), e)
};
}
if target_dir.is_dir() {
@ -423,10 +422,8 @@ fn link(src: &PathBuf, dst: &PathBuf, settings: &Settings) -> Result<()> {
}
}
if settings.no_dereference && settings.force {
if dst.exists() {
fs::remove_file(dst)?;
}
if settings.no_dereference && settings.force && dst.exists() {
fs::remove_file(dst)?;
}
if settings.symbolic {

View file

@ -120,13 +120,11 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
// See https://github.com/clap-rs/clap/pull/1587
let tmp = env::temp_dir();
(tmpdir, tmp)
} else if !matches.is_present(OPT_TMPDIR) {
let tmp = env::temp_dir();
(template, tmp)
} else {
if !matches.is_present(OPT_TMPDIR) {
let tmp = env::temp_dir();
(template, tmp)
} else {
(template, PathBuf::from(tmpdir))
}
(template, PathBuf::from(tmpdir))
};
let make_dir = matches.is_present(OPT_DIRECTORY);
@ -158,14 +156,12 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
crash!(1, "suffix cannot contain any path separators");
}
if matches.is_present(OPT_TMPDIR) {
if PathBuf::from(prefix).is_absolute() {
show_info!(
"invalid template, {}; with --tmpdir, it may not be absolute",
template
);
return 1;
}
if matches.is_present(OPT_TMPDIR) && PathBuf::from(prefix).is_absolute() {
show_info!(
"invalid template, {}; with --tmpdir, it may not be absolute",
template
);
return 1;
};
if matches.is_present(OPT_T) {

View file

@ -11,7 +11,9 @@ fn parse_style(chars: &[char]) -> Result<crate::NumberingStyle, String> {
} else if chars.len() > 1 && chars[0] == 'p' {
let s: String = chars[1..].iter().cloned().collect();
match regex::Regex::new(&s) {
Ok(re) => Ok(crate::NumberingStyle::NumberForRegularExpression(re)),
Ok(re) => Ok(crate::NumberingStyle::NumberForRegularExpression(Box::new(
re,
))),
Err(_) => Err(String::from("Illegal regular expression")),
}
} else {

View file

@ -55,7 +55,7 @@ enum NumberingStyle {
NumberForAll,
NumberForNonEmpty,
NumberForNone,
NumberForRegularExpression(regex::Regex),
NumberForRegularExpression(Box<regex::Regex>),
}
// NumberFormat specifies how line numbers are output within their allocated

View file

@ -24,7 +24,7 @@ pub trait HasError {
}
impl<'b> MultifileReader<'b> {
pub fn new<'a>(fnames: Vec<InputSource<'a>>) -> MultifileReader<'a> {
pub fn new(fnames: Vec<InputSource>) -> MultifileReader {
let mut mf = MultifileReader {
ni: fnames,
curr_file: None, // normally this means done; call next_file()

View file

@ -472,11 +472,11 @@ fn print_bytes(prefix: &str, input_decoder: &MemoryDecoder, output_info: &Output
///
/// `skip_bytes` is the number of bytes skipped from the input
/// `read_bytes` is an optional limit to the number of bytes to read
fn open_input_peek_reader<'a>(
input_strings: &'a [String],
fn open_input_peek_reader(
input_strings: &[String],
skip_bytes: usize,
read_bytes: Option<usize>,
) -> PeekReader<PartialReader<MultifileReader<'a>>> {
) -> PeekReader<PartialReader<MultifileReader>> {
// should return "impl PeekRead + Read + HasError" when supported in (stable) rust
let inputs = input_strings
.iter()

View file

@ -52,8 +52,7 @@ fn get_primitive_hex(
last_dec_place: usize,
capitalized: bool,
) -> FormatPrimitive {
let mut f: FormatPrimitive = Default::default();
f.prefix = Some(String::from(if inprefix.sign == -1 { "-0x" } else { "0x" }));
let prefix = Some(String::from(if inprefix.sign == -1 { "-0x" } else { "0x" }));
// assign the digits before and after the decimal points
// to separate slices. If no digits after decimal point,
@ -97,7 +96,7 @@ fn get_primitive_hex(
// conversion. The best way to do it is to just convert the floatnum
// directly to base 2 and then at the end translate back to hex.
let mantissa = 0;
f.suffix = Some({
let suffix = Some({
let ind = if capitalized { "P" } else { "p" };
if mantissa >= 0 {
format!("{}+{}", ind, mantissa)
@ -105,7 +104,11 @@ fn get_primitive_hex(
format!("{}{}", ind, mantissa)
}
});
f
FormatPrimitive {
prefix,
suffix,
..Default::default()
}
}
fn to_hex(src: &str, before_decimal: bool) -> String {

View file

@ -198,9 +198,10 @@ impl Formatter for Intf {
// We always will have a format primitive to return
Some(if convert_hints.len_digits == 0 || convert_hints.is_zero {
// if non-digit or end is reached before a non-zero digit
let mut fmt_prim: FormatPrimitive = Default::default();
fmt_prim.pre_decimal = Some(String::from("0"));
fmt_prim
FormatPrimitive {
pre_decimal: Some(String::from("0")),
..Default::default()
}
} else if !convert_hints.past_max {
// if the number is or may be below the bounds limit
let radix_out = match *field.field_char {

View file

@ -67,7 +67,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
let paths: Vec<PathBuf> = matches
.values_of(ARG_FILES)
.unwrap()
.map(|path| PathBuf::from(path))
.map(PathBuf::from)
.collect();
let strip = matches.is_present(OPT_STRIP);

View file

@ -97,9 +97,9 @@ With no FILE, or when FILE is -, read standard input.",
};
let repeat = matches.opt_present("repeat");
let sep = if matches.opt_present("zero-terminated") {
0x00 as u8
0x00_u8
} else {
0x0a as u8
0x0a_u8
};
let count = match matches.opt_str("head-count") {
Some(cnt) => match cnt.parse::<usize>() {

View file

@ -68,12 +68,13 @@ impl FilterWriter {
// set $FILE, save previous value (if there was one)
let _with_env_var_set = WithEnvVarSet::new("FILE", &filepath);
let shell_process = Command::new(env::var("SHELL").unwrap_or("/bin/sh".to_owned()))
.arg("-c")
.arg(command)
.stdin(Stdio::piped())
.spawn()
.expect("Couldn't spawn filter command");
let shell_process =
Command::new(env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_owned()))
.arg("-c")
.arg(command)
.stdin(Stdio::piped())
.spawn()
.expect("Couldn't spawn filter command");
FilterWriter { shell_process }
}

View file

@ -150,7 +150,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
.value_of(OPT_SUFFIX_LENGTH)
.unwrap()
.parse()
.expect(format!("Invalid number for {}", OPT_SUFFIX_LENGTH).as_str());
.unwrap_or_else(|_| panic!("Invalid number for {}", OPT_SUFFIX_LENGTH));
settings.numeric_suffix = matches.occurrences_of(OPT_NUMERIC_SUFFIXES) > 0;
settings.additional_suffix = matches.value_of(OPT_ADDITIONAL_SUFFIX).unwrap().to_owned();

View file

@ -275,7 +275,11 @@ impl Error for ParseSizeErr {
impl fmt::Display for ParseSizeErr {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.to_string())
let s = match self {
ParseSizeErr::ParseFailure(s) => s,
ParseSizeErr::SizeTooBig(s) => s,
};
write!(f, "{}", s)
}
}

View file

@ -12,7 +12,6 @@ extern crate uucore;
use clap::{App, Arg};
use std::fs::{metadata, File, OpenOptions};
use std::io::Result;
use std::path::Path;
#[derive(Eq, PartialEq)]
@ -118,10 +117,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
if reference.is_none() && size.is_none() {
crash!(1, "you must specify either --reference or --size");
} else {
match truncate(no_create, io_blocks, reference, size, files) {
Ok(()) => ( /* pass */ ),
Err(_) => return 1,
}
truncate(no_create, io_blocks, reference, size, files);
}
}
@ -134,7 +130,7 @@ fn truncate(
reference: Option<String>,
size: Option<String>,
filenames: Vec<String>,
) -> Result<()> {
) {
let (refsize, mode) = match reference {
Some(rfilename) => {
let _ = match File::open(Path::new(&rfilename)) {
@ -193,7 +189,6 @@ fn truncate(
Err(f) => crash!(1, "{}", f.to_string()),
}
}
Ok(())
}
fn parse_size(size: &str) -> (u64, TruncateMode) {