From 5af8503a5efbca58416f461a923c19253f49bb6c Mon Sep 17 00:00:00 2001 From: Roy Ivy III Date: Mon, 27 Jan 2020 23:14:11 -0600 Subject: [PATCH] `cargo fmt` --- build.rs | 25 +- mkmain.rs | 2 +- src/base32/base32.rs | 3 +- src/base64/base64.rs | 3 +- src/base64/base_common.rs | 25 +- src/cat/cat.rs | 51 ++-- src/chgrp/chgrp.rs | 8 +- src/chmod/chmod.rs | 68 +++-- src/chown/chown.rs | 8 +- src/chroot/chroot.rs | 7 +- src/cksum/build.rs | 3 +- src/cp/cp.rs | 49 ++-- src/cut/buffer.rs | 2 +- src/cut/cut.rs | 13 +- src/cut/ranges.rs | 10 +- src/date/date.rs | 5 +- src/dircolors/colors.rs | 3 +- src/dircolors/dircolors.rs | 13 +- src/du/du.rs | 246 ++++++++++-------- src/echo/echo.rs | 12 +- src/env/env.rs | 3 +- src/expand/expand.rs | 3 +- src/expr/expr.rs | 2 +- src/expr/syntax_tree.rs | 72 +++-- src/expr/tokens.rs | 7 +- src/factor/build.rs | 3 +- src/factor/factor.rs | 9 +- src/factor/numeric.rs | 2 +- src/fmt/fmt.rs | 8 +- src/fmt/linebreak.rs | 58 +++-- src/fmt/parasplit.rs | 15 +- src/fold/fold.rs | 16 +- src/groups/groups.rs | 2 +- src/hashsum/digest.rs | 16 +- src/hashsum/hashsum.rs | 83 ++++-- src/head/head.rs | 32 ++- src/hostname/hostname.rs | 44 +++- src/id/id.rs | 8 +- src/install/install.rs | 146 ++++++++--- src/install/mode.rs | 2 +- src/join/join.rs | 16 +- src/kill/kill.rs | 4 +- src/link/link.rs | 2 +- src/ln/ln.rs | 51 ++-- src/ls/ls.rs | 55 ++-- src/mkdir/mkdir.rs | 22 +- src/mkfifo/mkfifo.rs | 5 +- src/mknod/mknod.rs | 3 +- src/mktemp/mktemp.rs | 4 +- src/mktemp/tempdir.rs | 2 +- src/more/more.rs | 2 +- src/mv/mv.rs | 27 +- src/nl/nl.rs | 4 +- src/nohup/nohup.rs | 4 +- src/nproc/nproc.rs | 15 +- src/numfmt/numfmt.rs | 3 +- src/od/byteorder_io.rs | 2 +- src/od/inputdecoder.rs | 11 +- src/od/mockstream.rs | 2 +- src/od/multifilereader.rs | 4 +- src/od/od.rs | 41 +-- src/od/output_info.rs | 4 +- src/od/parse_formats.rs | 5 +- src/od/parse_inputs.rs | 12 +- src/od/partialreader.rs | 12 +- src/od/peekreader.rs | 2 +- src/od/prn_char.rs | 2 +- src/od/prn_float.rs | 4 +- src/od/prn_int.rs | 30 ++- src/paste/paste.rs | 6 +- src/pathchk/pathchk.rs | 18 +- src/pinky/pinky.rs | 6 +- src/printf/cli.rs | 2 +- src/printf/memo.rs | 6 +- src/printf/tokenize/mod.rs | 6 +- src/printf/tokenize/num_format/formatter.rs | 6 +- .../num_format/formatters/base_conv/tests.rs | 1 - .../formatters/cninetyninehexfloatf.rs | 2 +- .../num_format/formatters/float_common.rs | 12 +- .../tokenize/num_format/formatters/intf.rs | 9 +- .../tokenize/num_format/formatters/mod.rs | 8 +- src/printf/tokenize/num_format/num_format.rs | 32 +-- src/printf/tokenize/sub.rs | 50 ++-- src/printf/tokenize/unescaped_text.rs | 4 +- src/pwd/pwd.rs | 5 +- src/readlink/readlink.rs | 4 +- src/rm/rm.rs | 24 +- src/seq/seq.rs | 12 +- src/shred/shred.rs | 5 +- src/shuf/shuf.rs | 5 +- src/sleep/sleep.rs | 14 +- src/sort/sort.rs | 21 +- src/split/split.rs | 3 +- src/stat/fsext.rs | 53 +++- src/stat/stat.rs | 36 +-- src/stdbuf/libstdbuf/libstdbuf.rs | 2 +- src/stdbuf/stdbuf.rs | 17 +- src/sync/sync.rs | 28 +- src/tail/platform/redox.rs | 2 +- src/tail/platform/windows.rs | 2 +- src/tail/tail.rs | 26 +- src/tee/tee.rs | 10 +- src/test/test.rs | 25 +- src/touch/touch.rs | 8 +- src/tr/expand.rs | 12 +- src/truncate/truncate.rs | 30 ++- src/tsort/tsort.rs | 3 +- src/unexpand/unexpand.rs | 3 +- src/unlink/unlink.rs | 11 +- src/uptime/uptime.rs | 6 +- src/users/users.rs | 1 - src/uutils/uutils.rs | 8 +- src/wc/wc.rs | 5 +- src/who/who.rs | 154 +++++------ src/whoami/platform/unix.rs | 2 +- src/whoami/platform/windows.rs | 6 +- src/yes/yes.rs | 2 +- tests/common/macros.rs | 16 +- tests/common/util.rs | 27 +- 119 files changed, 1270 insertions(+), 923 deletions(-) diff --git a/build.rs b/build.rs index 124189839..f3aa4ffc5 100644 --- a/build.rs +++ b/build.rs @@ -16,8 +16,8 @@ pub fn main() { if val == "1" && key.starts_with(feature_prefix) { let krate = key[feature_prefix.len()..].to_lowercase(); match krate.as_ref() { - "default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic" | "windows" | "windows_legacy" - | "nightly" | "test_unimplemented" => continue, + "default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic" + | "windows" | "windows_legacy" | "nightly" | "test_unimplemented" => continue, _ => {} } crates.push(krate.to_string()); @@ -35,7 +35,8 @@ pub fn main() { fn util_map() -> UtilityMap { let mut map: UtilityMap = HashMap::new();\n" .as_bytes(), - ).unwrap(); + ) + .unwrap(); for krate in crates { cf.write_all(format!("extern crate uu_{krate};\n", krate = krate).as_bytes()) @@ -59,14 +60,18 @@ pub fn main() { map.insert(\"shake128sum\", uu_hashsum::uumain); map.insert(\"shake256sum\", uu_hashsum::uumain);\n" .as_bytes(), - ).unwrap(); + ) + .unwrap(); } - _ => mf.write_all( - format!( - "map.insert(\"{krate}\", uu_{krate}::uumain);\n", - krate = krate - ).as_bytes(), - ).unwrap(), + _ => mf + .write_all( + format!( + "map.insert(\"{krate}\", uu_{krate}::uumain);\n", + krate = krate + ) + .as_bytes(), + ) + .unwrap(), } } diff --git a/mkmain.rs b/mkmain.rs index f065ea8b2..c4d50d526 100644 --- a/mkmain.rs +++ b/mkmain.rs @@ -1,6 +1,6 @@ use std::env; -use std::io::Write; use std::fs::File; +use std::io::Write; use std::path::Path; static TEMPLATE: &'static str = "\ diff --git a/src/base32/base32.rs b/src/base32/base32.rs index 548784298..feb7bc384 100644 --- a/src/base32/base32.rs +++ b/src/base32/base32.rs @@ -16,8 +16,7 @@ use uucore::encoding::Format; mod base_common; static SYNTAX: &str = "[OPTION]... [FILE]"; -static SUMMARY: &str = - "Base32 encode or decode FILE, or standard input, to standard output."; +static SUMMARY: &str = "Base32 encode or decode FILE, or standard input, to standard output."; static LONG_HELP: &str = " With no FILE, or when FILE is -, read standard input. diff --git a/src/base64/base64.rs b/src/base64/base64.rs index 9072fecb0..effd4598b 100644 --- a/src/base64/base64.rs +++ b/src/base64/base64.rs @@ -16,8 +16,7 @@ use uucore::encoding::Format; mod base_common; static SYNTAX: &str = "[OPTION]... [FILE]"; -static SUMMARY: &str = - "Base64 encode or decode FILE, or standard input, to standard output."; +static SUMMARY: &str = "Base64 encode or decode FILE, or standard input, to standard output."; static LONG_HELP: &str = " With no FILE, or when FILE is -, read standard input. diff --git a/src/base64/base_common.rs b/src/base64/base_common.rs index 040b91608..1bb09ace1 100644 --- a/src/base64/base_common.rs +++ b/src/base64/base_common.rs @@ -36,13 +36,11 @@ pub fn execute( "COLS", ) .parse(args); - - let line_wrap = matches.opt_str("wrap").map(|s| { - match s.parse() { - Ok(n) => n, - Err(e) => { - crash!(1, "invalid wrap size: ‘{}’: {}", s, e); - } + + let line_wrap = matches.opt_str("wrap").map(|s| match s.parse() { + Ok(n) => n, + Err(e) => { + crash!(1, "invalid wrap size: ‘{}’: {}", s, e); } }); let ignore_garbage = matches.opt_present("ignore-garbage"); @@ -55,7 +53,13 @@ pub fn execute( if matches.free.is_empty() || &matches.free[0][..] == "-" { let stdin_raw = stdin(); - handle_input(&mut stdin_raw.lock(), format, line_wrap, ignore_garbage, decode); + handle_input( + &mut stdin_raw.lock(), + format, + line_wrap, + ignore_garbage, + decode, + ); } else { let path = Path::new(matches.free[0].as_str()); let file_buf = safe_unwrap!(File::open(&path)); @@ -73,8 +77,7 @@ fn handle_input( ignore_garbage: bool, decode: bool, ) { - let mut data = Data::new(input, format) - .ignore_garbage(ignore_garbage); + let mut data = Data::new(input, format).ignore_garbage(ignore_garbage); if let Some(wrap) = line_wrap { data = data.line_wrap(wrap); } @@ -88,4 +91,4 @@ fn handle_input( Err(_) => crash!(1, "invalid input"), } } -} \ No newline at end of file +} diff --git a/src/cat/cat.rs b/src/cat/cat.rs index 0b68c854f..477db9599 100755 --- a/src/cat/cat.rs +++ b/src/cat/cat.rs @@ -168,7 +168,10 @@ pub fn uumain(args: Vec) -> i32 { files.push("-".to_owned()); } - let can_write_fast = !(show_tabs || show_nonprint || show_ends || squeeze_blank + let can_write_fast = !(show_tabs + || show_nonprint + || show_ends + || squeeze_blank || number_mode != NumberingMode::None); let success = if can_write_fast { @@ -190,7 +193,11 @@ pub fn uumain(args: Vec) -> i32 { write_lines(files, &options).is_ok() }; - if success { 0 } else { 1 } + if success { + 0 + } else { + 1 + } } /// Classifies the `InputType` of file at `path` if possible @@ -205,25 +212,13 @@ fn get_input_type(path: &str) -> CatResult { match metadata(path).context(path)?.file_type() { #[cfg(unix)] - ft if ft.is_block_device() => - { - Ok(InputType::BlockDevice) - } + ft if ft.is_block_device() => Ok(InputType::BlockDevice), #[cfg(unix)] - ft if ft.is_char_device() => - { - Ok(InputType::CharacterDevice) - } + ft if ft.is_char_device() => Ok(InputType::CharacterDevice), #[cfg(unix)] - ft if ft.is_fifo() => - { - Ok(InputType::Fifo) - } + ft if ft.is_fifo() => Ok(InputType::Fifo), #[cfg(unix)] - ft if ft.is_socket() => - { - Ok(InputType::Socket) - } + ft if ft.is_socket() => Ok(InputType::Socket), ft if ft.is_dir() => Ok(InputType::Directory), ft if ft.is_file() => Ok(InputType::File), ft if ft.is_symlink() => Ok(InputType::SymLink), @@ -282,12 +277,14 @@ fn write_fast(files: Vec) -> CatResult<()> { for file in files { match open(&file[..]) { - Ok(mut handle) => while let Ok(n) = handle.reader.read(&mut in_buf) { - if n == 0 { - break; + Ok(mut handle) => { + while let Ok(n) = handle.reader.read(&mut in_buf) { + if n == 0 { + break; + } + writer.write_all(&in_buf[..n]).context(&file[..])?; } - writer.write_all(&in_buf[..n]).context(&file[..])?; - }, + } Err(error) => { writeln!(&mut stderr(), "{}", error)?; error_count += 1; @@ -421,10 +418,7 @@ fn write_to_end(in_buf: &[u8], writer: &mut W) -> usize { fn write_tab_to_end(mut in_buf: &[u8], writer: &mut W) -> usize { let mut count = 0; loop { - match in_buf - .iter() - .position(|c| *c == b'\n' || *c == b'\t') - { + match in_buf.iter().position(|c| *c == b'\n' || *c == b'\t') { Some(p) => { writer.write_all(&in_buf[..p]).unwrap(); if in_buf[p] == b'\n' { @@ -458,7 +452,8 @@ fn write_nonprint_to_end(in_buf: &[u8], writer: &mut W, tab: &[u8]) -> 128..=159 => writer.write_all(&[b'M', b'-', b'^', byte - 64]), 160..=254 => writer.write_all(&[b'M', b'-', byte - 128]), _ => writer.write_all(&[b'M', b'-', b'^', 63]), - }.unwrap(); + } + .unwrap(); count += 1; } if count != in_buf.len() { diff --git a/src/chgrp/chgrp.rs b/src/chgrp/chgrp.rs index ed50432d3..fac36f672 100644 --- a/src/chgrp/chgrp.rs +++ b/src/chgrp/chgrp.rs @@ -10,15 +10,15 @@ #[macro_use] extern crate uucore; -use uucore::libc::{self, gid_t, lchown}; pub use uucore::entries; use uucore::fs::resolve_relative_path; +use uucore::libc::{self, gid_t, lchown}; extern crate walkdir; use walkdir::WalkDir; -use std::io::Result as IOResult; use std::io::Error as IOError; +use std::io::Result as IOResult; use std::fs; use std::fs::Metadata; @@ -183,12 +183,12 @@ struct Chgrper { } macro_rules! unwrap { - ($m:expr, $e:ident, $err:block) => ( + ($m:expr, $e:ident, $err:block) => { match $m { Ok(meta) => meta, Err($e) => $err, } - ) + }; } impl Chgrper { diff --git a/src/chmod/chmod.rs b/src/chmod/chmod.rs index 17e111063..0dc5e737f 100644 --- a/src/chmod/chmod.rs +++ b/src/chmod/chmod.rs @@ -19,10 +19,10 @@ extern crate uucore; use std::fs; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::path::Path; -use walker::Walker; +use uucore::fs::display_permissions_unix; #[cfg(not(windows))] use uucore::mode; -use uucore::fs::display_permissions_unix; +use walker::Walker; const NAME: &str = "chmod"; static SUMMARY: &str = "Change the mode of each FILE to MODE. @@ -39,14 +39,31 @@ pub fn uumain(mut args: Vec) -> i32 { NAME ); let mut opts = new_coreopts!(&syntax, SUMMARY, LONG_HELP); - opts.optflag("c", "changes", "like verbose but report only when a change is made") - // TODO: support --silent (can be done using clap) - .optflag("f", "quiet", "suppress most error messages") - .optflag("v", "verbose", "output a diagnostic for every file processed") - .optflag("", "no-preserve-root", "do not treat '/' specially (the default)") - .optflag("", "preserve-root", "fail to operate recursively on '/'") - .optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE") - .optflag("R", "recursive", "change files and directories recursively"); + opts.optflag( + "c", + "changes", + "like verbose but report only when a change is made", + ) + // TODO: support --silent (can be done using clap) + .optflag("f", "quiet", "suppress most error messages") + .optflag( + "v", + "verbose", + "output a diagnostic for every file processed", + ) + .optflag( + "", + "no-preserve-root", + "do not treat '/' specially (the default)", + ) + .optflag("", "preserve-root", "fail to operate recursively on '/'") + .optopt( + "", + "reference", + "use RFILE's mode instead of MODE values", + "RFILE", + ) + .optflag("R", "recursive", "change files and directories recursively"); // sanitize input for - at beginning (e.g. chmod -x testfile). Remove // the option and save it for later, after parsing is finished. @@ -148,17 +165,19 @@ impl Chmoder { // on Windows OsStrings cannot be built out of non-UTF-8 chars. One // possible fix is to use CStrings rather than Strings in the args // to chmod() and chmod_file(). - r = self.chmod( - walk_dir - .filter_map(|x| match x { - Ok(o) => match o.path().into_os_string().to_str() { - Some(s) => Some(s.to_owned()), - None => None, - }, - Err(_) => None, - }) - .collect(), - ).and(r); + r = self + .chmod( + walk_dir + .filter_map(|x| match x { + Ok(o) => match o.path().into_os_string().to_str() { + Some(s) => Some(s.to_owned()), + None => None, + }, + Err(_) => None, + }) + .collect(), + ) + .and(r); r = self.chmod_file(&file, filename).and(r); } } else { @@ -230,7 +249,12 @@ impl Chmoder { fn change_file(&self, fperm: u32, mode: u32, file: &Path, path: &str) -> Result<(), i32> { if fperm == mode { if self.verbose && !self.changes { - show_info!("mode of '{}' retained as {:o} ({})", file.display(), fperm, display_permissions_unix(fperm)); + show_info!( + "mode of '{}' retained as {:o} ({})", + file.display(), + fperm, + display_permissions_unix(fperm) + ); } Ok(()) } else if let Err(err) = diff --git a/src/chown/chown.rs b/src/chown/chown.rs index 22d45938a..7b7378492 100644 --- a/src/chown/chown.rs +++ b/src/chown/chown.rs @@ -11,9 +11,9 @@ #[macro_use] extern crate uucore; -use uucore::libc::{self, gid_t, lchown, uid_t}; pub use uucore::entries::{self, Group, Locate, Passwd}; use uucore::fs::resolve_relative_path; +use uucore::libc::{self, gid_t, lchown, uid_t}; extern crate walkdir; use walkdir::WalkDir; @@ -24,8 +24,8 @@ use std::os::unix::fs::MetadataExt; use std::io; use std::io::Result as IOResult; -use std::path::Path; use std::convert::AsRef; +use std::path::Path; use std::ffi::CString; use std::os::unix::ffi::OsStrExt; @@ -253,12 +253,12 @@ struct Chowner { } macro_rules! unwrap { - ($m:expr, $e:ident, $err:block) => ( + ($m:expr, $e:ident, $err:block) => { match $m { Ok(meta) => meta, Err($e) => $err, } - ) + }; } impl Chowner { diff --git a/src/chroot/chroot.rs b/src/chroot/chroot.rs index a7973e8fe..140d2f18b 100644 --- a/src/chroot/chroot.rs +++ b/src/chroot/chroot.rs @@ -14,8 +14,8 @@ extern crate getopts; #[macro_use] extern crate uucore; -use uucore::libc::{self, chroot, setgid, setgroups, setuid}; use uucore::entries; +use uucore::libc::{self, chroot, setgid, setgroups, setuid}; use std::ffi::CString; use std::io::Error; @@ -140,10 +140,7 @@ fn enter_chroot(root: &Path) { let root_str = root.display(); std::env::set_current_dir(root).unwrap(); let err = unsafe { - chroot(CString::new(".") - .unwrap() - .as_bytes_with_nul() - .as_ptr() as *const libc::c_char) + chroot(CString::new(".").unwrap().as_bytes_with_nul().as_ptr() as *const libc::c_char) }; if err != 0 { crash!( diff --git a/src/cksum/build.rs b/src/cksum/build.rs index 00c5c0fb4..6d3824f4f 100644 --- a/src/cksum/build.rs +++ b/src/cksum/build.rs @@ -32,7 +32,8 @@ fn main() { &file, "#[allow(clippy::unreadable_literal)]\nconst CRC_TABLE: [u32; {}] = {:?};", CRC_TABLE_LEN, table - ).unwrap(); + ) + .unwrap(); } #[inline] diff --git a/src/cp/cp.rs b/src/cp/cp.rs index 796b5c4b2..6ab4527ce 100644 --- a/src/cp/cp.rs +++ b/src/cp/cp.rs @@ -1,5 +1,4 @@ #![crate_name = "uu_cp"] - #![allow(clippy::missing_safety_doc)] /* @@ -29,35 +28,35 @@ extern crate xattr; #[cfg(windows)] extern crate kernel32; #[cfg(windows)] -use kernel32::GetFileInformationByHandle; -#[cfg(windows)] use kernel32::CreateFileW; #[cfg(windows)] +use kernel32::GetFileInformationByHandle; +#[cfg(windows)] extern crate winapi; -use std::mem; +use clap::{App, Arg, ArgMatches}; +use filetime::FileTime; +use quick_error::ResultExt; +use std::collections::HashSet; #[cfg(not(windows))] use std::ffi::CString; #[cfg(windows)] use std::ffi::OsStr; -use clap::{App, Arg, ArgMatches}; -use quick_error::ResultExt; -use std::collections::HashSet; use std::fs; -use std::io::{stdin, stdout, Write}; +#[cfg(target_os = "linux")] +use std::fs::File; +use std::fs::OpenOptions; use std::io; +use std::io::{stdin, stdout, Write}; +use std::mem; +#[cfg(target_os = "linux")] +use std::os::unix::io::IntoRawFd; #[cfg(windows)] use std::os::windows::ffi::OsStrExt; use std::path::{Path, PathBuf, StripPrefixError}; use std::str::FromStr; use uucore::fs::{canonicalize, CanonicalizeMode}; use walkdir::WalkDir; -#[cfg(target_os = "linux")] -use std::os::unix::io::IntoRawFd; -#[cfg(target_os = "linux")] -use std::fs::File; -use std::fs::OpenOptions; -use filetime::FileTime; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; @@ -584,7 +583,8 @@ impl Options { } } - let recursive = matches.is_present(OPT_RECURSIVE) || matches.is_present(OPT_RECURSIVE_ALIAS) + let recursive = matches.is_present(OPT_RECURSIVE) + || matches.is_present(OPT_RECURSIVE_ALIAS) || matches.is_present(OPT_ARCHIVE); let backup = matches.is_present(OPT_BACKUP) || (matches.occurrences_of(OPT_SUFFIX) > 0); @@ -731,7 +731,8 @@ fn preserve_hardlinks( "cannot stat {:?}: {}", src_path, std::io::Error::last_os_error() - ).into()); + ) + .into()); } inode = stat.st_ino as u64; nlinks = stat.st_nlink as u64; @@ -755,7 +756,8 @@ fn preserve_hardlinks( "cannot get file information {:?}: {}", source, std::io::Error::last_os_error() - ).into()); + ) + .into()); } inode = ((*stat).nFileIndexHigh as u64) << 32 | (*stat).nFileIndexLow as u64; nlinks = (*stat).nNumberOfLinks as u64; @@ -836,7 +838,8 @@ fn construct_dest_path( return Err(format!( "cannot overwrite directory '{}' with non-directory", target.display() - ).into()); + ) + .into()); } Ok(match *target_type { @@ -1140,7 +1143,8 @@ fn copy_helper(source: &Path, dest: &Path, options: &Options) -> CopyResult<()> source, dest, std::io::Error::last_os_error() - ).into()); + ) + .into()); } else { return Ok(()); } @@ -1169,7 +1173,8 @@ pub fn verify_target_type(target: &Path, target_type: &TargetType) -> CopyResult (&TargetType::File, true) => Err(format!( "cannot overwrite directory '{}' with non-directory", target.display() - ).into()), + ) + .into()), _ => Ok(()), } } @@ -1205,6 +1210,8 @@ fn test_cp_localize_to_target() { &Path::new("a/source/"), &Path::new("a/source/c.txt"), &Path::new("target/") - ).unwrap() == Path::new("target/c.txt") + ) + .unwrap() + == Path::new("target/c.txt") ) } diff --git a/src/cut/buffer.rs b/src/cut/buffer.rs index 733244a54..54003f274 100644 --- a/src/cut/buffer.rs +++ b/src/cut/buffer.rs @@ -10,8 +10,8 @@ * file that was distributed with this source code. */ -use std::io::{BufRead, BufReader, Read, Write}; use std::io::Result as IoResult; +use std::io::{BufRead, BufReader, Read, Write}; #[allow(non_snake_case)] pub mod Bytes { diff --git a/src/cut/cut.rs b/src/cut/cut.rs index 58bdf59fe..5578713e0 100644 --- a/src/cut/cut.rs +++ b/src/cut/cut.rs @@ -466,8 +466,8 @@ pub fn uumain(args: Vec) -> i32 { ) }) } - (None, None, Some(field_ranges)) => list_to_ranges(&field_ranges[..], complement) - .and_then(|ranges| { + (None, None, Some(field_ranges)) => { + list_to_ranges(&field_ranges[..], complement).and_then(|ranges| { let out_delim = match matches.opt_str("output-delimiter") { Some(s) => { if s.is_empty() { @@ -519,11 +519,16 @@ pub fn uumain(args: Vec) -> i32 { }, )), } - }), + }) + } (ref b, ref c, ref f) if b.is_some() || c.is_some() || f.is_some() => Err( msg_expects_no_more_than_one_of!("--fields (-f)", "--chars (-c)", "--bytes (-b)"), ), - _ => Err(msg_expects_one_of!("--fields (-f)", "--chars (-c)", "--bytes (-b)")), + _ => Err(msg_expects_one_of!( + "--fields (-f)", + "--chars (-c)", + "--bytes (-b)" + )), }; let mode_parse = match mode_parse { diff --git a/src/cut/ranges.rs b/src/cut/ranges.rs index 76caff9ce..85b20fe38 100644 --- a/src/cut/ranges.rs +++ b/src/cut/ranges.rs @@ -42,10 +42,7 @@ impl FromStr for Range { (Some(n), Some(m)) if m.is_empty() => { if let Ok(low) = n.parse::() { if low > 0 { - Ok(Range { - low, - high: MAX - 1, - }) + Ok(Range { low, high: MAX - 1 }) } else { Err(field) } @@ -67,10 +64,7 @@ impl FromStr for Range { (Some(n), Some(m)) => match (n.parse::(), m.parse::()) { (Ok(low), Ok(high)) => { if low > 0 && low <= high { - Ok(Range { - low, - high, - }) + Ok(Range { low, high }) } else if low == 0 { Err(field) } else { diff --git a/src/date/date.rs b/src/date/date.rs index f07a5e756..adb9726a8 100644 --- a/src/date/date.rs +++ b/src/date/date.rs @@ -14,8 +14,8 @@ extern crate chrono; extern crate clap; extern crate uucore; -use chrono::{DateTime, FixedOffset, Local, Offset}; use chrono::offset::Utc; +use chrono::{DateTime, FixedOffset, Local, Offset}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; @@ -210,12 +210,11 @@ fn parse_cli(args: Vec) -> Settings { "set time described by STRING") (@arg utc: -u --utc --universal "print or set Coordinated Universal Time (UTC)")) - // TODO: Decide whether this is appropriate. // The GNU date command has an explanation of all formatting options, // but the `chrono` crate has a few differences (most notably, the %Z option) // (after_help: include_str!("usage.txt"))) - .get_matches_from(args); + .get_matches_from(args); let format = if let Some(form) = matches.value_of("custom_format") { let form = form[1..].into(); diff --git a/src/dircolors/colors.rs b/src/dircolors/colors.rs index c19920508..e9cea624f 100644 --- a/src/dircolors/colors.rs +++ b/src/dircolors/colors.rs @@ -1,5 +1,4 @@ -pub const INTERNAL_DB: &str = - r#"# Configuration file for dircolors, a utility to help you set the +pub const INTERNAL_DB: &str = r#"# Configuration file for dircolors, a utility to help you set the # LS_COLORS environment variable used by GNU ls with the --color option. # Copyright (C) 1996-2016 Free Software Foundation, Inc. # Copying and distribution of this file, with or without modification, diff --git a/src/dircolors/dircolors.rs b/src/dircolors/dircolors.rs index 31a065b06..fa5713a88 100644 --- a/src/dircolors/dircolors.rs +++ b/src/dircolors/dircolors.rs @@ -13,10 +13,10 @@ extern crate glob; #[macro_use] extern crate uucore; -use std::fs::File; -use std::io::{BufRead, BufReader}; use std::borrow::Borrow; use std::env; +use std::fs::File; +use std::io::{BufRead, BufReader}; static SYNTAX: &str = "[OPTION]... [FILE]"; static SUMMARY: &str = "Output commands to set the LS_COLORS environment variable."; @@ -68,8 +68,11 @@ pub fn uumain(args: Vec) -> i32 { .optflag("p", "print-database", "print the byte counts") .parse(args); - if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") - || matches.opt_present("bourne-shell")) && matches.opt_present("print-database") + if (matches.opt_present("csh") + || matches.opt_present("c-shell") + || matches.opt_present("sh") + || matches.opt_present("bourne-shell")) + && matches.opt_present("print-database") { disp_err!( "the options to output dircolors' internal database and\nto select a shell \ @@ -291,7 +294,7 @@ where } else if key.starts_with('*') { result.push_str(format!("{}={}:", key, val).as_str()); } else if lower == "options" || lower == "color" || lower == "eightbit" { - // Slackware only. Ignore + // Slackware only. Ignore } else if let Some(s) = table.get(lower.as_str()) { result.push_str(format!("{}={}:", s, val).as_str()); } else { diff --git a/src/du/du.rs b/src/du/du.rs index 28e1a8c03..7b4ff4f0a 100644 --- a/src/du/du.rs +++ b/src/du/du.rs @@ -163,40 +163,36 @@ fn du( for f in read { match f { - Ok(entry) => { - match Stat::new(entry.path()) { - Ok(this_stat) => { - if this_stat.is_dir { - futures.push(du(this_stat, options, depth + 1, inodes)); - } else { - if inodes.contains(&this_stat.inode) { - continue; - } - inodes.insert(this_stat.inode); - my_stat.size += this_stat.size; - my_stat.blocks += this_stat.blocks; - if options.all { - stats.push(this_stat); - } + Ok(entry) => match Stat::new(entry.path()) { + Ok(this_stat) => { + if this_stat.is_dir { + futures.push(du(this_stat, options, depth + 1, inodes)); + } else { + if inodes.contains(&this_stat.inode) { + continue; + } + inodes.insert(this_stat.inode); + my_stat.size += this_stat.size; + my_stat.blocks += this_stat.blocks; + if options.all { + stats.push(this_stat); } } - Err(error) => show_error!("{}", error), } - } + Err(error) => show_error!("{}", error), + }, Err(error) => show_error!("{}", error), } } } - stats.extend(futures.into_iter().flatten().rev().filter( - |stat| { - if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { - my_stat.size += stat.size; - my_stat.blocks += stat.blocks; - } - options.max_depth == None || depth < options.max_depth.unwrap() - }, - )); + stats.extend(futures.into_iter().flatten().rev().filter(|stat| { + if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { + my_stat.size += stat.size; + my_stat.blocks += stat.blocks; + } + options.max_depth == None || depth < options.max_depth.unwrap() + })); stats.push(my_stat); Box::new(stats.into_iter()) } @@ -220,7 +216,10 @@ fn convert_size_k(size: u64, multiplier: u64, _block_size: u64) -> String { } fn convert_size_m(size: u64, multiplier: u64, _block_size: u64) -> String { - format!("{}", ((size as f64) / ((multiplier * multiplier) as f64)).ceil()) + format!( + "{}", + ((size as f64) / ((multiplier * multiplier) as f64)).ceil() + ) } fn convert_size_other(size: u64, _multiplier: u64, block_size: u64) -> String { @@ -235,66 +234,109 @@ pub fn uumain(args: Vec) -> i32 { NAME ); let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) - // In task - .optflag("a", "all", " write counts for all files, not just directories") - // In main - .optflag("", "apparent-size", "print apparent sizes, rather than disk usage + // In task + .optflag( + "a", + "all", + " write counts for all files, not just directories", + ) + // In main + .optflag( + "", + "apparent-size", + "print apparent sizes, rather than disk usage although the apparent size is usually smaller, it may be larger due to holes - in ('sparse') files, internal fragmentation, indirect blocks, and the like") - // In main - .optopt("B", "block-size", "scale sizes by SIZE before printing them. + in ('sparse') files, internal fragmentation, indirect blocks, and the like", + ) + // In main + .optopt( + "B", + "block-size", + "scale sizes by SIZE before printing them. E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.", - "SIZE") - // In main - .optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'") - // In main + "SIZE", + ) + // In main + .optflag( + "b", + "bytes", + "equivalent to '--apparent-size --block-size=1'", + ) + // In main .optflag("c", "total", "produce a grand total") - // In task - // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed - // on the command line"), - // In main - // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file - // names specified in file F; - // If F is - then read names from standard input", "F"), - // // In task - // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), - // In main - .optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)") - // In main + // In task + // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed + // on the command line"), + // In main + // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file + // names specified in file F; + // If F is - then read names from standard input", "F"), + // // In task + // opts.optflag("H", "", "equivalent to --dereference-args (-D)"), + // In main + .optflag( + "h", + "human-readable", + "print sizes in human readable format (e.g., 1K 234M 2G)", + ) + // In main .optflag("", "si", "like -h, but use powers of 1000 not 1024") - // In main + // In main .optflag("k", "", "like --block-size=1K") - // In task + // In task .optflag("l", "count-links", "count sizes many times if hard linked") - // // In main + // // In main .optflag("m", "", "like --block-size=1M") - // // In task - // opts.optflag("L", "dereference", "dereference all symbolic links"), - // // In task - // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), - // // In main - .optflag("0", "null", "end each output line with 0 byte rather than newline") - // In main - .optflag("S", "separate-dirs", "do not include size of subdirectories") - // In main + // // In task + // opts.optflag("L", "dereference", "dereference all symbolic links"), + // // In task + // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), + // // In main + .optflag( + "0", + "null", + "end each output line with 0 byte rather than newline", + ) + // In main + .optflag( + "S", + "separate-dirs", + "do not include size of subdirectories", + ) + // In main .optflag("s", "summarize", "display only a total for each argument") - // // In task - // opts.optflag("x", "one-file-system", "skip directories on different file systems"), - // // In task - // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), - // // In task - // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), - // In main - .optopt("d", "max-depth", "print the total for a directory (or file, with --all) + // // In task + // opts.optflag("x", "one-file-system", "skip directories on different file systems"), + // // In task + // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), + // // In task + // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), + // In main + .optopt( + "d", + "max-depth", + "print the total for a directory (or file, with --all) only if it is N or fewer levels below the command - line argument; --max-depth=0 is the same as --summarize", "N") - // In main - .optflagopt("", "time", "show time of the last modification of any file in the + line argument; --max-depth=0 is the same as --summarize", + "N", + ) + // In main + .optflagopt( + "", + "time", + "show time of the last modification of any file in the directory, or any of its subdirectories. If WORD is given, show time as WORD instead - of modification time: atime, access, use, ctime or status", "WORD") - // In main - .optopt("", "time-style", "show times using style STYLE: - full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE") + of modification time: atime, access, use, ctime or status", + "WORD", + ) + // In main + .optopt( + "", + "time-style", + "show times using style STYLE: + full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", + "STYLE", + ) .parse(args); let summarize = matches.opt_present("summarize"); @@ -350,26 +392,24 @@ pub fn uumain(args: Vec) -> i32 { let convert_size = |size| convert_size_fn(size, multiplier, block_size); let time_format_str = match matches.opt_str("time-style") { - Some(s) => { - match &s[..] { - "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", - "long-iso" => "%Y-%m-%d %H:%M", - "iso" => "%Y-%m-%d", - _ => { - show_error!( - "invalid argument '{}' for 'time style' + Some(s) => match &s[..] { + "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", + "long-iso" => "%Y-%m-%d %H:%M", + "iso" => "%Y-%m-%d", + _ => { + show_error!( + "invalid argument '{}' for 'time style' Valid arguments are: - 'full-iso' - 'long-iso' - 'iso' Try '{} --help' for more information.", - s, - NAME - ); - return 1; - } + s, + NAME + ); + return 1; } - } + }, None => "%Y-%m-%d %H:%M", }; @@ -397,23 +437,21 @@ Try '{} --help' for more information.", let tm = { let (secs, nsecs) = { let time = match matches.opt_str("time") { - Some(s) => { - match &s[..] { - "accessed" => stat.accessed, - "created" => stat.created, - "modified" => stat.modified, - _ => { - show_error!( - "invalid argument 'modified' for '--time' + Some(s) => match &s[..] { + "accessed" => stat.accessed, + "created" => stat.created, + "modified" => stat.modified, + _ => { + show_error!( + "invalid argument 'modified' for '--time' Valid arguments are: - 'accessed', 'created', 'modified' Try '{} --help' for more information.", - NAME - ); - return 1; - } + NAME + ); + return 1; } - } + }, None => stat.modified, }; ((time / 1000) as i64, (time % 1000 * 1_000_000) as i32) diff --git a/src/echo/echo.rs b/src/echo/echo.rs index 989d0d719..28b5a91f9 100644 --- a/src/echo/echo.rs +++ b/src/echo/echo.rs @@ -71,8 +71,8 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result { 'b' => '\x08', 'c' => { should_stop = true; - break - }, + break; + } 'e' => '\x1b', 'f' => '\x0c', 'n' => '\n', @@ -90,7 +90,7 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result { _ => { start = 0; next - }, + } }; } } @@ -110,7 +110,11 @@ pub fn uumain(args: Vec) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, HELP) .optflag("n", "", "do not output the trailing newline") .optflag("e", "", "enable interpretation of backslash escapes") - .optflag("E", "", "disable interpretation of backslash escapes (default)") + .optflag( + "E", + "", + "disable interpretation of backslash escapes (default)", + ) .parse(args); let no_newline = matches.opt_present("n"); diff --git a/src/env/env.rs b/src/env/env.rs index a8c5344c0..e65ff6536 100644 --- a/src/env/env.rs +++ b/src/env/env.rs @@ -89,7 +89,8 @@ fn load_config_file(opts: &mut Options) -> Result<(), i32> { } }; - for (_, prop) in &conf { // ignore all INI section lines (treat them as comments) + for (_, prop) in &conf { + // ignore all INI section lines (treat them as comments) for (key, value) in prop { env::set_var(key, value); } diff --git a/src/expand/expand.rs b/src/expand/expand.rs index 8d5ba5aa8..017e7a28e 100644 --- a/src/expand/expand.rs +++ b/src/expand/expand.rs @@ -45,7 +45,8 @@ fn tabstops_parse(s: String) -> Vec { crash!(1, "{}\n", "tab size cannot be 0"); } - if let (false, _) = nums.iter() + if let (false, _) = nums + .iter() .fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { crash!(1, "{}\n", "tab sizes must be ascending"); diff --git a/src/expr/expr.rs b/src/expr/expr.rs index 1298137fb..a3b61f1fd 100644 --- a/src/expr/expr.rs +++ b/src/expr/expr.rs @@ -13,8 +13,8 @@ extern crate onig; #[macro_use] extern crate uucore; -mod tokens; mod syntax_tree; +mod tokens; static NAME: &str = "expr"; static VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/src/expr/syntax_tree.rs b/src/expr/syntax_tree.rs index d003d61ae..914c0ec9c 100644 --- a/src/expr/syntax_tree.rs +++ b/src/expr/syntax_tree.rs @@ -12,8 +12,8 @@ //! * https://en.wikipedia.org/wiki/Shunting-yard_algorithm //! -use tokens::Token; use onig::{Regex, RegexOptions, Syntax}; +use tokens::Token; type TokenStack = Vec<(usize, Token)>; pub type OperandsList = Vec>; @@ -85,25 +85,27 @@ impl ASTNode { 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(|a: i64, b: i64| { - checked_binop(|| a.checked_add(b), "+") - }, &operand_values + "+" => infix_operator_two_ints( + |a: i64, b: i64| checked_binop(|| a.checked_add(b), "+"), + &operand_values, ), - "-" => infix_operator_two_ints(|a: i64, b: i64| { - checked_binop(|| a.checked_sub(b), "-") - }, &operand_values + "-" => infix_operator_two_ints( + |a: i64, b: i64| checked_binop(|| a.checked_sub(b), "-"), + &operand_values, ), - "*" => infix_operator_two_ints(|a: i64, b: i64| { - checked_binop(|| a.checked_mul(b), "*") - }, &operand_values + "*" => infix_operator_two_ints( + |a: i64, b: i64| checked_binop(|| a.checked_mul(b), "*"), + &operand_values, ), - "/" => infix_operator_two_ints(|a: i64, b: i64| { + "/" => infix_operator_two_ints( + |a: i64, b: i64| { if b == 0 { Err("division by zero".to_owned()) } else { checked_binop(|| a.checked_div(b), "/") } - }, &operand_values + }, + &operand_values, ), "%" => infix_operator_two_ints( |a: i64, b: i64| { @@ -299,18 +301,29 @@ fn push_token_to_either_stack( op_stack: &mut TokenStack, ) -> Result<(), String> { let result = match *token { - Token::Value { .. } => { out_stack.push((token_idx, token.clone())); Ok(()) }, + Token::Value { .. } => { + out_stack.push((token_idx, token.clone())); + Ok(()) + } - Token::InfixOp { .. } => if op_stack.is_empty() { + Token::InfixOp { .. } => { + if op_stack.is_empty() { + op_stack.push((token_idx, token.clone())); + Ok(()) + } else { + push_op_to_stack(token_idx, token, out_stack, op_stack) + } + } + + Token::PrefixOp { .. } => { op_stack.push((token_idx, token.clone())); Ok(()) - } else { - push_op_to_stack(token_idx, token, out_stack, op_stack) - }, + } - Token::PrefixOp { .. } => { op_stack.push((token_idx, token.clone())); Ok(()) }, - - Token::ParOpen => { op_stack.push((token_idx, token.clone())); Ok(()) }, + Token::ParOpen => { + op_stack.push((token_idx, token.clone())); + Ok(()) + } Token::ParClose => move_till_match_paren(out_stack, op_stack), }; @@ -352,7 +365,10 @@ fn push_op_to_stack( { loop { match op_stack.last() { - None => { op_stack.push((token_idx, token.clone())); return Ok(()) }, + None => { + op_stack.push((token_idx, token.clone())); + return Ok(()); + } Some(&(_, Token::ParOpen)) => { op_stack.push((token_idx, token.clone())); @@ -365,12 +381,14 @@ fn push_op_to_stack( precedence: prev_prec, .. }, - )) => if la && prev_prec >= prec || !la && prev_prec > prec { - out_stack.push(op_stack.pop().unwrap()) - } else { - op_stack.push((token_idx, token.clone())); - return Ok(()); - }, + )) => { + if la && prev_prec >= prec || !la && prev_prec > prec { + out_stack.push(op_stack.pop().unwrap()) + } else { + op_stack.push((token_idx, token.clone())); + return Ok(()); + } + } Some(&(_, Token::PrefixOp { .. })) => { op_stack.push((token_idx, token.clone())); diff --git a/src/expr/tokens.rs b/src/expr/tokens.rs index ba17edb8f..5ea6e17ee 100644 --- a/src/expr/tokens.rs +++ b/src/expr/tokens.rs @@ -141,12 +141,7 @@ fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) { } } -fn push_token_if_not_escaped( - acc: &mut Vec<(usize, Token)>, - tok_idx: usize, - token: Token, - s: &str, -) { +fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) { // Smells heuristics... :( let prev_is_plus = match acc.last() { None => false, diff --git a/src/factor/build.rs b/src/factor/build.rs index d1e73d5a2..0ef305c19 100644 --- a/src/factor/build.rs +++ b/src/factor/build.rs @@ -115,7 +115,8 @@ fn main() { file, "\n];\n\n#[allow(dead_code)]\npub const NEXT_PRIME: u64 = {};\n", x - ).unwrap(); + ) + .unwrap(); } #[test] diff --git a/src/factor/factor.rs b/src/factor/factor.rs index ba39f27e1..81f655eb7 100644 --- a/src/factor/factor.rs +++ b/src/factor/factor.rs @@ -20,12 +20,12 @@ extern crate uucore; use numeric::*; use rand::distributions::{Distribution, Uniform}; -use rand::{SeedableRng, thread_rng}; use rand::rngs::SmallRng; +use rand::{thread_rng, SeedableRng}; use std::cmp::{max, min}; use std::io::{stdin, BufRead}; -use std::num::Wrapping; use std::mem::swap; +use std::num::Wrapping; mod numeric; @@ -155,7 +155,10 @@ fn print_factors(num: u64) { } fn print_factors_str(num_str: &str) { - if let Err(e) = num_str.parse::().and_then(|x| { print_factors(x); Ok(()) }) { + if let Err(e) = num_str.parse::().and_then(|x| { + print_factors(x); + Ok(()) + }) { show_warning!("{}: {}", num_str, e); } } diff --git a/src/factor/numeric.rs b/src/factor/numeric.rs index b6c4c9543..474c80613 100644 --- a/src/factor/numeric.rs +++ b/src/factor/numeric.rs @@ -9,8 +9,8 @@ * that was distributed with this source code. */ -use std::u64::MAX as MAX_U64; use std::num::Wrapping; +use std::u64::MAX as MAX_U64; pub fn big_add(a: u64, b: u64, m: u64) -> u64 { let Wrapping(msb_mod_m) = Wrapping(MAX_U64) - Wrapping(m) + Wrapping(1); diff --git a/src/fmt/fmt.rs b/src/fmt/fmt.rs index 39167b9d3..d078d20a2 100644 --- a/src/fmt/fmt.rs +++ b/src/fmt/fmt.rs @@ -14,12 +14,12 @@ extern crate unicode_width; #[macro_use] extern crate uucore; -use std::cmp; -use std::io::{BufReader, BufWriter, Read}; -use std::fs::File; -use std::io::{stdin, stdout, Write}; use linebreak::break_lines; use parasplit::ParagraphStream; +use std::cmp; +use std::fs::File; +use std::io::{stdin, stdout, Write}; +use std::io::{BufReader, BufWriter, Read}; macro_rules! silent_unwrap( ($exp:expr) => ( diff --git a/src/fmt/linebreak.rs b/src/fmt/linebreak.rs index 2bf7b0ef9..7f1097cdc 100644 --- a/src/fmt/linebreak.rs +++ b/src/fmt/linebreak.rs @@ -7,12 +7,12 @@ * file that was distributed with this source code. */ -use FmtOptions; use parasplit::{ParaWords, Paragraph, WordInfo}; -use std::io::{BufWriter, Stdout, Write}; -use std::i64; use std::cmp; +use std::i64; +use std::io::{BufWriter, Stdout, Write}; use std::mem; +use FmtOptions; struct BreakArgs<'a> { opts: &'a FmtOptions, @@ -58,18 +58,19 @@ pub fn break_lines(para: &Paragraph, opts: &FmtOptions, ostream: &mut BufWriter< } }; // print the init, if it exists, and get its length - let p_init_len = w_len + if opts.crown || opts.tagged { - // handle "init" portion - silent_unwrap!(ostream.write_all(para.init_str.as_bytes())); - para.init_len - } else if !para.mail_header { - // for non-(crown, tagged) that's the same as a normal indent - silent_unwrap!(ostream.write_all(p_indent.as_bytes())); - p_indent_len - } else { - // except that mail headers get no indent at all - 0 - }; + let p_init_len = w_len + + if opts.crown || opts.tagged { + // handle "init" portion + silent_unwrap!(ostream.write_all(para.init_str.as_bytes())); + para.init_len + } else if !para.mail_header { + // for non-(crown, tagged) that's the same as a normal indent + silent_unwrap!(ostream.write_all(p_indent.as_bytes())); + p_indent_len + } else { + // except that mail headers get no indent at all + 0 + }; // write first word after writing init silent_unwrap!(ostream.write_all(w.as_bytes())); @@ -218,17 +219,15 @@ fn find_kp_breakpoints<'a, T: Iterator>>( ) -> Vec<(&'a WordInfo<'a>, bool)> { let mut iter = iter.peekable(); // set up the initial null linebreak - let mut linebreaks = vec![ - LineBreak { - prev: 0, - linebreak: None, - break_before: false, - demerits: 0, - prev_rat: 0.0f32, - length: args.init_len, - fresh: false, - }, - ]; + let mut linebreaks = vec![LineBreak { + prev: 0, + linebreak: None, + break_before: false, + demerits: 0, + prev_rat: 0.0f32, + length: args.init_len, + fresh: false, + }]; // this vec holds the current active linebreaks; next_ holds the breaks that will be active for // the next word let active_breaks = &mut vec![0]; @@ -275,7 +274,9 @@ fn find_kp_breakpoints<'a, T: Iterator>>( } // get the new length - let tlen = w.word_nchars + args.compute_width(w, active.length, active.fresh) + slen + let tlen = w.word_nchars + + args.compute_width(w, active.length, active.fresh) + + slen + active.length; // if tlen is longer than args.opts.width, we drop this break from the active list @@ -304,7 +305,8 @@ fn find_kp_breakpoints<'a, T: Iterator>>( // do not even consider adding a line that has too many demerits // also, try to detect overflow by checking signum let total_demerits = new_demerits + active.demerits; - if new_demerits < BAD_INFTY_SQ && total_demerits < ld_new + if new_demerits < BAD_INFTY_SQ + && total_demerits < ld_new && active.demerits.signum() <= new_demerits.signum() { ld_new = total_demerits; diff --git a/src/fmt/parasplit.rs b/src/fmt/parasplit.rs index de9734729..0d788d752 100644 --- a/src/fmt/parasplit.rs +++ b/src/fmt/parasplit.rs @@ -7,8 +7,8 @@ * file that was distributed with this source code. */ -use std::iter::Peekable; use std::io::{BufRead, Lines}; +use std::iter::Peekable; use std::slice::Iter; use unicode_width::UnicodeWidthChar; use FileOrStdReader; @@ -72,10 +72,7 @@ pub struct FileLines<'a> { impl<'a> FileLines<'a> { fn new<'b>(opts: &'b FmtOptions, lines: Lines<&'b mut FileOrStdReader>) -> FileLines<'b> { - FileLines { - opts, - lines, - } + FileLines { opts, lines } } // returns true if this line should be formatted @@ -363,8 +360,9 @@ impl<'a> Iterator for ParagraphStream<'a> { } } else if !second_done { // now we have enough info to handle crown margin and tagged mode - if // in both crown and tagged modes we require that prefix_len is the same - prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end + if + // in both crown and tagged modes we require that prefix_len is the same + prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end || // in tagged mode, indent has to be *different* on following lines self.opts.tagged && indent_len - 4 == fl.indent_len && indent_end == fl.indent_end @@ -380,7 +378,8 @@ impl<'a> Iterator for ParagraphStream<'a> { second_done = true; } else { // detect mismatch - if indent_end != fl.indent_end || pfxind_end != fl.pfxind_end + if indent_end != fl.indent_end + || pfxind_end != fl.pfxind_end || indent_len != fl.indent_len || prefix_len != fl.prefix_len { diff --git a/src/fold/fold.rs b/src/fold/fold.rs index 083dd8df6..20decdb38 100644 --- a/src/fold/fold.rs +++ b/src/fold/fold.rs @@ -70,9 +70,7 @@ pub fn uumain(args: Vec) -> i32 { fn handle_obsolete(args: &[String]) -> (Vec, Option) { for (i, arg) in args.iter().enumerate() { let slice = &arg; - if slice.starts_with('-') && slice.len() > 1 - && slice.chars().nth(1).unwrap().is_digit(10) - { + if slice.starts_with('-') && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { let mut v = args.to_vec(); v.remove(i); return (v, Some(slice[1..].to_owned())); @@ -145,11 +143,13 @@ fn fold_file(mut file: BufReader, bytes: bool, spaces: bool, width: let ncount = routput.chars().fold(0, |out, ch: char| { out + match ch { '\t' => 8, - '\x08' => if out > 0 { - !0 - } else { - 0 - }, + '\x08' => { + if out > 0 { + !0 + } else { + 0 + } + } '\r' => return 0, _ => 1, } diff --git a/src/groups/groups.rs b/src/groups/groups.rs index 406429eea..d320382d4 100644 --- a/src/groups/groups.rs +++ b/src/groups/groups.rs @@ -12,7 +12,7 @@ #[macro_use] extern crate uucore; -use uucore::entries::{get_groups, Locate, Passwd, gid2grp}; +use uucore::entries::{get_groups, gid2grp, Locate, Passwd}; static SYNTAX: &str = "[user]"; static SUMMARY: &str = "display current group names"; diff --git a/src/hashsum/digest.rs b/src/hashsum/digest.rs index d85403ee6..d9b885e00 100644 --- a/src/hashsum/digest.rs +++ b/src/hashsum/digest.rs @@ -71,7 +71,7 @@ impl Digest for sha1::Sha1 { // Implements the Digest trait for sha2 / sha3 algorithms with fixed ouput macro_rules! impl_digest_sha { - ($type: ty, $size: expr) => ( + ($type: ty, $size: expr) => { impl Digest for $type { fn new() -> Self { Self::default() @@ -89,14 +89,16 @@ macro_rules! impl_digest_sha { *self = Self::new(); } - fn output_bits(&self) -> usize { $size } + fn output_bits(&self) -> usize { + $size + } } - ) + }; } // Implements the Digest trait for sha2 / sha3 algorithms with variable ouput macro_rules! impl_digest_shake { - ($type: ty) => ( + ($type: ty) => { impl Digest for $type { fn new() -> Self { Self::default() @@ -114,9 +116,11 @@ macro_rules! impl_digest_shake { *self = Self::new(); } - fn output_bits(&self) -> usize { 0 } + fn output_bits(&self) -> usize { + 0 + } } - ) + }; } impl_digest_sha!(sha2::Sha224, 224); diff --git a/src/hashsum/hashsum.rs b/src/hashsum/hashsum.rs index ea8063403..abbb7686f 100644 --- a/src/hashsum/hashsum.rs +++ b/src/hashsum/hashsum.rs @@ -65,10 +65,26 @@ fn detect_algo( "sha512sum" => ("SHA512", Box::new(Sha512::new()) as Box, 512), "sha3sum" => match matches.opt_str("bits") { Some(bits_str) => match usize::from_str_radix(&bits_str, 10) { - Ok(224) => ("SHA3-224", Box::new(Sha3_224::new()) as Box, 224), - Ok(256) => ("SHA3-256", Box::new(Sha3_256::new()) as Box, 256), - Ok(384) => ("SHA3-384", Box::new(Sha3_384::new()) as Box, 384), - Ok(512) => ("SHA3-512", Box::new(Sha3_512::new()) as Box, 512), + Ok(224) => ( + "SHA3-224", + Box::new(Sha3_224::new()) as Box, + 224, + ), + Ok(256) => ( + "SHA3-256", + Box::new(Sha3_256::new()) as Box, + 256, + ), + Ok(384) => ( + "SHA3-384", + Box::new(Sha3_384::new()) as Box, + 384, + ), + Ok(512) => ( + "SHA3-512", + Box::new(Sha3_512::new()) as Box, + 512, + ), Ok(_) => crash!( 1, "Invalid output size for SHA3 (expected 224, 256, 384, or 512)" @@ -77,20 +93,44 @@ fn detect_algo( }, None => crash!(1, "--bits required for SHA3"), }, - "sha3-224sum" => ("SHA3-224", Box::new(Sha3_224::new()) as Box, 224), - "sha3-256sum" => ("SHA3-256", Box::new(Sha3_256::new()) as Box, 256), - "sha3-384sum" => ("SHA3-384", Box::new(Sha3_384::new()) as Box, 384), - "sha3-512sum" => ("SHA3-512", Box::new(Sha3_512::new()) as Box, 512), + "sha3-224sum" => ( + "SHA3-224", + Box::new(Sha3_224::new()) as Box, + 224, + ), + "sha3-256sum" => ( + "SHA3-256", + Box::new(Sha3_256::new()) as Box, + 256, + ), + "sha3-384sum" => ( + "SHA3-384", + Box::new(Sha3_384::new()) as Box, + 384, + ), + "sha3-512sum" => ( + "SHA3-512", + Box::new(Sha3_512::new()) as Box, + 512, + ), "shake128sum" => match matches.opt_str("bits") { Some(bits_str) => match usize::from_str_radix(&bits_str, 10) { - Ok(bits) => ("SHAKE128", Box::new(Shake128::new()) as Box, bits), + Ok(bits) => ( + "SHAKE128", + Box::new(Shake128::new()) as Box, + bits, + ), Err(err) => crash!(1, "{}", err), }, None => crash!(1, "--bits required for SHAKE-128"), }, "shake256sum" => match matches.opt_str("bits") { Some(bits_str) => match usize::from_str_radix(&bits_str, 10) { - Ok(bits) => ("SHAKE256", Box::new(Shake256::new()) as Box, bits), + Ok(bits) => ( + "SHAKE256", + Box::new(Shake256::new()) as Box, + bits, + ), Err(err) => crash!(1, "{}", err), }, None => crash!(1, "--bits required for SHAKE-256"), @@ -319,17 +359,7 @@ pub fn uumain(args: Vec) -> i32 { matches.free }; match hashsum( - name, - algo, - files, - binary, - check, - tag, - status, - quiet, - strict, - warn, - bits, + name, algo, files, binary, check, tag, status, quiet, strict, warn, bits, ) { Ok(()) => return 0, Err(e) => return e, @@ -449,7 +479,8 @@ fn hashsum( &mut ckf, binary_check, output_bits - )).to_ascii_lowercase(); + )) + .to_ascii_lowercase(); if sum == real_sum { if !quiet { println!("{}: OK", ck_filename); @@ -472,8 +503,12 @@ fn hashsum( } if !status { match bad_format.cmp(&1) { - std::cmp::Ordering::Equal => show_warning!("{} line is improperly formatted", bad_format), - std::cmp::Ordering::Greater => show_warning!("{} lines are improperly formatted", bad_format), + std::cmp::Ordering::Equal => { + show_warning!("{} line is improperly formatted", bad_format) + } + std::cmp::Ordering::Greater => { + show_warning!("{} lines are improperly formatted", bad_format) + } _ => {} }; if failed > 0 { diff --git a/src/head/head.rs b/src/head/head.rs index efc0ab8db..c9542d108 100644 --- a/src/head/head.rs +++ b/src/head/head.rs @@ -14,8 +14,8 @@ #[macro_use] extern crate uucore; -use std::io::{stdin, BufRead, BufReader, Read}; use std::fs::File; +use std::io::{stdin, BufRead, BufReader, Read}; use std::path::Path; use std::str::from_utf8; @@ -90,12 +90,14 @@ pub fn uumain(args: Vec) -> i32 { } } } - None => if let Some(count) = matches.opt_str("c") { - match count.parse::() { - Ok(m) => settings.mode = FilterMode::Bytes(m), - Err(e) => { - show_error!("invalid byte count '{}': {}", count, e); - return 1; + None => { + if let Some(count) = matches.opt_str("c") { + match count.parse::() { + Ok(m) => settings.mode = FilterMode::Bytes(m), + Err(e) => { + show_error!("invalid byte count '{}': {}", count, e); + return 1; + } } } } @@ -186,12 +188,16 @@ fn obsolete(options: &[String]) -> (Vec, Option) { // TODO: handle errors on read fn head(reader: &mut BufReader, settings: &Settings) -> bool { match settings.mode { - FilterMode::Bytes(count) => for byte in reader.bytes().take(count) { - print!("{}", byte.unwrap() as char); - }, - FilterMode::Lines(count) => for line in reader.lines().take(count) { - println!("{}", line.unwrap()); - }, + FilterMode::Bytes(count) => { + for byte in reader.bytes().take(count) { + print!("{}", byte.unwrap() as char); + } + } + FilterMode::Lines(count) => { + for line in reader.lines().take(count) { + println!("{}", line.unwrap()); + } + } } true } diff --git a/src/hostname/hostname.rs b/src/hostname/hostname.rs index 7c79af072..81e7eb6a8 100644 --- a/src/hostname/hostname.rs +++ b/src/hostname/hostname.rs @@ -17,21 +17,21 @@ extern crate winapi; #[macro_use] extern crate uucore; -use std::collections::hash_set::HashSet; -use std::iter::repeat; -use std::io; -use std::str; -use std::net::ToSocketAddrs; use getopts::Matches; +use std::collections::hash_set::HashSet; +use std::io; +use std::iter::repeat; +use std::net::ToSocketAddrs; +use std::str; #[cfg(windows)] -use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; -#[cfg(windows)] -use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW}; +use uucore::wide::*; #[cfg(windows)] use winapi::shared::minwindef::MAKEWORD; #[cfg(windows)] -use uucore::wide::*; +use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW}; +#[cfg(windows)] +use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; #[cfg(not(windows))] use libc::gethostname; @@ -63,12 +63,28 @@ pub fn uumain(args: Vec) -> i32 { fn execute(args: Vec) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) - .optflag("d", "domain", "Display the name of the DNS domain if possible") - .optflag("i", "ip-address", "Display the network address(es) of the host") + .optflag( + "d", + "domain", + "Display the name of the DNS domain if possible", + ) + .optflag( + "i", + "ip-address", + "Display the network address(es) of the host", + ) // TODO: support --long - .optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)") - .optflag("s", "short", "Display the short hostname (the portion before the first dot) if \ - possible") + .optflag( + "f", + "fqdn", + "Display the FQDN (Fully Qualified Domain Name) (default)", + ) + .optflag( + "s", + "short", + "Display the short hostname (the portion before the first dot) if \ + possible", + ) .parse(args); match matches.free.len() { diff --git a/src/id/id.rs b/src/id/id.rs index c8bd4f476..a32d955a3 100644 --- a/src/id/id.rs +++ b/src/id/id.rs @@ -16,16 +16,16 @@ #[macro_use] extern crate uucore; +use std::ffi::CStr; +use uucore::entries::{self, Group, Locate, Passwd}; pub use uucore::libc; use uucore::libc::{getlogin, uid_t}; -use uucore::entries::{self, Group, Locate, Passwd}; use uucore::process::{getegid, geteuid, getgid, getuid}; -use std::ffi::CStr; macro_rules! cstr2cow { - ($v:expr) => ( + ($v:expr) => { unsafe { CStr::from_ptr($v).to_string_lossy() } - ) + }; } #[cfg(not(target_os = "linux"))] diff --git a/src/install/install.rs b/src/install/install.rs index b99e93ace..03085d5c5 100644 --- a/src/install/install.rs +++ b/src/install/install.rs @@ -101,49 +101,115 @@ fn parse_opts(args: Vec) -> getopts::Matches { NAME ); new_coreopts!(&syntax, SUMMARY, LONG_HELP) - // TODO implement flag - .optflagopt("", "backup", "(unimplemented) make a backup of each existing destination\n \ - file", "CONTROL") - // TODO implement flag - .optflag("b", "", "(unimplemented) like --backup but does not accept an argument") + // TODO implement flag + .optflagopt( + "", + "backup", + "(unimplemented) make a backup of each existing destination\n \ + file", + "CONTROL", + ) + // TODO implement flag + .optflag( + "b", + "", + "(unimplemented) like --backup but does not accept an argument", + ) .optflag("c", "", "ignored") - // TODO implement flag - .optflag("C", "compare", "(unimplemented) compare each pair of source and destination\n \ - files, and in some cases, do not modify the destination at all") - .optflag("d", "directory", "treat all arguments as directory names.\n \ - create all components of the specified directories") - // TODO implement flag - .optflag("D", "", "(unimplemented) create all leading components of DEST except the\n \ - last, then copy SOURCE to DEST") - // TODO implement flag - .optflagopt("g", "group", "(unimplemented) set group ownership, instead of process'\n \ - current group", "GROUP") - .optflagopt("m", "mode", "set permission mode (as in chmod), instead\n \ - of rwxr-xr-x", "MODE") - // TODO implement flag - .optflagopt("o", "owner", "(unimplemented) set ownership (super-user only)", - "OWNER") - // TODO implement flag - .optflag("p", "preserve-timestamps", "(unimplemented) apply access/modification times\n \ - of SOURCE files to corresponding destination files") - // TODO implement flag + // TODO implement flag + .optflag( + "C", + "compare", + "(unimplemented) compare each pair of source and destination\n \ + files, and in some cases, do not modify the destination at all", + ) + .optflag( + "d", + "directory", + "treat all arguments as directory names.\n \ + create all components of the specified directories", + ) + // TODO implement flag + .optflag( + "D", + "", + "(unimplemented) create all leading components of DEST except the\n \ + last, then copy SOURCE to DEST", + ) + // TODO implement flag + .optflagopt( + "g", + "group", + "(unimplemented) set group ownership, instead of process'\n \ + current group", + "GROUP", + ) + .optflagopt( + "m", + "mode", + "set permission mode (as in chmod), instead\n \ + of rwxr-xr-x", + "MODE", + ) + // TODO implement flag + .optflagopt( + "o", + "owner", + "(unimplemented) set ownership (super-user only)", + "OWNER", + ) + // TODO implement flag + .optflag( + "p", + "preserve-timestamps", + "(unimplemented) apply access/modification times\n \ + of SOURCE files to corresponding destination files", + ) + // TODO implement flag .optflag("s", "strip", "(unimplemented) strip symbol tables") - // TODO implement flag - .optflagopt("", "strip-program", "(unimplemented) program used to strip binaries", - "PROGRAM") - // TODO implement flag - .optopt("S", "suffix", "(unimplemented) override the usual backup suffix", "SUFFIX") - // TODO implement flag - .optopt("t", "target-directory", "(unimplemented) move all SOURCE arguments into\n \ - DIRECTORY", "DIRECTORY") - // TODO implement flag - .optflag("T", "no-target-directory", "(unimplemented) treat DEST as a normal file") + // TODO implement flag + .optflagopt( + "", + "strip-program", + "(unimplemented) program used to strip binaries", + "PROGRAM", + ) + // TODO implement flag + .optopt( + "S", + "suffix", + "(unimplemented) override the usual backup suffix", + "SUFFIX", + ) + // TODO implement flag + .optopt( + "t", + "target-directory", + "(unimplemented) move all SOURCE arguments into\n \ + DIRECTORY", + "DIRECTORY", + ) + // TODO implement flag + .optflag( + "T", + "no-target-directory", + "(unimplemented) treat DEST as a normal file", + ) .optflag("v", "verbose", "explain what is being done") - // TODO implement flag - .optflag("P", "preserve-context", "(unimplemented) preserve security context") - // TODO implement flag - .optflagopt("Z", "context", "(unimplemented) set security context of files and\n \ - directories", "CONTEXT") + // TODO implement flag + .optflag( + "P", + "preserve-context", + "(unimplemented) preserve security context", + ) + // TODO implement flag + .optflagopt( + "Z", + "context", + "(unimplemented) set security context of files and\n \ + directories", + "CONTEXT", + ) .parse(args) } diff --git a/src/install/mode.rs b/src/install/mode.rs index 726b359df..06f458dc7 100644 --- a/src/install/mode.rs +++ b/src/install/mode.rs @@ -1,7 +1,7 @@ extern crate libc; -use std::path::Path; use std::fs; +use std::path::Path; #[cfg(not(windows))] use uucore::mode; diff --git a/src/join/join.rs b/src/join/join.rs index 7ae82fe6e..0c82473e4 100755 --- a/src/join/join.rs +++ b/src/join/join.rs @@ -14,10 +14,10 @@ extern crate clap; #[macro_use] extern crate uucore; +use clap::{App, Arg}; +use std::cmp::{min, Ordering}; use std::fs::File; use std::io::{stdin, BufRead, BufReader, Lines, Stdin}; -use std::cmp::{min, Ordering}; -use clap::{App, Arg}; static NAME: &str = "join"; static VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -425,11 +425,13 @@ impl<'a> State<'a> { if repr.uses_format() { repr.print_format(|spec| match *spec { Spec::Key => line.get_field(self.key), - Spec::Field(file_num, field_num) => if file_num == self.file_num { - line.get_field(field_num) - } else { - None - }, + Spec::Field(file_num, field_num) => { + if file_num == self.file_num { + line.get_field(field_num) + } else { + None + } + } }); } else { repr.print_field(line.get_field(self.key)); diff --git a/src/kill/kill.rs b/src/kill/kill.rs index 3d73f9093..f38fbc0fb 100644 --- a/src/kill/kill.rs +++ b/src/kill/kill.rs @@ -74,9 +74,7 @@ fn handle_obsolete(mut args: Vec) -> (Vec, Option) { while i < args.len() { // this is safe because slice is valid when it is referenced let slice = &args[i].clone(); - if slice.starts_with('-') && slice.len() > 1 - && slice.chars().nth(1).unwrap().is_digit(10) - { + if slice.starts_with('-') && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { let val = &slice[1..]; match val.parse() { Ok(num) => { diff --git a/src/link/link.rs b/src/link/link.rs index 4ff654f4b..ae5993d52 100644 --- a/src/link/link.rs +++ b/src/link/link.rs @@ -13,8 +13,8 @@ extern crate uucore; use std::fs::hard_link; -use std::path::Path; use std::io::Error; +use std::path::Path; static SYNTAX: &str = "[OPTIONS] FILE1 FILE2"; static SUMMARY: &str = "Create a link named FILE2 to FILE1"; diff --git a/src/ln/ln.rs b/src/ln/ln.rs index f5f5ddf53..2c791c135 100644 --- a/src/ln/ln.rs +++ b/src/ln/ln.rs @@ -67,24 +67,45 @@ pub fn uumain(args: Vec) -> i32 { NAME ); let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) - .optflag("b", "", "make a backup of each file that would otherwise be overwritten or \ - removed") - .optflagopt("", "backup", "make a backup of each file that would otherwise be overwritten \ - or removed", "METHOD") - // TODO: opts.optflag("d", "directory", "allow users with appropriate privileges to attempt \ - // to make hard links to directories"); + .optflag( + "b", + "", + "make a backup of each file that would otherwise be overwritten or \ + removed", + ) + .optflagopt( + "", + "backup", + "make a backup of each file that would otherwise be overwritten \ + or removed", + "METHOD", + ) + // TODO: opts.optflag("d", "directory", "allow users with appropriate privileges to attempt \ + // to make hard links to directories"); .optflag("f", "force", "remove existing destination files") - .optflag("i", "interactive", "prompt whether to remove existing destination files") - // TODO: opts.optflag("L", "logical", "dereference TARGETs that are symbolic links"); - // TODO: opts.optflag("n", "no-dereference", "treat LINK_NAME as a normal file if it is a \ - // symbolic link to a directory"); - // TODO: opts.optflag("P", "physical", "make hard links directly to symbolic links"); - // TODO: opts.optflag("r", "relative", "create symbolic links relative to link location"); + .optflag( + "i", + "interactive", + "prompt whether to remove existing destination files", + ) + // TODO: opts.optflag("L", "logical", "dereference TARGETs that are symbolic links"); + // TODO: opts.optflag("n", "no-dereference", "treat LINK_NAME as a normal file if it is a \ + // symbolic link to a directory"); + // TODO: opts.optflag("P", "physical", "make hard links directly to symbolic links"); + // TODO: opts.optflag("r", "relative", "create symbolic links relative to link location"); .optflag("s", "symbolic", "make symbolic links instead of hard links") .optopt("S", "suffix", "override the usual backup suffix", "SUFFIX") - .optopt("t", "target-directory", "specify the DIRECTORY in which to create the links", - "DIRECTORY") - .optflag("T", "no-target-directory", "treat LINK_NAME as a normal file always") + .optopt( + "t", + "target-directory", + "specify the DIRECTORY in which to create the links", + "DIRECTORY", + ) + .optflag( + "T", + "no-target-directory", + "treat LINK_NAME as a normal file always", + ) .optflag("v", "verbose", "print name of each linked file") .parse(args); diff --git a/src/ls/ls.rs b/src/ls/ls.rs index 56acc97dc..80641b291 100644 --- a/src/ls/ls.rs +++ b/src/ls/ls.rs @@ -9,12 +9,12 @@ // extern crate getopts; +extern crate number_prefix; extern crate term_grid; extern crate termsize; extern crate time; extern crate unicode_width; -extern crate number_prefix; -use number_prefix::{Standalone, Prefixed, decimal_prefix}; +use number_prefix::{decimal_prefix, Prefixed, Standalone}; use term_grid::{Cell, Direction, Filling, Grid, GridOptions}; use time::{strftime, Timespec}; @@ -30,20 +30,19 @@ extern crate lazy_static; #[macro_use] extern crate uucore; #[cfg(unix)] -use uucore::libc::{mode_t, S_ISGID, S_ISUID, S_ISVTX, S_IWOTH, - S_IXGRP, S_IXOTH, S_IXUSR}; +use uucore::libc::{mode_t, S_ISGID, S_ISUID, S_ISVTX, S_IWOTH, S_IXGRP, S_IXOTH, S_IXUSR}; -use std::fs; -use std::fs::{DirEntry, FileType, Metadata}; -use std::path::{Path, PathBuf}; use std::cmp::Reverse; #[cfg(unix)] use std::collections::HashMap; +use std::fs; +use std::fs::{DirEntry, FileType, Metadata}; +use std::path::{Path, PathBuf}; -#[cfg(any(unix, target_os = "redox"))] -use std::os::unix::fs::MetadataExt; #[cfg(unix)] use std::os::unix::fs::FileTypeExt; +#[cfg(any(unix, target_os = "redox"))] +use std::os::unix::fs::MetadataExt; #[cfg(unix)] use unicode_width::UnicodeWidthStr; @@ -63,7 +62,8 @@ static DEFAULT_COLORS: &str = "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do #[cfg(unix)] lazy_static! { - static ref LS_COLORS: String = std::env::var("LS_COLORS").unwrap_or_else(|_| DEFAULT_COLORS.to_string()); + static ref LS_COLORS: String = + std::env::var("LS_COLORS").unwrap_or_else(|_| DEFAULT_COLORS.to_string()); static ref COLOR_MAP: HashMap<&'static str, &'static str> = { let codes = LS_COLORS.split(':'); let mut map = HashMap::new(); @@ -163,7 +163,12 @@ pub fn uumain(args: Vec) -> i32 { directory. This is especially useful when listing very large directories, \ since not doing any sorting can be noticeably faster.", ) - .optflagopt("", "color", "Color output based on file type.", "always|auto|never") + .optflagopt( + "", + "color", + "Color output based on file type.", + "always|auto|never", + ) .parse(args); list(matches); @@ -357,19 +362,17 @@ fn display_items(items: &[PathBuf], strip: Option<&Path>, options: &getopts::Mat } } else { if !options.opt_present("1") { - let names = items - .iter() - .filter_map(|i| { - let md = get_metadata(i, options); - match md { - Err(e) => { - let filename = get_file_name(i, strip); - show_error!("{}: {}", filename, e); - None - } - Ok(md) => Some(display_file_name(&i, strip, &md, options)), + let names = items.iter().filter_map(|i| { + let md = get_metadata(i, options); + match md { + Err(e) => { + let filename = get_file_name(i, strip); + show_error!("{}: {}", filename, e); + None } - }); + Ok(md) => Some(display_file_name(&i, strip, &md, options)), + } + }); if let Some(size) = termsize::get() { let mut grid = Grid::new(GridOptions { @@ -512,7 +515,7 @@ fn display_file_size(metadata: &Metadata, options: &getopts::Matches) -> String if options.opt_present("human-readable") { match decimal_prefix(metadata.len() as f64) { Standalone(bytes) => bytes.to_string(), - Prefixed(prefix, bytes) => format!("{:.2}{}", bytes, prefix).to_uppercase() + Prefixed(prefix, bytes) => format!("{:.2}{}", bytes, prefix).to_uppercase(), } } else { metadata.len().to_string() @@ -596,9 +599,9 @@ fn color_name(name: String, typ: &str) -> String { #[cfg(unix)] macro_rules! has { - ($mode:expr, $perm:expr) => ( + ($mode:expr, $perm:expr) => { $mode & ($perm as mode_t) != 0 - ) + }; } #[cfg(unix)] diff --git a/src/mkdir/mkdir.rs b/src/mkdir/mkdir.rs index 2f37b2400..85ab67c48 100644 --- a/src/mkdir/mkdir.rs +++ b/src/mkdir/mkdir.rs @@ -60,10 +60,10 @@ pub fn uumain(args: Vec) -> i32 { let res: Option = u16::from_str_radix(&m, 8).ok(); match res { Some(r) => r, - _ => crash!(1, "no mode given") + _ => crash!(1, "no mode given"), } - }, - _ => 0o755 as u16 + } + _ => 0o755 as u16, }; let dirs = matches.free; @@ -112,7 +112,11 @@ fn exec(dirs: Vec, recursive: bool, mode: u16, verbose: bool) -> i32 { * Wrapper to catch errors, return 1 if failed */ fn mkdir(path: &Path, recursive: bool, mode: u16, verbose: bool) -> i32 { - let create_dir = if recursive { fs::create_dir_all } else { fs::create_dir }; + let create_dir = if recursive { + fs::create_dir_all + } else { + fs::create_dir + }; if let Err(e) = create_dir(path) { show_info!("{}: {}", path.display(), e.to_string()); return 1; @@ -124,17 +128,13 @@ fn mkdir(path: &Path, recursive: bool, mode: u16, verbose: bool) -> i32 { #[cfg(any(unix, target_os = "redox"))] fn chmod(path: &Path, mode: u16) -> i32 { - use fs::{Permissions, set_permissions}; - use std::os::unix::fs::{PermissionsExt}; + use fs::{set_permissions, Permissions}; + use std::os::unix::fs::PermissionsExt; let mode = Permissions::from_mode(u32::from(mode)); if let Err(err) = set_permissions(path, mode) { - show_error!( - "{}: {}", - path.display(), - err - ); + show_error!("{}: {}", path.display(), err); return 1; } 0 diff --git a/src/mkfifo/mkfifo.rs b/src/mkfifo/mkfifo.rs index 58d59cb1f..5c5107112 100644 --- a/src/mkfifo/mkfifo.rs +++ b/src/mkfifo/mkfifo.rs @@ -77,10 +77,7 @@ Create a FIFO with the given name.", for f in &matches.free { let err = unsafe { let name = CString::new(f.as_bytes()).unwrap(); - mkfifo( - name.as_ptr(), - mode as libc::mode_t, - ) + mkfifo(name.as_ptr(), mode as libc::mode_t) }; if err == -1 { show_error!( diff --git a/src/mknod/mknod.rs b/src/mknod/mknod.rs index 8429d741a..f7b8d97ee 100644 --- a/src/mknod/mknod.rs +++ b/src/mknod/mknod.rs @@ -31,8 +31,7 @@ const MODE_RW_UGO: mode_t = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_ #[inline(always)] fn makedev(maj: u64, min: u64) -> dev_t { // pick up from - ((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32)) - as dev_t + ((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32)) as dev_t } #[cfg(windows)] diff --git a/src/mktemp/mktemp.rs b/src/mktemp/mktemp.rs index a35e3bfba..5e200dbee 100644 --- a/src/mktemp/mktemp.rs +++ b/src/mktemp/mktemp.rs @@ -17,9 +17,9 @@ extern crate tempfile; extern crate uucore; use std::env; -use std::path::{is_separator, PathBuf}; -use std::mem::forget; use std::iter; +use std::mem::forget; +use std::path::{is_separator, PathBuf}; use rand::Rng; use tempfile::NamedTempFileOptions; diff --git a/src/mktemp/tempdir.rs b/src/mktemp/tempdir.rs index b3f2e60e1..187ade269 100644 --- a/src/mktemp/tempdir.rs +++ b/src/mktemp/tempdir.rs @@ -1,8 +1,8 @@ // Mainly taken from crate `tempdir` extern crate rand; -use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; +use rand::{thread_rng, Rng}; use std::io::Result as IOResult; use std::io::{Error, ErrorKind}; diff --git a/src/more/more.rs b/src/more/more.rs index 334be558b..44a61dc20 100644 --- a/src/more/more.rs +++ b/src/more/more.rs @@ -15,8 +15,8 @@ extern crate getopts; extern crate uucore; use getopts::Options; -use std::io::{stdout, Read, Write}; use std::fs::File; +use std::io::{stdout, Read, Write}; #[cfg(all(unix, not(target_os = "fuchsia")))] extern crate nix; diff --git a/src/mv/mv.rs b/src/mv/mv.rs index 5f96a5f1c..0c7be9e9d 100644 --- a/src/mv/mv.rs +++ b/src/mv/mv.rs @@ -14,8 +14,8 @@ extern crate getopts; #[macro_use] extern crate uucore; -use std::fs; use std::env; +use std::fs; use std::io::{stdin, Result}; use std::path::{Path, PathBuf}; @@ -202,7 +202,9 @@ fn determine_backup_suffix(backup_mode: BackupMode, matches: &getopts::Matches) ); } } - } else if let (Ok(s), BackupMode::SimpleBackup) = (env::var("SIMPLE_BACKUP_SUFFIX"), backup_mode) { + } else if let (Ok(s), BackupMode::SimpleBackup) = + (env::var("SIMPLE_BACKUP_SUFFIX"), backup_mode) + { s } else { "~".to_owned() @@ -257,7 +259,9 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 { Err(e) => { show_error!( "cannot move ‘{}’ to ‘{}’: {}", - source.display(), target.display(), e + source.display(), + target.display(), + e ); 1 } @@ -269,7 +273,8 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 { } else if target.exists() && source.is_dir() { show_error!( "cannot overwrite non-directory ‘{}’ with directory ‘{}’", - target.display(), source.display() + target.display(), + source.display() ); return 1; } @@ -359,8 +364,7 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> { fs::rename(to, p)?; } - if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? - { + if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? { return Ok(()); } } @@ -372,7 +376,10 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> { if is_empty_dir(to) { fs::remove_dir(to)? } else { - return Err(std::io::Error::new(std::io::ErrorKind::Other, "Directory not empty")); + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + "Directory not empty", + )); } } } @@ -425,9 +432,7 @@ fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { fn is_empty_dir(path: &PathBuf) -> bool { match fs::read_dir(path) { - Ok(contents) => { - contents.peekable().peek().is_none() - }, - Err(_e) => { false } + Ok(contents) => contents.peekable().peek().is_none(), + Err(_e) => false, } } diff --git a/src/nl/nl.rs b/src/nl/nl.rs index e24d4f0b8..be43101e1 100644 --- a/src/nl/nl.rs +++ b/src/nl/nl.rs @@ -336,7 +336,9 @@ fn nl(reader: &mut BufReader, settings: &Settings) { // A line number is to be printed. let w = if settings.number_width > line_no_width { settings.number_width - line_no_width - } else { 0 }; + } else { + 0 + }; let fill: String = repeat(fill_char).take(w).collect(); match settings.number_format { NumberFormat::Left => println!( diff --git a/src/nohup/nohup.rs b/src/nohup/nohup.rs index b71c16fb5..574cd82fb 100644 --- a/src/nohup/nohup.rs +++ b/src/nohup/nohup.rs @@ -15,14 +15,14 @@ extern crate libc; #[macro_use] extern crate uucore; -use libc::{c_char, execvp, signal, dup2}; +use libc::{c_char, dup2, execvp, signal}; use libc::{SIGHUP, SIG_IGN}; +use std::env; use std::ffi::CString; use std::fs::{File, OpenOptions}; use std::io::Error; use std::os::unix::prelude::*; use std::path::{Path, PathBuf}; -use std::env; use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive}; static NAME: &str = "nohup"; diff --git a/src/nproc/nproc.rs b/src/nproc/nproc.rs index 0b7d48ceb..3d6b9151c 100644 --- a/src/nproc/nproc.rs +++ b/src/nproc/nproc.rs @@ -108,7 +108,12 @@ Print the number of cores available to the current process.", 0 } -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd"))] +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +))] fn num_cpus_all() -> usize { let nprocs = unsafe { libc::sysconf(_SC_NPROCESSORS_CONF) }; if nprocs == 1 { @@ -123,8 +128,12 @@ fn num_cpus_all() -> usize { } // Other platform(e.g., windows), num_cpus::get() directly. -#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd", - target_os = "netbsd")))] +#[cfg(not(any( + target_os = "linux", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +)))] fn num_cpus_all() -> usize { num_cpus::get() } diff --git a/src/numfmt/numfmt.rs b/src/numfmt/numfmt.rs index 32e3731db..8a639a37f 100644 --- a/src/numfmt/numfmt.rs +++ b/src/numfmt/numfmt.rs @@ -70,7 +70,8 @@ impl fmt::Display for DisplayableSuffix { RawSuffix::E => write!(f, "E"), RawSuffix::Z => write!(f, "Z"), RawSuffix::Y => write!(f, "Y"), - }.and_then(|()| match with_i { + } + .and_then(|()| match with_i { true => write!(f, "i"), false => Ok(()), }) diff --git a/src/od/byteorder_io.rs b/src/od/byteorder_io.rs index 33f617910..5d7ad4cab 100644 --- a/src/od/byteorder_io.rs +++ b/src/od/byteorder_io.rs @@ -1,8 +1,8 @@ // workaround until https://github.com/BurntSushi/byteorder/issues/41 has been fixed // based on: https://github.com/netvl/immeta/blob/4460ee/src/utils.rs#L76 -use byteorder::{BigEndian, LittleEndian, NativeEndian}; use byteorder::ByteOrder as ByteOrderTrait; +use byteorder::{BigEndian, LittleEndian, NativeEndian}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum ByteOrder { diff --git a/src/od/inputdecoder.rs b/src/od/inputdecoder.rs index 50a4c081b..ea75ef237 100644 --- a/src/od/inputdecoder.rs +++ b/src/od/inputdecoder.rs @@ -1,8 +1,8 @@ -use std::io; use byteorder_io::ByteOrder; +use half::f16; use multifilereader::HasError; use peekreader::PeekRead; -use half::f16; +use std::io; /// Processes an input and provides access to the data read in various formats /// @@ -60,7 +60,8 @@ where /// calls `peek_read` on the internal stream to (re)fill the buffer. Returns a /// MemoryDecoder providing access to the result or returns an i/o error. pub fn peek_read(&mut self) -> io::Result { - match self.input + match self + .input .peek_read(self.data.as_mut_slice(), self.reserved_peek_length) { Ok((n, p)) => { @@ -157,9 +158,9 @@ impl<'a> MemoryDecoder<'a> { #[cfg(test)] mod tests { use super::*; - use std::io::Cursor; - use peekreader::PeekReader; use byteorder_io::ByteOrder; + use peekreader::PeekReader; + use std::io::Cursor; #[test] fn smoke_test() { diff --git a/src/od/mockstream.rs b/src/od/mockstream.rs index 3523caf58..f66f1dec7 100644 --- a/src/od/mockstream.rs +++ b/src/od/mockstream.rs @@ -1,7 +1,7 @@ // https://github.com/lazy-bitfield/rust-mockstream/pull/2 -use std::io::{Cursor, Error, ErrorKind, Read, Result}; use std::error::Error as errorError; +use std::io::{Cursor, Error, ErrorKind, Read, Result}; /// `FailingMockStream` mocks a stream which will fail upon read or write /// diff --git a/src/od/multifilereader.rs b/src/od/multifilereader.rs index b0fb34b8d..48951db94 100644 --- a/src/od/multifilereader.rs +++ b/src/od/multifilereader.rs @@ -1,7 +1,7 @@ use std; +use std::fs::File; use std::io; use std::io::BufReader; -use std::fs::File; use std::vec::Vec; pub enum InputSource<'a> { @@ -125,8 +125,8 @@ impl<'b> HasError for MultifileReader<'b> { #[cfg(test)] mod tests { use super::*; - use std::io::{Cursor, ErrorKind, Read}; use mockstream::*; + use std::io::{Cursor, ErrorKind, Read}; #[test] fn test_multi_file_reader_one_read() { diff --git a/src/od/od.rs b/src/od/od.rs index 9ed0d3953..c8982c630 100644 --- a/src/od/od.rs +++ b/src/od/od.rs @@ -16,36 +16,36 @@ extern crate half; #[macro_use] extern crate uucore; -mod multifilereader; -mod partialreader; -mod peekreader; mod byteorder_io; mod formatteriteminfo; -mod prn_int; -mod prn_char; -mod prn_float; -mod parse_nrofbytes; -mod parse_formats; -mod parse_inputs; -mod inputoffset; mod inputdecoder; -mod output_info; +mod inputoffset; #[cfg(test)] mod mockstream; +mod multifilereader; +mod output_info; +mod parse_formats; +mod parse_inputs; +mod parse_nrofbytes; +mod partialreader; +mod peekreader; +mod prn_char; +mod prn_float; +mod prn_int; -use std::cmp; use byteorder_io::*; +use formatteriteminfo::*; +use inputdecoder::{InputDecoder, MemoryDecoder}; +use inputoffset::{InputOffset, Radix}; use multifilereader::*; +use output_info::OutputInfo; +use parse_formats::{parse_format_flags, ParsedFormatterItemInfo}; +use parse_inputs::{parse_inputs, CommandLineInputs}; +use parse_nrofbytes::parse_number_of_bytes; use partialreader::*; use peekreader::*; -use formatteriteminfo::*; -use parse_nrofbytes::parse_number_of_bytes; -use parse_formats::{parse_format_flags, ParsedFormatterItemInfo}; use prn_char::format_ascii_dump; -use parse_inputs::{parse_inputs, CommandLineInputs}; -use inputoffset::{InputOffset, Radix}; -use inputdecoder::{InputDecoder, MemoryDecoder}; -use output_info::OutputInfo; +use std::cmp; static VERSION: &str = env!("CARGO_PKG_VERSION"); const PEEK_BUFFER_SIZE: usize = 4; // utf-8 can be 4 bytes @@ -379,7 +379,8 @@ where memory_decoder.zero_out_buffer(length, max_used); } - if !output_info.output_duplicates && length == line_bytes + if !output_info.output_duplicates + && length == line_bytes && memory_decoder.get_buffer(0) == &previous_bytes[..] { if !duplicate_line { diff --git a/src/od/output_info.rs b/src/od/output_info.rs index edcccd913..01e48c002 100644 --- a/src/od/output_info.rs +++ b/src/od/output_info.rs @@ -1,7 +1,7 @@ +use formatteriteminfo::FormatterItemInfo; +use parse_formats::ParsedFormatterItemInfo; use std::cmp; use std::slice::Iter; -use parse_formats::ParsedFormatterItemInfo; -use formatteriteminfo::FormatterItemInfo; /// Size in bytes of the max datatype. ie set to 16 for 128-bit numbers. const MAX_BYTES_PER_UNIT: usize = 8; diff --git a/src/od/parse_formats.rs b/src/od/parse_formats.rs index 36ce3604e..872e5840c 100644 --- a/src/od/parse_formats.rs +++ b/src/od/parse_formats.rs @@ -1,7 +1,7 @@ use formatteriteminfo::FormatterItemInfo; -use prn_int::*; use prn_char::*; use prn_float::*; +use prn_int::*; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct ParsedFormatterItemInfo { @@ -539,7 +539,8 @@ fn test_mixed_formats() { "--".to_string(), "-h".to_string(), "--format=f8".to_string(), - ]).unwrap(), + ]) + .unwrap(), vec![ ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC64S, false), // I ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC8U, true), // tu1z diff --git a/src/od/parse_inputs.rs b/src/od/parse_inputs.rs index b777b8e16..21da091e1 100644 --- a/src/od/parse_inputs.rs +++ b/src/od/parse_inputs.rs @@ -323,23 +323,27 @@ mod tests { parse_inputs(&MockOptions::new( vec!["file1", "10", "10"], vec!["traditional"] - )).unwrap() + )) + .unwrap() ); parse_inputs(&MockOptions::new( vec!["10", "file1", "10"], vec!["traditional"], - )).unwrap_err(); + )) + .unwrap_err(); parse_inputs(&MockOptions::new( vec!["10", "10", "file1"], vec!["traditional"], - )).unwrap_err(); + )) + .unwrap_err(); parse_inputs(&MockOptions::new( vec!["10", "10", "10", "10"], vec!["traditional"], - )).unwrap_err(); + )) + .unwrap_err(); } fn parse_offset_operand_str(s: &str) -> Result { diff --git a/src/od/partialreader.rs b/src/od/partialreader.rs index d8e2310d2..265f13dae 100644 --- a/src/od/partialreader.rs +++ b/src/od/partialreader.rs @@ -1,7 +1,7 @@ +use multifilereader::HasError; use std::cmp; use std::io; use std::io::Read; -use multifilereader::HasError; /// When a large number of bytes must be skipped, it will be read into a /// dynamically allocated buffer. The buffer will be limited to this size. @@ -21,11 +21,7 @@ impl PartialReader { /// `skip` bytes, and limits the output to `limit` bytes. Set `limit` /// to `None` if there should be no limit. pub fn new(inner: R, skip: usize, limit: Option) -> Self { - PartialReader { - inner, - skip, - limit, - } + PartialReader { inner, skip, limit } } } @@ -77,9 +73,9 @@ impl HasError for PartialReader { #[cfg(test)] mod tests { use super::*; - use std::io::{Cursor, ErrorKind, Read}; - use std::error::Error; use mockstream::*; + use std::error::Error; + use std::io::{Cursor, ErrorKind, Read}; #[test] fn test_read_without_limits() { diff --git a/src/od/peekreader.rs b/src/od/peekreader.rs index 10428a77f..be82e1266 100644 --- a/src/od/peekreader.rs +++ b/src/od/peekreader.rs @@ -1,8 +1,8 @@ //! Contains the trait `PeekRead` and type `PeekReader` implementing it. +use multifilereader::HasError; use std::io; use std::io::{Read, Write}; -use multifilereader::HasError; /// A trait which supplies a function to peek into a stream without /// actually reading it. diff --git a/src/od/prn_char.rs b/src/od/prn_char.rs index 58ad323ef..fadc2d11b 100644 --- a/src/od/prn_char.rs +++ b/src/od/prn_char.rs @@ -1,5 +1,5 @@ -use std::str::from_utf8; use formatteriteminfo::*; +use std::str::from_utf8; pub static FORMAT_ITEM_A: FormatterItemInfo = FormatterItemInfo { byte_size: 1, diff --git a/src/od/prn_float.rs b/src/od/prn_float.rs index 99e259b20..109ce041a 100644 --- a/src/od/prn_float.rs +++ b/src/od/prn_float.rs @@ -1,8 +1,8 @@ -use std::num::FpCategory; +use formatteriteminfo::*; use half::f16; use std::f32; use std::f64; -use formatteriteminfo::*; +use std::num::FpCategory; pub static FORMAT_ITEM_F16: FormatterItemInfo = FormatterItemInfo { byte_size: 2, diff --git a/src/od/prn_int.rs b/src/od/prn_int.rs index cc47a16e7..0de656117 100644 --- a/src/od/prn_int.rs +++ b/src/od/prn_int.rs @@ -1,11 +1,23 @@ use formatteriteminfo::*; /// format string to print octal using `int_writer_unsigned` -macro_rules! OCT { () => { " {:0width$o}" }} +macro_rules! OCT { + () => { + " {:0width$o}" + }; +} /// format string to print hexadecimal using `int_writer_unsigned` -macro_rules! HEX { () => { " {:0width$x}" }} +macro_rules! HEX { + () => { + " {:0width$x}" + }; +} /// format string to print decimal using `int_writer_unsigned` or `int_writer_signed` -macro_rules! DEC { () => { " {:width$}" }} +macro_rules! DEC { + () => { + " {:width$}" + }; +} /// defines a static struct of type `FormatterItemInfo` called `$NAME` /// @@ -15,9 +27,7 @@ macro_rules! DEC { () => { " {:width$}" }} macro_rules! int_writer_unsigned { ($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => { fn $function(p: u64) -> String { - format!($format_str, - p, - width = $print_width - 1) + format!($format_str, p, width = $print_width - 1) } pub static $NAME: FormatterItemInfo = FormatterItemInfo { @@ -25,7 +35,7 @@ macro_rules! int_writer_unsigned { print_width: $print_width, formatter: FormatWriter::IntWriter($function), }; - } + }; } /// defines a static struct of type `FormatterItemInfo` called `$NAME` @@ -37,9 +47,7 @@ macro_rules! int_writer_signed { ($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => { fn $function(p: u64) -> String { let s = sign_extend(p, $byte_size); - format!($format_str, - s, - width = $print_width - 1) + format!($format_str, s, width = $print_width - 1) } pub static $NAME: FormatterItemInfo = FormatterItemInfo { @@ -47,7 +55,7 @@ macro_rules! int_writer_signed { print_width: $print_width, formatter: FormatWriter::IntWriter($function), }; - } + }; } /// Extends a signed number in `item` of `itembytes` bytes into a (signed) i64 diff --git a/src/paste/paste.rs b/src/paste/paste.rs index 59e4762ee..3a1e209b8 100644 --- a/src/paste/paste.rs +++ b/src/paste/paste.rs @@ -14,9 +14,9 @@ extern crate getopts; #[macro_use] extern crate uucore; +use std::fs::File; use std::io::{stdin, BufRead, BufReader, Read}; use std::iter::repeat; -use std::fs::File; use std::path::Path; static NAME: &str = "paste"; @@ -60,7 +60,9 @@ FILE, separated by TABs, to standard output.", println!("{} {}", NAME, VERSION); } else { let serial = matches.opt_present("serial"); - let delimiters = matches.opt_str("delimiters").unwrap_or_else(|| "\t".to_owned()); + let delimiters = matches + .opt_str("delimiters") + .unwrap_or_else(|| "\t".to_owned()); paste(matches.free, serial, delimiters); } diff --git a/src/pathchk/pathchk.rs b/src/pathchk/pathchk.rs index 83d30f5d2..36bb591b1 100644 --- a/src/pathchk/pathchk.rs +++ b/src/pathchk/pathchk.rs @@ -89,7 +89,9 @@ pub fn uumain(args: Vec) -> i32 { let mut res = if matches.free.is_empty() { show_error!("missing operand\nTry {} --help for more information", NAME); false - } else { true }; + } else { + true + }; // free strings are path operands // FIXME: TCS, seems inefficient and overly verbose (?) for p in matches.free { @@ -233,12 +235,14 @@ fn check_searchable(path: &str) -> bool { // we use lstat, just like the original implementation match fs::symlink_metadata(path) { Ok(_) => true, - Err(e) => if e.kind() == ErrorKind::NotFound { - true - } else { - writeln!(&mut std::io::stderr(), "{}", e); - false - }, + Err(e) => { + if e.kind() == ErrorKind::NotFound { + true + } else { + writeln!(&mut std::io::stderr(), "{}", e); + false + } + } } } diff --git a/src/pinky/pinky.rs b/src/pinky/pinky.rs index f604846d5..a3e506ad7 100644 --- a/src/pinky/pinky.rs +++ b/src/pinky/pinky.rs @@ -11,9 +11,9 @@ #[macro_use] extern crate uucore; -use uucore::utmpx::{self, time, Utmpx}; -use uucore::libc::S_IWGRP; use uucore::entries::{Locate, Passwd}; +use uucore::libc::S_IWGRP; +use uucore::utmpx::{self, time, Utmpx}; use std::io::prelude::*; use std::io::BufReader; @@ -291,7 +291,7 @@ impl Pinky { if self.names.is_empty() { self.print_entry(&ut) } else if self.names.iter().any(|n| n.as_str() == ut.user()) { - self.print_entry(&ut); + self.print_entry(&ut); } } } diff --git a/src/printf/cli.rs b/src/printf/cli.rs index a6d185017..62aeb8a7c 100644 --- a/src/printf/cli.rs +++ b/src/printf/cli.rs @@ -1,7 +1,7 @@ //! stdio convenience fns -use std::io::{stderr, stdout, Write}; use std::env; +use std::io::{stderr, stdout, Write}; pub const EXIT_OK: i32 = 0; pub const EXIT_ERR: i32 = 1; diff --git a/src/printf/memo.rs b/src/printf/memo.rs index 226178e4b..4d26efc15 100644 --- a/src/printf/memo.rs +++ b/src/printf/memo.rs @@ -5,13 +5,13 @@ //! 2. feeds remaining arguments into function //! that prints tokens. +use cli; +use itertools::put_back_n; use std::iter::Peekable; use std::slice::Iter; -use itertools::put_back_n; -use cli; +use tokenize::sub::Sub; use tokenize::token::{Token, Tokenizer}; use tokenize::unescaped_text::UnescapedText; -use tokenize::sub::Sub; pub struct Memo { tokens: Vec>, diff --git a/src/printf/tokenize/mod.rs b/src/printf/tokenize/mod.rs index dfcdeb095..dfe44a0e5 100644 --- a/src/printf/tokenize/mod.rs +++ b/src/printf/tokenize/mod.rs @@ -1,5 +1,5 @@ -pub mod token; -pub mod sub; -pub mod unescaped_text; #[allow(clippy::module_inception)] mod num_format; +pub mod sub; +pub mod token; +pub mod unescaped_text; diff --git a/src/printf/tokenize/num_format/formatter.rs b/src/printf/tokenize/num_format/formatter.rs index aa5cf18a7..f770823de 100644 --- a/src/printf/tokenize/num_format/formatter.rs +++ b/src/printf/tokenize/num_format/formatter.rs @@ -1,10 +1,10 @@ //! Primitives used by num_format and sub_modules. //! never dealt with above (e.g. Sub Tokenizer never uses these) -use std::str::Chars; -use itertools::{put_back_n, PutBackN}; -use cli; use super::format_field::FormatField; +use cli; +use itertools::{put_back_n, PutBackN}; +use std::str::Chars; // contains the rough ingredients to final // output for a number, organized together diff --git a/src/printf/tokenize/num_format/formatters/base_conv/tests.rs b/src/printf/tokenize/num_format/formatters/base_conv/tests.rs index b69dcdb65..55e7fdfca 100644 --- a/src/printf/tokenize/num_format/formatters/base_conv/tests.rs +++ b/src/printf/tokenize/num_format/formatters/base_conv/tests.rs @@ -1,5 +1,4 @@ #[cfg(test)] - use super::*; #[test] diff --git a/src/printf/tokenize/num_format/formatters/cninetyninehexfloatf.rs b/src/printf/tokenize/num_format/formatters/cninetyninehexfloatf.rs index 72dc13af2..6e9cdc757 100644 --- a/src/printf/tokenize/num_format/formatters/cninetyninehexfloatf.rs +++ b/src/printf/tokenize/num_format/formatters/cninetyninehexfloatf.rs @@ -1,9 +1,9 @@ //! formatter for %a %F C99 Hex-floating-point subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; -use super::float_common::{primitive_to_str_common, FloatAnalysis}; use super::base_conv; use super::base_conv::RadixDef; +use super::float_common::{primitive_to_str_common, FloatAnalysis}; pub struct CninetyNineHexFloatf { as_num: f64, diff --git a/src/printf/tokenize/num_format/formatters/float_common.rs b/src/printf/tokenize/num_format/formatters/float_common.rs index b5fc98d92..49ebf035d 100644 --- a/src/printf/tokenize/num_format/formatters/float_common.rs +++ b/src/printf/tokenize/num_format/formatters/float_common.rs @@ -28,9 +28,9 @@ fn has_enough_digits( false //undecidable without converting } } else if hex_input { - ((((string_position - 1) - starting_position) * 9) / 8 >= limit) + ((((string_position - 1) - starting_position) * 9) / 8 >= limit) } else { - ((string_position - 1) - starting_position >= limit) + ((string_position - 1) - starting_position >= limit) } } @@ -72,7 +72,8 @@ impl FloatAnalysis { } } } - if ret.decimal_pos.is_some() && pos_before_first_nonzero_after_decimal.is_none() + if ret.decimal_pos.is_some() + && pos_before_first_nonzero_after_decimal.is_none() && e != '0' { pos_before_first_nonzero_after_decimal = Some(i - 1); @@ -180,10 +181,7 @@ fn round_terminal_digit( if position < after_dec.len() { let digit_at_pos: char; { - digit_at_pos = (&after_dec[position..=position]) - .chars() - .next() - .expect(""); + digit_at_pos = (&after_dec[position..=position]).chars().next().expect(""); } if let '5'..='9' = digit_at_pos { let (new_after_dec, finished_in_dec) = _round_str_from(&after_dec, position); diff --git a/src/printf/tokenize/num_format/formatters/intf.rs b/src/printf/tokenize/num_format/formatters/intf.rs index 35cd8711d..c4ba35284 100644 --- a/src/printf/tokenize/num_format/formatters/intf.rs +++ b/src/printf/tokenize/num_format/formatters/intf.rs @@ -1,11 +1,12 @@ //! formatter for unsigned and signed int subs //! unsigned ints: %X %x (hex u64) %o (octal u64) %u (base ten u64) //! signed ints: %i %d (both base ten i64) -use std::u64; -use std::i64; use super::super::format_field::FormatField; -use super::super::formatter::{get_it_at, warn_incomplete_conv, Base, FormatPrimitive, Formatter, - InPrefix}; +use super::super::formatter::{ + get_it_at, warn_incomplete_conv, Base, FormatPrimitive, Formatter, InPrefix, +}; +use std::i64; +use std::u64; pub struct Intf { a: u32, diff --git a/src/printf/tokenize/num_format/formatters/mod.rs b/src/printf/tokenize/num_format/formatters/mod.rs index 329e36d87..f6e2e7389 100644 --- a/src/printf/tokenize/num_format/formatters/mod.rs +++ b/src/printf/tokenize/num_format/formatters/mod.rs @@ -1,7 +1,7 @@ -pub mod intf; -pub mod floatf; +mod base_conv; pub mod cninetyninehexfloatf; -pub mod scif; pub mod decf; mod float_common; -mod base_conv; +pub mod floatf; +pub mod intf; +pub mod scif; diff --git a/src/printf/tokenize/num_format/num_format.rs b/src/printf/tokenize/num_format/num_format.rs index b0a4a3f4b..e84116bfc 100644 --- a/src/printf/tokenize/num_format/num_format.rs +++ b/src/printf/tokenize/num_format/num_format.rs @@ -1,15 +1,15 @@ //! handles creating printed output for numeric substitutions -use std::env; -use std::vec::Vec; -use cli; use super::format_field::{FieldType, FormatField}; use super::formatter::{Base, FormatPrimitive, Formatter, InPrefix}; -use super::formatters::intf::Intf; -use super::formatters::floatf::Floatf; use super::formatters::cninetyninehexfloatf::CninetyNineHexFloatf; -use super::formatters::scif::Scif; use super::formatters::decf::Decf; +use super::formatters::floatf::Floatf; +use super::formatters::intf::Intf; +use super::formatters::scif::Scif; +use cli; +use std::env; +use std::vec::Vec; pub fn warn_expected_numeric(pf_arg: &str) { // important: keep println here not print @@ -21,13 +21,15 @@ pub fn warn_expected_numeric(pf_arg: &str) { fn warn_char_constant_ign(remaining_bytes: Vec) { match env::var("POSIXLY_CORRECT") { Ok(_) => {} - Err(e) => if let env::VarError::NotPresent = e { - cli::err_msg(&format!( - "warning: {:?}: character(s) following character \ - constant have been ignored", - &*remaining_bytes - )); - }, + Err(e) => { + if let env::VarError::NotPresent = e { + cli::err_msg(&format!( + "warning: {:?}: character(s) following character \ + constant have been ignored", + &*remaining_bytes + )); + } + } } } @@ -63,9 +65,7 @@ fn get_provided(str_in_opt: Option<&String>) -> Option { }) } // first byte is not quote - _ => { - None - } // no first byte + _ => None, // no first byte } } else { Some(0 as u8) diff --git a/src/printf/tokenize/sub.rs b/src/printf/tokenize/sub.rs index 3e538c518..03fef5797 100644 --- a/src/printf/tokenize/sub.rs +++ b/src/printf/tokenize/sub.rs @@ -3,16 +3,16 @@ //! it is created by Sub's implementation of the Tokenizer trait //! Subs which have numeric field chars make use of the num_format //! submodule -use std::slice::Iter; -use std::iter::Peekable; -use std::str::Chars; -use std::process::exit; -use cli; -use itertools::{put_back_n, PutBackN}; -use super::token; -use super::unescaped_text::UnescapedText; use super::num_format::format_field::{FieldType, FormatField}; use super::num_format::num_format; +use super::token; +use super::unescaped_text::UnescapedText; +use cli; +use itertools::{put_back_n, PutBackN}; +use std::iter::Peekable; +use std::process::exit; +use std::slice::Iter; +use std::str::Chars; // use std::collections::HashSet; fn err_conv(sofar: &str) { @@ -155,22 +155,10 @@ impl SubParser { // though, as we want to mimic the original behavior of printing // the field as interpreted up until the error in the field. - let mut legal_fields = vec![// 'a', 'A', //c99 hex float implementation not yet complete - 'b', - 'c', - 'd', - 'e', - 'E', - 'f', - 'F', - 'g', - 'G', - 'i', - 'o', - 's', - 'u', - 'x', - 'X']; + let mut legal_fields = vec![ + // 'a', 'A', //c99 hex float implementation not yet complete + 'b', 'c', 'd', 'e', 'E', 'f', 'F', 'g', 'G', 'i', 'o', 's', 'u', 'x', 'X', + ]; let mut specifiers = vec!['h', 'j', 'l', 'L', 't', 'z']; legal_fields.sort(); specifiers.sort(); @@ -289,8 +277,12 @@ impl SubParser { } } } else { - if let Some(x) = n_ch { it.put_back(x) }; - if let Some(x) = preface { it.put_back(x) }; + if let Some(x) = n_ch { + it.put_back(x) + }; + if let Some(x) = preface { + it.put_back(x) + }; false } } @@ -302,7 +294,8 @@ impl SubParser { || (field_char == 'c' && (self.min_width_tmp == Some(String::from("0")) || self.past_decimal)) || (field_char == 'b' - && (self.min_width_tmp.is_some() || self.past_decimal + && (self.min_width_tmp.is_some() + || self.past_decimal || self.second_field_tmp.is_some())) { err_conv(&self.text_so_far); @@ -393,8 +386,7 @@ impl token::Token for Sub { "{}", match field.min_width { Some(min_width) => { - let diff: isize = - min_width.abs() as isize - pre_min_width.len() as isize; + let diff: isize = min_width.abs() as isize - pre_min_width.len() as isize; if diff > 0 { let mut final_str = String::new(); // definitely more efficient ways diff --git a/src/printf/tokenize/unescaped_text.rs b/src/printf/tokenize/unescaped_text.rs index c2b6eca9e..bb9566cef 100644 --- a/src/printf/tokenize/unescaped_text.rs +++ b/src/printf/tokenize/unescaped_text.rs @@ -63,7 +63,9 @@ impl UnescapedText { let leading_zeros = if eight_word { preface = 'U'; 8 - } else { 4 }; + } else { + 4 + }; let err_msg = format!( "invalid universal character name {0}{1:02$x}", preface, val, leading_zeros diff --git a/src/pwd/pwd.rs b/src/pwd/pwd.rs index c43fcf386..2eff91fa6 100644 --- a/src/pwd/pwd.rs +++ b/src/pwd/pwd.rs @@ -15,8 +15,8 @@ extern crate getopts; extern crate uucore; use std::env; -use std::path::{Path, PathBuf}; use std::io; +use std::path::{Path, PathBuf}; static NAME: &str = "pwd"; static VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -30,7 +30,8 @@ pub fn absolute_path(path: &Path) -> io::Result { .as_path() .to_string_lossy() .trim_start_matches(r"\\?\"), - ).to_path_buf(); + ) + .to_path_buf(); Ok(path_buf) } diff --git a/src/readlink/readlink.rs b/src/readlink/readlink.rs index 170fff6d3..47bea285c 100644 --- a/src/readlink/readlink.rs +++ b/src/readlink/readlink.rs @@ -76,7 +76,9 @@ pub fn uumain(args: Vec) -> i32 { CanonicalizeMode::Existing } else if matches.opt_present("canonicalize-missing") { CanonicalizeMode::Missing - } else { CanonicalizeMode::None }; + } else { + CanonicalizeMode::None + }; let files = matches.free; if files.is_empty() { diff --git a/src/rm/rm.rs b/src/rm/rm.rs index 34b9adb98..b3c241a8d 100644 --- a/src/rm/rm.rs +++ b/src/rm/rm.rs @@ -16,12 +16,12 @@ extern crate walkdir; #[macro_use] extern crate uucore; +use remove_dir_all::remove_dir_all; use std::collections::VecDeque; use std::fs; use std::io::{stderr, stdin, BufRead, Write}; use std::ops::BitOr; use std::path::Path; -use remove_dir_all::remove_dir_all; use walkdir::{DirEntry, WalkDir}; #[derive(Eq, PartialEq, Clone, Copy)] @@ -181,7 +181,8 @@ fn remove(files: Vec, options: Options) -> bool { false } } - }.bitor(had_err); + } + .bitor(had_err); } had_err @@ -247,9 +248,11 @@ fn remove_dir(path: &Path, options: &Options) -> bool { }; if response { match fs::remove_dir(path) { - Ok(_) => if options.verbose { - println!("removed '{}'", path.display()); - }, + Ok(_) => { + if options.verbose { + println!("removed '{}'", path.display()); + } + } Err(e) => { show_error!("removing '{}': {}", path.display(), e); return true; @@ -268,9 +271,11 @@ fn remove_file(path: &Path, options: &Options) -> bool { }; if response { match fs::remove_file(path) { - Ok(_) => if options.verbose { - println!("removed '{}'", path.display()); - }, + Ok(_) => { + if options.verbose { + println!("removed '{}'", path.display()); + } + } Err(e) => { show_error!("removing '{}': {}", path.display(), e); return true; @@ -320,5 +325,6 @@ fn is_symlink_dir(metadata: &fs::Metadata) -> bool { pub type DWORD = c_ulong; pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10; - metadata.file_type().is_symlink() && ((metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY) != 0) + metadata.file_type().is_symlink() + && ((metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY) != 0) } diff --git a/src/seq/seq.rs b/src/seq/seq.rs index 18295583d..a8a4f6ec4 100644 --- a/src/seq/seq.rs +++ b/src/seq/seq.rs @@ -96,10 +96,7 @@ fn parse_options(args: Vec, options: &mut SeqOptions) -> Result, options: &mut SeqOptions) -> Result, options: &mut SeqOptions) -> Result { let rvec = (b..e).map(|x| format!("{}", x)).collect::>(); - let mut rvec = rvec.iter().map(std::string::String::as_bytes).collect::>(); + let mut rvec = rvec + .iter() + .map(std::string::String::as_bytes) + .collect::>(); shuf_bytes(&mut rvec, repeat, count, sep, output, random); } Mode::Default => { diff --git a/src/sleep/sleep.rs b/src/sleep/sleep.rs index f27c42be5..ca05560b7 100644 --- a/src/sleep/sleep.rs +++ b/src/sleep/sleep.rs @@ -63,12 +63,14 @@ specified by the sum of their values.", } fn sleep(args: Vec) { - let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg| { - match uucore::parse_time::from_str(&arg[..]) { - Ok(m) => m + result, - Err(f) => crash!(1, "{}", f), - } - }); + let sleep_dur = + args.iter().fold( + Duration::new(0, 0), + |result, arg| match uucore::parse_time::from_str(&arg[..]) { + Ok(m) => m + result, + Err(f) => crash!(1, "{}", f), + }, + ); thread::sleep(sleep_dur); } diff --git a/src/sort/sort.rs b/src/sort/sort.rs index 2259bea0c..bddf26479 100644 --- a/src/sort/sort.rs +++ b/src/sort/sort.rs @@ -16,15 +16,15 @@ extern crate itertools; #[macro_use] extern crate uucore; +use itertools::Itertools; +use semver::Version; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::fs::File; use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Lines, Read, Write}; use std::mem::replace; use std::path::Path; -use uucore::fs::is_stdin_interactive; -use semver::Version; -use itertools::Itertools; // for Iterator::dedup() +use uucore::fs::is_stdin_interactive; // for Iterator::dedup() static NAME: &str = "sort"; static VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -380,13 +380,11 @@ fn permissive_f64_parse(a: &str) -> f64 { // GNU sort treats "NaN" as non-number in numeric, so it needs special care. match a.split_whitespace().next() { None => std::f64::NEG_INFINITY, - Some(sa) => { - match sa.parse::() { - Ok(a) if a.is_nan() => std::f64::NEG_INFINITY, - Ok(a) => a, - Err(_) => std::f64::NEG_INFINITY, - } - } + Some(sa) => match sa.parse::() { + Ok(a) if a.is_nan() => std::f64::NEG_INFINITY, + Ok(a) => a, + Err(_) => std::f64::NEG_INFINITY, + }, } } @@ -467,7 +465,8 @@ enum Month { /// Parse the beginning string into a Month, returning Month::Unknown on errors. fn month_parse(line: &str) -> Month { - match line.split_whitespace() + match line + .split_whitespace() .next() .unwrap() .to_uppercase() diff --git a/src/split/split.rs b/src/split/split.rs index d867c773b..e06bb33f8 100644 --- a/src/split/split.rs +++ b/src/split/split.rs @@ -319,7 +319,8 @@ fn split(settings: &Settings) -> i32 { num_prefix(fileno, settings.suffix_length) } else { str_prefix(fileno, settings.suffix_length) - }.as_ref(), + } + .as_ref(), ); if fileno != 0 { diff --git a/src/stat/fsext.rs b/src/stat/fsext.rs index 2f7d79e07..6cc333439 100644 --- a/src/stat/fsext.rs +++ b/src/stat/fsext.rs @@ -10,9 +10,11 @@ pub use super::uucore::libc; extern crate time; use self::time::Timespec; -pub use libc::{c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, - S_IFREG, S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, - S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR}; +pub use libc::{ + c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG, + S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, S_IWOTH, S_IWUSR, + S_IXGRP, S_IXOTH, S_IXUSR, +}; pub trait BirthTime { fn pretty_birth(&self) -> String; @@ -40,9 +42,9 @@ impl BirthTime for Metadata { #[macro_export] macro_rules! has { - ($mode:expr, $perm:expr) => ( + ($mode:expr, $perm:expr) => { $mode & $perm != 0 - ) + }; } pub fn pretty_time(sec: i64, nsec: i64) -> String { @@ -137,22 +139,44 @@ pub fn pretty_access(mode: mode_t) -> String { result } -use std::mem; -use std::path::Path; use std::borrow::Cow; -use std::ffi::CString; use std::convert::{AsRef, From}; use std::error::Error; +use std::ffi::CString; use std::io::Error as IOError; +use std::mem; +use std::path::Path; -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android", target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "android", + target_os = "freebsd" +))] use libc::statfs as Sstatfs; -#[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "openbsd", target_os = "bitrig", target_os = "dragonfly"))] +#[cfg(any( + target_os = "openbsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "bitrig", + target_os = "dragonfly" +))] use libc::statvfs as Sstatfs; -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android", target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "android", + target_os = "freebsd" +))] use libc::statfs as statfs_fn; -#[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "openbsd", target_os = "bitrig", target_os = "dragonfly"))] +#[cfg(any( + target_os = "openbsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "bitrig", + target_os = "dragonfly" +))] use libc::statvfs as statfs_fn; pub trait FsMeta { @@ -219,7 +243,8 @@ impl FsMeta for Sstatfs { // struct statvfs, containing an unsigned long f_fsid #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "linux"))] fn fsid(&self) -> u64 { - let f_fsid: &[u32; 2] = unsafe { &*(&self.f_fsid as *const uucore::libc::fsid_t as *const [u32; 2]) }; + let f_fsid: &[u32; 2] = + unsafe { &*(&self.f_fsid as *const uucore::libc::fsid_t as *const [u32; 2]) }; (u64::from(f_fsid[0])) << 32 | u64::from(f_fsid[1]) } #[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "linux")))] @@ -261,10 +286,10 @@ where Err(CString::from_raw(strerror(errno)) .into_string() .unwrap_or_else(|_| "Unknown Error".to_owned())) - } } } } + } Err(e) => Err(e.description().to_owned()), } } diff --git a/src/stat/stat.rs b/src/stat/stat.rs index cf8ea1517..d8be79f8b 100644 --- a/src/stat/stat.rs +++ b/src/stat/stat.rs @@ -19,29 +19,31 @@ pub use fsext::*; extern crate uucore; use uucore::entries; -use std::{cmp, fs, iter}; +use std::borrow::Cow; +use std::convert::AsRef; use std::fs::File; use std::io::{BufRead, BufReader}; -use std::borrow::Cow; use std::os::unix::fs::{FileTypeExt, MetadataExt}; use std::path::Path; -use std::convert::AsRef; +use std::{cmp, fs, iter}; macro_rules! check_bound { - ($str: ident, $bound:expr, $beg: expr, $end: expr) => ( + ($str: ident, $bound:expr, $beg: expr, $end: expr) => { if $end >= $bound { return Err(format!("‘{}’: invalid directive", &$str[$beg..$end])); } - - ) + }; } macro_rules! fill_string { - ($str: ident, $c: expr, $cnt: expr) => ( - iter::repeat($c).take($cnt).map(|c| $str.push(c)).all(|_| true) - ) + ($str: ident, $c: expr, $cnt: expr) => { + iter::repeat($c) + .take($cnt) + .map(|c| $str.push(c)) + .all(|_| true) + }; } macro_rules! extend_digits { - ($str: expr, $min: expr) => ( + ($str: expr, $min: expr) => { if $min > $str.len() { let mut pad = String::with_capacity($min); fill_string!(pad, '0', $min - $str.len()); @@ -50,10 +52,10 @@ macro_rules! extend_digits { } else { $str.into() } - ) + }; } macro_rules! pad_and_print { - ($result: ident, $str: ident, $left: expr, $width: expr, $padding: expr) => ( + ($result: ident, $str: ident, $left: expr, $width: expr, $padding: expr) => { if $str.len() < $width { if $left { $result.push_str($str.as_ref()); @@ -66,7 +68,7 @@ macro_rules! pad_and_print { $result.push_str($str.as_ref()); } print!("{}", $result); - ) + }; } macro_rules! print_adjusted { ($str: ident, $left: expr, $width: expr, $padding: expr) => { @@ -82,7 +84,7 @@ macro_rules! print_adjusted { field_width -= $prefix.len(); } pad_and_print!(result, $str, $left, field_width, $padding); - } + }; } static NAME: &str = "stat"; @@ -481,7 +483,11 @@ impl Stater { let mut mount_list = reader .lines() .filter_map(std::result::Result::ok) - .filter_map(|line| line.split_whitespace().nth(1).map(std::borrow::ToOwned::to_owned)) + .filter_map(|line| { + line.split_whitespace() + .nth(1) + .map(std::borrow::ToOwned::to_owned) + }) .collect::>(); // Reverse sort. The longer comes first. mount_list.sort_by(|a, b| b.cmp(a)); diff --git a/src/stdbuf/libstdbuf/libstdbuf.rs b/src/stdbuf/libstdbuf/libstdbuf.rs index 1e290d005..5b2f41244 100644 --- a/src/stdbuf/libstdbuf/libstdbuf.rs +++ b/src/stdbuf/libstdbuf/libstdbuf.rs @@ -9,7 +9,7 @@ use libc::{c_char, c_int, size_t, FILE, _IOFBF, _IOLBF, _IONBF}; use std::env; use std::ptr; -cpp!{{ +cpp! {{ #include extern "C" { diff --git a/src/stdbuf/stdbuf.rs b/src/stdbuf/stdbuf.rs index 9c27a1a13..c78105602 100644 --- a/src/stdbuf/stdbuf.rs +++ b/src/stdbuf/stdbuf.rs @@ -16,12 +16,12 @@ extern crate tempdir; extern crate uucore; use getopts::{Matches, Options}; -use tempdir::TempDir; use std::fs::File; use std::io::{self, Write}; use std::os::unix::process::ExitStatusExt; use std::path::PathBuf; use std::process::Command; +use tempdir::TempDir; static NAME: &str = "stdbuf"; static VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -51,7 +51,12 @@ enum OkMsg { Version, } -#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "dragonflybsd"))] +#[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "netbsd", + target_os = "dragonflybsd" +))] fn preload_strings() -> (&'static str, &'static str) { ("LD_PRELOAD", "so") } @@ -61,7 +66,13 @@ fn preload_strings() -> (&'static str, &'static str) { ("DYLD_LIBRARY_PATH", "dylib") } -#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "dragonflybsd", target_os = "macos")))] +#[cfg(not(any( + target_os = "linux", + target_os = "freebsd", + target_os = "netbsd", + target_os = "dragonflybsd", + target_os = "macos" +)))] fn preload_strings() -> (&'static str, &'static str) { crash!(1, "Command not supported for this operating system!") } diff --git a/src/sync/sync.rs b/src/sync/sync.rs index a6d7faaba..2b976d5db 100644 --- a/src/sync/sync.rs +++ b/src/sync/sync.rs @@ -42,27 +42,29 @@ mod platform { mod platform { extern crate kernel32; extern crate winapi; - use std::mem; - use std::fs::OpenOptions; - use std::os::windows::prelude::*; - use uucore::wide::{FromWide, ToWide}; + use self::winapi::shared::minwindef; + use self::winapi::shared::winerror; + use self::winapi::um::handleapi; use self::winapi::um::winbase; use self::winapi::um::winnt; - use self::winapi::shared::minwindef; - use self::winapi::um::handleapi; - use self::winapi::shared::winerror; + use std::fs::OpenOptions; + use std::mem; + use std::os::windows::prelude::*; + use uucore::wide::{FromWide, ToWide}; unsafe fn flush_volume(name: &str) { let name_wide = name.to_wide_null(); if kernel32::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED { let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash match OpenOptions::new().write(true).open(sliced_name) { - Ok(file) => if kernel32::FlushFileBuffers(file.as_raw_handle()) == 0 { - crash!( - kernel32::GetLastError() as i32, - "failed to flush file buffer" - ); - }, + Ok(file) => { + if kernel32::FlushFileBuffers(file.as_raw_handle()) == 0 { + crash!( + kernel32::GetLastError() as i32, + "failed to flush file buffer" + ); + } + } Err(e) => crash!( e.raw_os_error().unwrap_or(1), "failed to create volume handle" diff --git a/src/tail/platform/redox.rs b/src/tail/platform/redox.rs index c0d43cb1c..a3a8c5fa0 100644 --- a/src/tail/platform/redox.rs +++ b/src/tail/platform/redox.rs @@ -1,6 +1,6 @@ extern crate syscall; -use self::syscall::{Error, EPERM, ENOSYS}; +use self::syscall::{Error, ENOSYS, EPERM}; pub type Pid = usize; diff --git a/src/tail/platform/windows.rs b/src/tail/platform/windows.rs index ebab7d32b..fbf9351d4 100644 --- a/src/tail/platform/windows.rs +++ b/src/tail/platform/windows.rs @@ -12,7 +12,7 @@ extern crate winapi; use self::kernel32::{CloseHandle, OpenProcess, WaitForSingleObject}; use self::winapi::shared::minwindef::DWORD; -use self::winapi::um::winbase::{WAIT_OBJECT_0, WAIT_FAILED}; +use self::winapi::um::winbase::{WAIT_FAILED, WAIT_OBJECT_0}; use self::winapi::um::winnt::{HANDLE, SYNCHRONIZE}; pub type Pid = DWORD; diff --git a/src/tail/tail.rs b/src/tail/tail.rs index 8aa7abb3e..825a14b95 100755 --- a/src/tail/tail.rs +++ b/src/tail/tail.rs @@ -154,20 +154,22 @@ pub fn uumain(args: Vec) -> i32 { } } } - None => if let Some(n) = given_options.opt_str("c") { - let mut slice: &str = n.as_ref(); - if slice.chars().next().unwrap_or('_') == '+' { - settings.beginning = true; - slice = &slice[1..]; - } - match parse_size(slice) { - Ok(m) => settings.mode = FilterMode::Bytes(m), - Err(e) => { - show_error!("{}", e.description()); - return 1; + None => { + if let Some(n) = given_options.opt_str("c") { + let mut slice: &str = n.as_ref(); + if slice.chars().next().unwrap_or('_') == '+' { + settings.beginning = true; + slice = &slice[1..]; + } + match parse_size(slice) { + Ok(m) => settings.mode = FilterMode::Bytes(m), + Err(e) => { + show_error!("{}", e.description()); + return 1; + } } } - }, + } }; if given_options.opt_present("z") { diff --git a/src/tee/tee.rs b/src/tee/tee.rs index abc77e347..c2cfc1ac0 100644 --- a/src/tee/tee.rs +++ b/src/tee/tee.rs @@ -80,7 +80,10 @@ fn options(args: &[String]) -> Result { fn exec(options: Options) -> Result<()> { match options.print_and_exit { - Some(text) => { println!("{}", text); Ok(()) }, + Some(text) => { + println!("{}", text); + Ok(()) + } None => tee(options), } } @@ -118,10 +121,7 @@ fn open(name: String, append: bool) -> Box { Err(_) => Box::new(sink()), } }; - Box::new(NamedWriter { - inner, - path, - }) as Box + Box::new(NamedWriter { inner, path }) as Box } struct MultiWriter { diff --git a/src/test/test.rs b/src/test/test.rs index a89ce7300..0631d292e 100644 --- a/src/test/test.rs +++ b/src/test/test.rs @@ -14,8 +14,8 @@ extern crate libc; extern crate syscall; use std::collections::HashMap; -use std::ffi::OsString; use std::env::args_os; +use std::ffi::OsString; use std::str::from_utf8; static NAME: &str = "test"; @@ -25,7 +25,8 @@ static NAME: &str = "test"; pub fn uumain(_: Vec) -> i32 { let args = args_os().collect::>(); // This is completely disregarding valid windows paths that aren't valid unicode - let args = args.iter() + let args = args + .iter() .map(|a| a.to_str().unwrap().as_bytes()) .collect::>(); if args.is_empty() { @@ -149,7 +150,9 @@ fn isatty(fd: &[u8]) -> bool { .and_then(|s| s.parse().ok()) .map_or(false, |i| { #[cfg(not(target_os = "redox"))] - unsafe { libc::isatty(i) == 1 } + unsafe { + libc::isatty(i) == 1 + } #[cfg(target_os = "redox")] syscall::dup(i, b"termios").map(syscall::close).is_ok() }) @@ -342,10 +345,10 @@ enum PathCondition { #[cfg(not(windows))] fn path(path: &[u8], cond: PathCondition) -> bool { - use std::os::unix::fs::{MetadataExt, FileTypeExt}; - use std::os::unix::ffi::OsStrExt; - use std::fs::{self, Metadata}; use std::ffi::OsStr; + use std::fs::{self, Metadata}; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::{FileTypeExt, MetadataExt}; let path = OsStr::from_bytes(path); @@ -362,8 +365,10 @@ fn path(path: &[u8], cond: PathCondition) -> bool { #[cfg(not(target_os = "redox"))] let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) }; #[cfg(target_os = "redox")] - let (uid, gid) = (syscall::getuid().unwrap() as u32, - syscall::getgid().unwrap() as u32); + let (uid, gid) = ( + syscall::getuid().unwrap() as u32, + syscall::getgid().unwrap() as u32, + ); if uid == metadata.uid() { metadata.mode() & ((p as u32) << 6) != 0 @@ -382,7 +387,9 @@ fn path(path: &[u8], cond: PathCondition) -> bool { let metadata = match metadata { Ok(metadata) => metadata, - Err(_) => { return false; } + Err(_) => { + return false; + } }; let file_type = metadata.file_type(); diff --git a/src/touch/touch.rs b/src/touch/touch.rs index 503ee062e..a129f6db8 100644 --- a/src/touch/touch.rs +++ b/src/touch/touch.rs @@ -164,14 +164,16 @@ pub fn uumain(args: Vec) -> i32 { let st = stat(path, !matches.opt_present("no-dereference")); let time = matches.opt_strs("time"); - if !(matches.opt_present("a") || time.contains(&"access".to_owned()) + if !(matches.opt_present("a") + || time.contains(&"access".to_owned()) || time.contains(&"atime".to_owned()) || time.contains(&"use".to_owned())) { atime = st.0; } - if !(matches.opt_present("m") || time.contains(&"modify".to_owned()) + if !(matches.opt_present("m") + || time.contains(&"modify".to_owned()) || time.contains(&"mtime".to_owned())) { mtime = st.1; @@ -183,7 +185,7 @@ pub fn uumain(args: Vec) -> i32 { show_warning!("cannot touch '{}': {}", path, e); } } else if let Err(e) = filetime::set_file_times(path, atime, mtime) { - show_warning!("cannot touch '{}': {}", path, e); + show_warning!("cannot touch '{}': {}", path, e); } } diff --git a/src/tr/expand.rs b/src/tr/expand.rs index 510e33925..5aeb3b04c 100644 --- a/src/tr/expand.rs +++ b/src/tr/expand.rs @@ -88,16 +88,18 @@ impl<'a> Iterator for ExpandSet<'a> { if let Some(first) = self.unesc.next() { // peek ahead - if self.unesc.peek() == Some(&'-') && match self.unesc.size_hint() { - (x, _) if x > 1 => true, // there's a range here; record it in our internal Range struct - _ => false, - } { + if self.unesc.peek() == Some(&'-') + && match self.unesc.size_hint() { + (x, _) if x > 1 => true, // there's a range here; record it in our internal Range struct + _ => false, + } + { self.unesc.next(); // this is the '-' let last = self.unesc.next().unwrap(); // this is the end of the range #[allow(clippy::range_plus_one)] { - self.range = first as u32 + 1..last as u32 + 1; + self.range = first as u32 + 1..last as u32 + 1; } } diff --git a/src/truncate/truncate.rs b/src/truncate/truncate.rs index f6ee266e0..0358b4382 100644 --- a/src/truncate/truncate.rs +++ b/src/truncate/truncate.rs @@ -148,16 +148,20 @@ fn truncate( TruncateMode::Reference => refsize, TruncateMode::Extend => fsize + refsize, TruncateMode::Reduce => fsize - refsize, - TruncateMode::AtMost => if fsize > refsize { - refsize - } else { - fsize - }, - TruncateMode::AtLeast => if fsize < refsize { - refsize - } else { - fsize - }, + TruncateMode::AtMost => { + if fsize > refsize { + refsize + } else { + fsize + } + } + TruncateMode::AtLeast => { + if fsize < refsize { + refsize + } else { + fsize + } + } TruncateMode::RoundDown => fsize - fsize % refsize, TruncateMode::RoundUp => fsize + fsize % refsize, }; @@ -195,14 +199,16 @@ fn parse_size(size: &str) -> (u64, TruncateMode) { } } slice - }.to_owned(); + } + .to_owned(); let mut number: u64 = match bytes.parse() { Ok(num) => num, Err(e) => crash!(1, "'{}' is not a valid number: {}", size, e), }; if size.chars().last().unwrap().is_alphabetic() { number *= match size.chars().last().unwrap().to_ascii_uppercase() { - 'B' => match size.chars() + 'B' => match size + .chars() .nth(size.len() - 2) .unwrap() .to_ascii_uppercase() diff --git a/src/tsort/tsort.rs b/src/tsort/tsort.rs index b24ce5007..9a01b0cc3 100644 --- a/src/tsort/tsort.rs +++ b/src/tsort/tsort.rs @@ -79,7 +79,8 @@ pub fn uumain(args: Vec) -> i32 { let mut line = String::new(); match reader.read_line(&mut line) { Ok(_) => { - let tokens: Vec = line.trim_end() + let tokens: Vec = line + .trim_end() .split_whitespace() .map(|s| s.to_owned()) .collect(); diff --git a/src/unexpand/unexpand.rs b/src/unexpand/unexpand.rs index 2006424a5..15d380633 100644 --- a/src/unexpand/unexpand.rs +++ b/src/unexpand/unexpand.rs @@ -42,7 +42,8 @@ fn tabstops_parse(s: String) -> Vec { crash!(1, "{}\n", "tab size cannot be 0"); } - if let (false, _) = nums.iter() + if let (false, _) = nums + .iter() .fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { crash!(1, "{}\n", "tab sizes must be ascending"); diff --git a/src/unlink/unlink.rs b/src/unlink/unlink.rs index 8c472824b..3c8bc71da 100644 --- a/src/unlink/unlink.rs +++ b/src/unlink/unlink.rs @@ -18,10 +18,10 @@ extern crate libc; extern crate uucore; use getopts::Options; -use libc::{S_IFLNK, S_IFMT, S_IFREG}; use libc::{lstat, stat, unlink}; -use std::io::{Error, ErrorKind}; +use libc::{S_IFLNK, S_IFMT, S_IFREG}; use std::ffi::CString; +use std::io::{Error, ErrorKind}; static NAME: &str = "unlink"; static VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -72,12 +72,7 @@ pub fn uumain(args: Vec) -> i32 { let st_mode = { #[allow(deprecated)] let mut buf: stat = unsafe { std::mem::uninitialized() }; - let result = unsafe { - lstat( - c_string.as_ptr(), - &mut buf as *mut stat, - ) - }; + let result = unsafe { lstat(c_string.as_ptr(), &mut buf as *mut stat) }; if result < 0 { crash!( diff --git a/src/uptime/uptime.rs b/src/uptime/uptime.rs index 73fca4716..458ddbe81 100644 --- a/src/uptime/uptime.rs +++ b/src/uptime/uptime.rs @@ -18,8 +18,8 @@ extern crate time; #[macro_use] extern crate uucore; // import crate time from utmpx -use uucore::libc::time_t; pub use uucore::libc; +use uucore::libc::time_t; use getopts::Options; @@ -190,7 +190,9 @@ fn print_uptime(upsecs: i64) { let upmins = (upsecs - (updays * 86400) - (uphours * 3600)) / 60; match updays.cmp(&1) { std::cmp::Ordering::Equal => print!("up {:1} day, {:2}:{:02}, ", updays, uphours, upmins), - std::cmp::Ordering::Greater => print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins), + std::cmp::Ordering::Greater => { + print!("up {:1} days, {:2}:{:02}, ", updays, uphours, upmins) + } _ => print!("up {:2}:{:02}, ", uphours, upmins), }; } diff --git a/src/users/users.rs b/src/users/users.rs index 11330346e..57e515fc3 100644 --- a/src/users/users.rs +++ b/src/users/users.rs @@ -10,7 +10,6 @@ */ /* last synced with: whoami (GNU coreutils) 8.22 */ - // Allow dead code here in order to keep all fields, constants here, for consistency. #![allow(dead_code)] diff --git a/src/uutils/uutils.rs b/src/uutils/uutils.rs index e7bd54345..c90c73d02 100644 --- a/src/uutils/uutils.rs +++ b/src/uutils/uutils.rs @@ -12,8 +12,8 @@ include!(concat!(env!("OUT_DIR"), "/uutils_crates.rs")); use std::collections::hash_map::HashMap; -use std::path::Path; use std::io::Write; +use std::path::Path; extern crate uucore; @@ -51,8 +51,10 @@ fn main() { std::process::exit(uumain(args)); } - if binary_as_util.ends_with("uutils") || binary_as_util.starts_with("uutils") - || binary_as_util.ends_with("busybox") || binary_as_util.starts_with("busybox") + if binary_as_util.ends_with("uutils") + || binary_as_util.starts_with("uutils") + || binary_as_util.ends_with("busybox") + || binary_as_util.starts_with("busybox") { args.remove(0); } else { diff --git a/src/wc/wc.rs b/src/wc/wc.rs index 782859412..8c70ff9f4 100644 --- a/src/wc/wc.rs +++ b/src/wc/wc.rs @@ -40,7 +40,10 @@ impl Settings { show_max_line_length: matches.opt_present("L"), }; - if settings.show_bytes || settings.show_chars || settings.show_lines || settings.show_words + if settings.show_bytes + || settings.show_chars + || settings.show_lines + || settings.show_words || settings.show_max_line_length { return settings; diff --git a/src/who/who.rs b/src/who/who.rs index f3b8a3b80..a1a5d8002 100644 --- a/src/who/who.rs +++ b/src/who/who.rs @@ -11,13 +11,13 @@ #[macro_use] extern crate uucore; -use uucore::utmpx::{self, time, Utmpx}; use uucore::libc::{ttyname, STDIN_FILENO, S_IWGRP}; +use uucore::utmpx::{self, time, Utmpx}; use std::borrow::Cow; use std::ffi::CStr; -use std::path::PathBuf; use std::os::unix::fs::MetadataExt; +use std::path::PathBuf; static SYNTAX: &str = "[OPTION]... [ FILE | ARG1 ARG2 ]"; static SUMMARY: &str = "Print information about users who are currently logged in."; @@ -60,7 +60,12 @@ pub fn uumain(args: Vec) -> i32 { "count", "all login names and number of users logged on", ); - #[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux", target_os = "android"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "linux", + target_os = "android" + ))] opts.optflag("r", "runlevel", "print current runlevel"); opts.optflag("s", "short", "print only name, line, and time (default)"); opts.optflag("t", "time", "print last system clock change"); @@ -130,80 +135,80 @@ pub fn uumain(args: Vec) -> i32 { #[allow(clippy::useless_let_if_seq)] { - if matches.opt_present("a") { - need_boottime = true; - need_deadprocs = true; - need_login = true; - need_initspawn = true; - need_runlevel = true; - need_clockchange = true; - need_users = true; - include_idle = true; - include_exit = true; - assumptions = false; - } + if matches.opt_present("a") { + need_boottime = true; + need_deadprocs = true; + need_login = true; + need_initspawn = true; + need_runlevel = true; + need_clockchange = true; + need_users = true; + include_idle = true; + include_exit = true; + assumptions = false; + } - if matches.opt_present("b") { - need_boottime = true; - assumptions = false; - } + if matches.opt_present("b") { + need_boottime = true; + assumptions = false; + } - if matches.opt_present("d") { - need_deadprocs = true; - include_idle = true; - include_exit = true; - assumptions = false; - } + if matches.opt_present("d") { + need_deadprocs = true; + include_idle = true; + include_exit = true; + assumptions = false; + } - if matches.opt_present("l") { - need_login = true; - include_idle = true; - assumptions = false; - } + if matches.opt_present("l") { + need_login = true; + include_idle = true; + assumptions = false; + } - if matches.opt_present("m") || matches.free.len() == 2 { - my_line_only = true; - } + if matches.opt_present("m") || matches.free.len() == 2 { + my_line_only = true; + } - if matches.opt_present("p") { - need_initspawn = true; - assumptions = false; - } + if matches.opt_present("p") { + need_initspawn = true; + assumptions = false; + } - if matches.opt_present("r") { - need_runlevel = true; - include_idle = true; - assumptions = false; - } + if matches.opt_present("r") { + need_runlevel = true; + include_idle = true; + assumptions = false; + } - if matches.opt_present("s") { - short_output = true; - } + if matches.opt_present("s") { + short_output = true; + } - if matches.opt_present("t") { - need_clockchange = true; - assumptions = false; - } + if matches.opt_present("t") { + need_clockchange = true; + assumptions = false; + } - if matches.opt_present("u") { - need_users = true; - include_idle = true; - assumptions = false; - } + if matches.opt_present("u") { + need_users = true; + include_idle = true; + assumptions = false; + } - if assumptions { - need_users = true; - short_output = true; - } + if assumptions { + need_users = true; + short_output = true; + } - if include_exit { - short_output = false; - } + if include_exit { + short_output = false; + } - if matches.free.len() > 2 { - disp_err!("{}", msg_wrong_number_of_arguments!()); - exit!(1); - } + if matches.free.len() > 2 { + disp_err!("{}", msg_wrong_number_of_arguments!()); + exit!(1); + } } let mut who = Who { @@ -266,7 +271,8 @@ fn idle_string<'a>(when: i64, boottime: i64) -> Cow<'a, str> { "{:02}:{:02}", seconds_idle / 3600, (seconds_idle % 3600) / 60 - ).into() + ) + .into() } } else { " old ".into() @@ -299,7 +305,12 @@ impl Who { #[allow(unused_assignments)] let mut res = false; - #[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux", target_os = "android"))] + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "linux", + target_os = "android" + ))] { res = record == utmpx::RUN_LVL; } @@ -529,14 +540,7 @@ impl Who { #[inline] fn print_heading(&self) { self.print_line( - "NAME", - ' ', - "LINE", - "TIME", - "IDLE", - "PID", - "COMMENT", - "EXIT", + "NAME", ' ', "LINE", "TIME", "IDLE", "PID", "COMMENT", "EXIT", ); } } diff --git a/src/whoami/platform/unix.rs b/src/whoami/platform/unix.rs index ab7c42ff6..259f806ef 100644 --- a/src/whoami/platform/unix.rs +++ b/src/whoami/platform/unix.rs @@ -9,8 +9,8 @@ */ use std::io::Result; -use uucore::libc::geteuid; use uucore::entries::uid2usr; +use uucore::libc::geteuid; pub unsafe fn getusername() -> Result { // Get effective user id diff --git a/src/whoami/platform/windows.rs b/src/whoami/platform/windows.rs index d08937a65..6ae9027f0 100644 --- a/src/whoami/platform/windows.rs +++ b/src/whoami/platform/windows.rs @@ -11,12 +11,12 @@ extern crate advapi32; extern crate uucore; extern crate winapi; +use self::winapi::shared::lmcons; +use self::winapi::shared::minwindef; +use self::winapi::um::winnt; use std::io::{Error, Result}; use std::mem; use uucore::wide::FromWide; -use self::winapi::um::winnt; -use self::winapi::shared::lmcons; -use self::winapi::shared::minwindef; pub unsafe fn getusername() -> Result { #[allow(deprecated)] diff --git a/src/yes/yes.rs b/src/yes/yes.rs index b8e7971fd..6a46d61ba 100644 --- a/src/yes/yes.rs +++ b/src/yes/yes.rs @@ -17,9 +17,9 @@ extern crate clap; extern crate uucore; use clap::Arg; -use uucore::zero_copy::ZeroCopyWriter; use std::borrow::Cow; use std::io::{self, Write}; +use uucore::zero_copy::ZeroCopyWriter; // force a re-build whenever Cargo.toml changes const _CARGO_TOML: &str = include_str!("Cargo.toml"); diff --git a/tests/common/macros.rs b/tests/common/macros.rs index e36fdffdc..645cfcc67 100644 --- a/tests/common/macros.rs +++ b/tests/common/macros.rs @@ -49,18 +49,22 @@ macro_rules! path_concat { #[macro_export] macro_rules! util_name { - () => ( module_path!().split("_").nth(1).expect("no test name") ) + () => { + module_path!().split("_").nth(1).expect("no test name") + }; } #[macro_export] macro_rules! new_ucmd { - () => ( TestScenario::new(util_name!()).ucmd() ) + () => { + TestScenario::new(util_name!()).ucmd() + }; } #[macro_export] macro_rules! at_and_ucmd { - () => ({ - let ts = TestScenario::new(util_name!()); - (ts.fixtures.clone(), ts.ucmd()) - }) + () => {{ + let ts = TestScenario::new(util_name!()); + (ts.fixtures.clone(), ts.ucmd()) + }}; } diff --git a/tests/common/util.rs b/tests/common/util.rs index abae40826..ce0779077 100644 --- a/tests/common/util.rs +++ b/tests/common/util.rs @@ -1,7 +1,9 @@ #![allow(dead_code)] extern crate tempdir; +use self::tempdir::TempDir; use std::env; +use std::ffi::OsStr; use std::fs::{self, File, OpenOptions}; use std::io::{Read, Result, Write}; #[cfg(unix)] @@ -10,12 +12,10 @@ use std::os::unix::fs::{symlink as symlink_dir, symlink as symlink_file}; use std::os::windows::fs::{symlink_dir, symlink_file}; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; -use std::str::from_utf8; -use std::ffi::OsStr; use std::rc::Rc; +use std::str::from_utf8; use std::thread::sleep; use std::time::Duration; -use self::tempdir::TempDir; #[cfg(windows)] static PROGNAME: &'static str = "uutils.exe"; @@ -37,13 +37,13 @@ static MULTIPLE_STDIN_MEANINGLESS: &'static str = "Ucommand is designed around a pub fn is_wsl() -> bool { #[cfg(target_os = "linux")] { - if let Ok(b) = std::fs::read("/proc/sys/kernel/osrelease") { - if let Ok(s) = std::str::from_utf8(&b) { - let a = s.to_ascii_lowercase(); - return a.contains("microsoft") || a.contains("wsl"); + if let Ok(b) = std::fs::read("/proc/sys/kernel/osrelease") { + if let Ok(s) = std::str::from_utf8(&b) { + let a = s.to_ascii_lowercase(); + return a.contains("microsoft") || a.contains("wsl"); + } } } - } false } @@ -108,10 +108,7 @@ impl CmdResult { /// passed in value, trailing whitespace are kept to force strict comparison (#1235) /// stdout_only is a better choice unless stderr may or will be non-empty pub fn stdout_is>(&self, msg: T) -> Box<&CmdResult> { - assert_eq!( - self.stdout, - String::from(msg.as_ref()) - ); + assert_eq!(self.stdout, String::from(msg.as_ref())); Box::new(self) } @@ -373,7 +370,8 @@ impl AtPath { pub fn root_dir_resolved(&self) -> String { log_info("current_directory_resolved", ""); - let s = self.subdir + let s = self + .subdir .canonicalize() .unwrap() .to_str() @@ -573,7 +571,8 @@ impl UCommand { } self.has_run = true; log_info("run", &self.comm_string); - let mut result = self.raw + let mut result = self + .raw .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped())