diff --git a/.travis.yml b/.travis.yml index 32929a629b4..8302f285ca8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -52,8 +52,15 @@ install: pip3 install $SPHINX_VERSIONED fi +before_script: + - rustup component add rustfmt + script: + # Check style + - cargo fmt --all -- --check + # Build - cargo build $CARGO_ARGS --features "$FEATURES" + # Run tests - if [ ! $REDOX ]; then cargo test $CARGO_ARGS --features "$FEATURES" --no-fail-fast; fi - if [ -n "$TEST_INSTALL" ]; then mkdir installdir_test; DESTDIR=installdir_test make install; [ `ls installdir_test/usr/local/bin | wc -l` -gt 0 ]; fi diff --git a/build.rs b/build.rs index b5b70c01984..ce9e2aa024c 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" - | "nightly" | "test_unimplemented" => continue, + "default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic" + | "windows" | "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 f065ea8b2dc..c4d50d52682 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 5487842982d..feb7bc38429 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 9072fecb03d..effd4598b43 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 040b91608e7..1bb09ace16e 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/basename/basename.rs b/src/basename/basename.rs index 9711efea35c..57817d72bea 100644 --- a/src/basename/basename.rs +++ b/src/basename/basename.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_basename"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jimmy Lu - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jimmy Lu +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; @@ -21,9 +19,7 @@ static SUMMARY: &str = "Print NAME with any leading directory components removed static LONG_HELP: &str = ""; pub fn uumain(args: Vec) -> i32 { - // // Argument parsing - // let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag( "a", @@ -74,9 +70,7 @@ pub fn uumain(args: Vec) -> i32 { "".to_owned() }; - // // Main Program Processing - // let paths = if multiple_paths { &matches.free[..] diff --git a/src/cat/cat.rs b/src/cat/cat.rs index 37762fb8e84..26304236052 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::NumberNone); 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; @@ -404,7 +401,8 @@ fn write_file_lines(file: &str, options: &OutputOptions, state: &mut OutputState // write***_to_end methods // Write all symbols till end of line or end of buffer is reached -// Return the (number of written symbols + 1) or 0 if the end of buffer is reached +// Return the (number of written symbols + 1) or 0 if the end of buffer is +// reached fn write_to_end(in_buf: &[u8], writer: &mut W) -> usize { match in_buf.iter().position(|c| *c == b'\n') { Some(p) => { @@ -421,10 +419,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 +453,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 ed50432d3eb..fac36f67219 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 b428285bd75..840c0b3eaf4 100644 --- a/src/chmod/chmod.rs +++ b/src/chmod/chmod.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_chmod"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[cfg(unix)] extern crate libc; @@ -19,10 +17,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 +37,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 +163,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 +247,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 ef6086c2ce4..6107dd9f666 100644 --- a/src/chown/chown.rs +++ b/src/chown/chown.rs @@ -5,15 +5,14 @@ // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -// #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #[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 +23,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 +252,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 a7973e8fe2a..032e03b0b57 100644 --- a/src/chroot/chroot.rs +++ b/src/chroot/chroot.rs @@ -1,21 +1,19 @@ #![crate_name = "uu_chroot"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Vsevolod Velichko - * (c) Jian Zeng - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Vsevolod Velichko +// (c) Jian Zeng +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. 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 +138,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 37c48db5c6f..c71d03d067d 100644 --- a/src/cksum/build.rs +++ b/src/cksum/build.rs @@ -1,12 +1,10 @@ -/* -* This file is part of the uutils coreutils package. -* -* (c) Alex Lyon -* (c) Michael Gehring -* -* For the full copyright and license information, please view the LICENSE -* file that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. use std::env; use std::fs::File; @@ -32,7 +30,8 @@ fn main() { &file, "const CRC_TABLE: [u32; {}] = {:?};", CRC_TABLE_LEN, table - ).unwrap(); + ) + .unwrap(); } #[inline] diff --git a/src/cksum/cksum.rs b/src/cksum/cksum.rs index 08b56b7d3eb..d3e45eb7734 100644 --- a/src/cksum/cksum.rs +++ b/src/cksum/cksum.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_cksum"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; @@ -78,7 +76,7 @@ fn cksum(fname: &str) -> io::Result<(u32, usize)> { Err(err) => return Err(err), } } - //Ok((0 as u32,0 as usize)) + // Ok((0 as u32,0 as usize)) } pub fn uumain(args: Vec) -> i32 { diff --git a/src/comm/comm.rs b/src/comm/comm.rs index f9381826bca..ee7aa44ebd9 100644 --- a/src/comm/comm.rs +++ b/src/comm/comm.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_comm"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/cp/cp.rs b/src/cp/cp.rs index eb220511308..338e54ebcd1 100644 --- a/src/cp/cp.rs +++ b/src/cp/cp.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_cp"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordy Dickinson - * (c) Joshua S. Miller - * - * For the full copyright and license information, please view the LICENSE file - * that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordy Dickinson +// (c) Joshua S. Miller +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate clap; extern crate filetime; @@ -27,30 +25,30 @@ extern crate xattr; #[cfg(windows)] extern crate kernel32; #[cfg(windows)] -use kernel32::GetFileInformationByHandle; -#[cfg(windows)] use kernel32::CreateFile2; #[cfg(windows)] +use kernel32::GetFileInformationByHandle; +#[cfg(windows)] extern crate winapi; -use std::mem; -use std::ffi::CString; use clap::{App, Arg, ArgMatches}; +use filetime::FileTime; use quick_error::ResultExt; use std::collections::HashSet; +use std::ffi::CString; 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; 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; @@ -576,7 +574,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); @@ -723,7 +722,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; @@ -743,7 +743,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; @@ -824,7 +825,8 @@ fn construct_dest_path( return Err(format!( "cannot overwrite directory '{}' with non-directory", target.display() - ).into()); + ) + .into()); } Ok(match *target_type { @@ -1101,8 +1103,9 @@ fn copy_file(source: &Path, dest: &Path, options: &Options) -> CopyResult<()> { Ok(()) } -///Copy the file from `source` to `dest` either using the normal `fs::copy` or the -///`FICLONE` ioctl if --reflink is specified and the filesystem supports it. +/// Copy the file from `source` to `dest` either using the normal `fs::copy` or +/// the `FICLONE` ioctl if --reflink is specified and the filesystem supports +/// it. fn copy_helper(source: &Path, dest: &Path, options: &Options) -> CopyResult<()> { if options.reflink { #[cfg(not(target_os = "linux"))] @@ -1127,7 +1130,8 @@ fn copy_helper(source: &Path, dest: &Path, options: &Options) -> CopyResult<()> source, dest, std::io::Error::last_os_error() - ).into()); + ) + .into()); } else { return Ok(()); } @@ -1156,7 +1160,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(()), } } @@ -1192,6 +1197,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 11f48bccb4e..5324c33368a 100644 --- a/src/cut/buffer.rs +++ b/src/cut/buffer.rs @@ -1,17 +1,15 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Rolf Morel - * (c) kwantam - * substantially rewritten to use the stdlib BufReader trait - * rather than re-implementing it here. - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Rolf Morel +// (c) kwantam +// substantially rewritten to use the stdlib BufReader trait +// rather than re-implementing it here. +// +// For the full copyright and license information, please view the LICENSE +// 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 c6efea47e8e..46a804e00da 100644 --- a/src/cut/cut.rs +++ b/src/cut/cut.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_cut"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Rolf Morel - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Rolf Morel +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; @@ -464,8 +462,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() { @@ -488,7 +486,8 @@ pub fn uumain(args: Vec) -> i32 { "a value 2 characters or longer", "--delimiter", "-d" - ).to_owned()) + ) + .to_owned()) } else { let delim = if delim.is_empty() { "\0".to_owned() @@ -517,7 +516,8 @@ 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)") .to_owned(), @@ -537,7 +537,8 @@ pub fn uumain(args: Vec) -> i32 { "printing a sequence of fields", "--only-delimited", "-s" - ).to_owned()) + ) + .to_owned()) } _ => Ok(mode), }, diff --git a/src/cut/ranges.rs b/src/cut/ranges.rs index 44edcb9434e..e96cb9bd9d7 100644 --- a/src/cut/ranges.rs +++ b/src/cut/ranges.rs @@ -1,11 +1,9 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Rolf Morel - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Rolf Morel +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. use std::str::FromStr; @@ -42,10 +40,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 +62,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/cut/searcher.rs b/src/cut/searcher.rs index 2394ca539fd..f0821ff3a0b 100644 --- a/src/cut/searcher.rs +++ b/src/cut/searcher.rs @@ -1,11 +1,9 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Rolf Morel - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Rolf Morel +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[derive(Clone)] pub struct Searcher<'a> { diff --git a/src/date/date.rs b/src/date/date.rs index db81f2fd6de..37e278ab0fb 100644 --- a/src/date/date.rs +++ b/src/date/date.rs @@ -1,21 +1,19 @@ #![crate_name = "uu_date"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Anthony Deschamps - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Anthony Deschamps +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate chrono; #[macro_use] 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; @@ -128,7 +126,8 @@ pub fn uumain(args: Vec) -> i32 { }; /// Parse a `String` into a `DateTime`. - /// If it fails, return a tuple of the `String` along with its `ParseError`. + /// If it fails, return a tuple of the `String` along with its + /// `ParseError`. fn parse_date( s: String, ) -> Result, (String, chrono::format::ParseError)> { @@ -210,12 +209,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 c19920508f0..e9cea624fcd 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 864438500b4..5dca27ee603 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/dirname/dirname.rs b/src/dirname/dirname.rs index d56c9e4648b..b6b6e865c58 100644 --- a/src/dirname/dirname.rs +++ b/src/dirname/dirname.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_dirname"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Derek Chiang - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Derek Chiang +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; diff --git a/src/du/du.rs b/src/du/du.rs index a3fc1dd1e94..15160d33ebc 100644 --- a/src/du/du.rs +++ b/src/du/du.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_du"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Derek Chiang - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Derek Chiang +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate time; @@ -163,44 +161,46 @@ 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().flat_map(|val| val).rev().filter_map( - |stat| { - if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { - my_stat.size += stat.size; - my_stat.blocks += stat.blocks; - } - if options.max_depth == None || depth < options.max_depth.unwrap() { - Some(stat) - } else { - None - } - }, - )); + stats.extend( + futures + .into_iter() + .flat_map(|val| val) + .rev() + .filter_map(|stat| { + if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { + my_stat.size += stat.size; + my_stat.blocks += stat.blocks; + } + if options.max_depth == None || depth < options.max_depth.unwrap() { + Some(stat) + } else { + None + } + }), + ); stats.push(my_stat); Box::new(stats.into_iter()) } @@ -224,7 +224,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 { @@ -238,66 +241,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"); @@ -339,7 +385,7 @@ pub fn uumain(args: Vec) -> i32 { }; let convert_size_fn = { if matches.opt_present("human-readable") || matches.opt_present("si") { - convert_size_human + convert_size_human } else if matches.opt_present("b") { convert_size_b } else if matches.opt_present("k") { @@ -353,26 +399,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", }; @@ -402,23 +446,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 1178652e1a2..70a03a10ec8 100644 --- a/src/echo/echo.rs +++ b/src/echo/echo.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_echo"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Derek Chiang - * (c) Christopher Brown - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Derek Chiang +// (c) Christopher Brown +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; @@ -71,8 +69,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,14 +88,15 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result { _ => { start = 0; next - }, + } }; } } buffer[1] = c; - // because printing char slices is apparently not available in the standard library + // because printing char slices is apparently not available in the standard + // library for ch in &buffer[start..] { write!(output, "{}", ch)?; } @@ -110,7 +109,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 1d03137a40f..627d0f8a320 100644 --- a/src/env/env.rs +++ b/src/env/env.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_env"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. -/* last synced with: env (GNU coreutils) 8.13 */ +// last synced with: env (GNU coreutils) 8.13 #[macro_use] extern crate clap; @@ -70,8 +68,9 @@ fn parse_program_opt<'a>(opts: &mut Options<'a>, opt: &'a str) -> Result<(), i32 } fn load_config_file(opts: &mut Options) -> Result<(), i32> { - // NOTE: config files are parsed using an INI parser b/c it's available and compatible with ".env"-style files - // ... * but support for actual INI files, although working, is not intended, nor claimed + // NOTE: config files are parsed using an INI parser b/c it's available and + // compatible with ".env"-style files ... * but support for actual INI + // files, although working, is not intended, nor claimed for &file in &opts.files { let conf = if file == "-" { let stdin = io::stdin(); @@ -89,7 +88,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); } @@ -175,8 +175,8 @@ fn run_env(args: Vec) -> Result<(), i32> { program: vec![], }; - // we handle the name, value pairs and the program to be executed by treating them as external - // subcommands in clap + // we handle the name, value pairs and the program to be executed by treating + // them as external subcommands in clap if let (external, Some(matches)) = matches.subcommand() { let mut begin_prog_opts = false; @@ -204,8 +204,9 @@ fn run_env(args: Vec) -> Result<(), i32> { } } - // NOTE: we manually set and unset the env vars below rather than using Command::env() to more - // easily handle the case where no command is given + // NOTE: we manually set and unset the env vars below rather than using + // Command::env() to more easily handle the case where no command is + // given // remove all env vars if told to ignore presets if opts.ignore_env { diff --git a/src/expand/expand.rs b/src/expand/expand.rs index 7430aa1ea68..0ab2d1f1458 100644 --- a/src/expand/expand.rs +++ b/src/expand/expand.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_expand"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Virgile Andreani - * (c) kwantam - * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Virgile Andreani +// (c) kwantam +// 20150428 updated to work with both UTF-8 and non-UTF-8 encodings +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate unicode_width; @@ -45,7 +43,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"); @@ -217,7 +216,8 @@ fn expand(options: Options) { let nts = next_tabstop(ts, col); col += nts; - // now dump out either spaces if we're expanding, or a literal tab if we're not + // now dump out either spaces if we're expanding, or a literal tab if we're + // not if init || !options.iflag { safe_unwrap!(output.write_all(&options.tspaces[..nts].as_bytes())); } else { diff --git a/src/expr/expr.rs b/src/expr/expr.rs index f0e124d428c..1dc1def688a 100644 --- a/src/expr/expr.rs +++ b/src/expr/expr.rs @@ -1,27 +1,26 @@ #![crate_name = "uu_expr"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Roman Gafiyatullin - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Roman Gafiyatullin +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. 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"); pub fn uumain(args: Vec) -> i32 { // For expr utility we do not want getopts. - // The following usage should work without escaping hyphens: `expr -15 = 1 + 2 \* \( 3 - -4 \)` + // The following usage should work without escaping hyphens: `expr -15 = 1 + 2 + // \* \( 3 - -4 \)` if maybe_handle_help_or_version(&args) { 0 diff --git a/src/expr/syntax_tree.rs b/src/expr/syntax_tree.rs index 66b467bf6ea..74598ad22be 100644 --- a/src/expr/syntax_tree.rs +++ b/src/expr/syntax_tree.rs @@ -1,19 +1,17 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Roman Gafiyatullin - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -//! -//! Here we employ shunting-yard algorithm for building AST from tokens according to operators' precedence and associativeness. +// This file is part of the uutils coreutils package. +// +// (c) Roman Gafiyatullin +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +//! Here we employ shunting-yard algorithm for building AST from tokens +//! according to operators' precedence and associativeness. //! * 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 +83,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| { @@ -300,11 +300,13 @@ fn push_token_to_either_stack( let result = match *token { Token::Value { .. } => Ok(out_stack.push((token_idx, token.clone()))), - Token::InfixOp { .. } => if op_stack.is_empty() { - Ok(op_stack.push((token_idx, token.clone()))) - } else { - push_op_to_stack(token_idx, token, out_stack, op_stack) - }, + Token::InfixOp { .. } => { + if op_stack.is_empty() { + Ok(op_stack.push((token_idx, token.clone()))) + } else { + push_op_to_stack(token_idx, token, out_stack, op_stack) + } + } Token::PrefixOp { .. } => Ok(op_stack.push((token_idx, token.clone()))), @@ -362,12 +364,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 5684b0bed10..a267eab9777 100644 --- a/src/expr/tokens.rs +++ b/src/expr/tokens.rs @@ -1,21 +1,19 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Roman Gafiyatullin - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Roman Gafiyatullin +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. -//! //! The following tokens are present in the expr grammar: //! * integer literal; //! * string literal; //! * infix binary operators; //! * prefix operators. //! -//! According to the man-page of expr we have expression split into tokens (each token -- separate CLI-argument). -//! Hence all we need is to map the strings into the Token structures, except for some ugly fiddling with +-escaping. +//! According to the man-page of expr we have expression split into tokens (each +//! token -- separate CLI-argument). Hence all we need is to map the strings +//! into the Token structures, except for some ugly fiddling with +-escaping. //! #[derive(Debug, Clone)] @@ -144,12 +142,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 6e336841561..93523541f65 100644 --- a/src/factor/build.rs +++ b/src/factor/build.rs @@ -1,11 +1,9 @@ -/* -* This file is part of the uutils coreutils package. -* -* (c) kwantam -* -* For the full copyright and license information, please view the LICENSE file -* that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) kwantam +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. //! Generate a table of the multiplicative inverses of p_i mod 2^64 //! for the first 1027 odd primes (all 13 bit and smaller primes). @@ -78,7 +76,8 @@ fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&out_dir).join("prime_table.rs")).unwrap(); - // By default, we print the multiplicative inverses mod 2^64 of the first 1k primes + // By default, we print the multiplicative inverses mod 2^64 of the first 1k + // primes let n = args() .skip(1) .next() @@ -115,7 +114,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 2f5d5bb2f7f..05d2c5424e2 100644 --- a/src/factor/factor.rs +++ b/src/factor/factor.rs @@ -1,17 +1,15 @@ #![crate_name = "uu_factor"] -/* -* This file is part of the uutils coreutils package. -* -* (c) T. Jameson Little -* (c) Wiktor Kuropatwa -* 20150223 added Pollard rho method implementation -* (c) kwantam -* 20150429 sped up trial division by adding table of prime inverses -* -* For the full copyright and license information, please view the LICENSE file -* that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) T. Jameson Little +// (c) Wiktor Kuropatwa +// 20150223 added Pollard rho method implementation +// (c) kwantam +// 20150429 sped up trial division by adding table of prime inverses +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate rand; @@ -20,12 +18,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; @@ -130,9 +128,9 @@ fn table_division(mut num: u64, factors: &mut Vec) { // do we still have more factoring to do? // Decide whether to use Pollard Rho or slow divisibility based on // number's size: - //if num >= 1 << 63 { + // if num >= 1 << 63 { // number is too big to use rho pollard without overflowing - //trial_division_slow(num, factors); + // trial_division_slow(num, factors); //} else if num > 1 { // number is still greater than 1, but not so big that we have to worry rho_pollard_factor(num, factors); diff --git a/src/factor/numeric.rs b/src/factor/numeric.rs index 0cce6093a8f..a527f2ead67 100644 --- a/src/factor/numeric.rs +++ b/src/factor/numeric.rs @@ -1,16 +1,14 @@ -/* -* This file is part of the uutils coreutils package. -* -* (c) Wiktor Kuropatwa -* (c) kwantam -* 20150507 added big_ routines to prevent overflow when num > 2^63 -* -* For the full copyright and license information, please view the LICENSE file -* that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) Wiktor Kuropatwa +// (c) kwantam +// 20150507 added big_ routines to prevent overflow when num > 2^63 +// +// For the full copyright and license information, please view the LICENSE +// file 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/factor/sieve.rs b/src/factor/sieve.rs index d0a2711f25c..44d6d07f57c 100644 --- a/src/factor/sieve.rs +++ b/src/factor/sieve.rs @@ -1,11 +1,9 @@ -/* -* This file is part of the uutils coreutils package. -* -* (c) kwantam -* -* For the full copyright and license information, please view the LICENSE file -* that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) kwantam +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. use std::iter::{Chain, Cycle, Map}; use std::slice::Iter; diff --git a/src/false/false.rs b/src/false/false.rs index bdfe1c1b678..13f25843c1e 100644 --- a/src/false/false.rs +++ b/src/false/false.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_false"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. pub fn uumain(_: Vec) -> i32 { 1 diff --git a/src/fmt/fmt.rs b/src/fmt/fmt.rs index 816e47ede5c..03f7ab2d22c 100644 --- a/src/fmt/fmt.rs +++ b/src/fmt/fmt.rs @@ -1,25 +1,23 @@ #![crate_name = "uu_fmt"] -/* - * This file is part of `fmt` from the uutils coreutils package. - * - * (c) kwantam - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of `fmt` from the uutils coreutils package. +// +// (c) kwantam +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate unicode_width; #[macro_use] extern crate uucore; +use linebreak::break_lines; +use parasplit::ParagraphStream; 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::io::{BufReader, BufWriter, Read}; macro_rules! silent_unwrap( ($exp:expr) => ( diff --git a/src/fmt/linebreak.rs b/src/fmt/linebreak.rs index 2bf7b0ef963..75a4a97595b 100644 --- a/src/fmt/linebreak.rs +++ b/src/fmt/linebreak.rs @@ -1,18 +1,16 @@ -/* - * This file is part of `fmt` from the uutils coreutils package. - * - * (c) kwantam - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of `fmt` from the uutils coreutils package. +// +// (c) kwantam +// +// For the full copyright and license information, please view the LICENSE +// 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 +56,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())); @@ -106,7 +105,8 @@ fn accum_words_simple<'a>( (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>, ) -> (usize, bool) { - // compute the length of this word, considering how tabs will expand at this position on the line + // compute the length of this word, considering how tabs will expand at this + // position on the line let wlen = winfo.word_nchars + args.compute_width(winfo, l, false); let slen = compute_slen( @@ -127,8 +127,8 @@ fn accum_words_simple<'a>( } // break_knuth_plass implements an "optimal" breaking algorithm in the style of -// Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in Software, -// Practice and Experience. Vol. 11, No. 11, November 1981. +// Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in +// Software, Practice and Experience. Vol. 11, No. 11, November 1981. // http://onlinelibrary.wiley.com/doi/10.1002/spe.4380111102/pdf fn break_knuth_plass<'a, T: Clone + Iterator>>( mut iter: T, @@ -137,14 +137,16 @@ fn break_knuth_plass<'a, T: Clone + Iterator>>( // run the algorithm to get the breakpoints let breakpoints = find_kp_breakpoints(iter.clone(), args); - // iterate through the breakpoints (note that breakpoints is in reverse break order, so we .rev() it + // iterate through the breakpoints (note that breakpoints is in reverse break + // order, so we .rev() it let (mut prev_punct, mut fresh) = breakpoints.iter().rev().fold( (false, false), |(mut prev_punct, mut fresh), &(next_break, break_before)| { if fresh { write_newline(args.indent_str, args.ostream); } - // at each breakpoint, keep emitting words until we find the word matching this breakpoint + // at each breakpoint, keep emitting words until we find the word matching this + // breakpoint for winfo in &mut iter { let (slen, word) = slice_if_fresh( fresh, @@ -159,7 +161,8 @@ fn break_knuth_plass<'a, T: Clone + Iterator>>( prev_punct = winfo.ends_punct; // We find identical breakpoints here by comparing addresses of the references. - // This is OK because the backing vector is not mutating once we are linebreaking. + // This is OK because the backing vector is not mutating once we are + // linebreaking. let winfo_ptr = winfo as *const _; let next_break_ptr = next_break as *const _; if winfo_ptr == next_break_ptr { @@ -168,7 +171,8 @@ fn break_knuth_plass<'a, T: Clone + Iterator>>( write_newline(args.indent_str, args.ostream); write_with_spaces(&winfo.word[winfo.word_start..], 0, args.ostream); } else { - // breaking after this word, so that means "fresh" is true for the next iteration + // breaking after this word, so that means "fresh" is true for the next + // iteration write_with_spaces(word, slen, args.ostream); fresh = true; } @@ -218,19 +222,17 @@ 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, - }, - ]; - // this vec holds the current active linebreaks; next_ holds the breaks that will be active for - // the next word + 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]; let next_active_breaks = &mut vec![]; @@ -275,11 +277,14 @@ 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 - // otherwise, we extend the break, and possibly add a new break at this point + // if tlen is longer than args.opts.width, we drop this break from the active + // list otherwise, we extend the break, and possibly add a new break + // at this point if tlen <= args.opts.width { // this break will still be active next time next_active_breaks.push(i); @@ -304,7 +309,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; @@ -334,7 +340,8 @@ fn find_kp_breakpoints<'a, T: Iterator>>( } if next_active_breaks.is_empty() { - // every potential linebreak is too long! choose the linebreak with the least demerits, ld_idx + // every potential linebreak is too long! choose the linebreak with the least + // demerits, ld_idx let new_break = restart_active_breaks(args, &linebreaks[ld_idx], ld_idx, w, slen, minlength); next_active_breaks.push(linebreaks.len()); @@ -347,7 +354,8 @@ fn find_kp_breakpoints<'a, T: Iterator>>( } // swap in new list of active breaks mem::swap(active_breaks, next_active_breaks); - // If this was the last word in a sentence, the next one must be the first in the next. + // If this was the last word in a sentence, the next one must be the first in + // the next. is_sentence_start = is_sentence_end; } @@ -380,7 +388,8 @@ fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a Wo } } -// "infinite" badness is more like (1+BAD_INFTY)^2 because of how demerits are computed +// "infinite" badness is more like (1+BAD_INFTY)^2 because of how demerits are +// computed const BAD_INFTY: i64 = 10_000_000; const BAD_INFTY_SQ: i64 = BAD_INFTY * BAD_INFTY; // badness = BAD_MULT * abs(r) ^ 3 @@ -459,7 +468,8 @@ fn restart_active_breaks<'a>( } } -// Number of spaces to add before a word, based on mode, newline, sentence start. +// Number of spaces to add before a word, based on mode, newline, sentence +// start. fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize { if uniform || newline { if start || (newline && punct) { diff --git a/src/fmt/parasplit.rs b/src/fmt/parasplit.rs index 5ffe4593e9e..7299737bcef 100644 --- a/src/fmt/parasplit.rs +++ b/src/fmt/parasplit.rs @@ -1,14 +1,12 @@ -/* - * This file is part of `fmt` from the uutils coreutils package. - * - * (c) kwantam - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of `fmt` from the uutils coreutils package. +// +// (c) kwantam +// +// For the full copyright and license information, please view the LICENSE +// 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; @@ -16,18 +14,18 @@ use FmtOptions; fn char_width(c: char) -> usize { if (c as usize) < 0xA0 { - // if it is ASCII, call it exactly 1 wide (including control chars) + // If it is ASCII, call it exactly 1 wide (including control chars) // calling control chars' widths 1 is consistent with OpenBSD fmt 1 } else { - // otherwise, get the unicode width - // note that we shouldn't actually get None here because only c < 0xA0 + // Otherwise, get the unicode width: + // Note that we shouldn't actually get None here because only c < 0xA0 // can return None, but for safety and future-proofing we do it this way UnicodeWidthChar::width(c).unwrap_or(1) } } -// lines with PSKIP, lacking PREFIX, or which are entirely blank are +// Lines with PSKIP, lacking PREFIX, or which are entirely blank are // NoFormatLines; otherwise, they are FormatLines #[derive(Debug)] pub enum Line { @@ -36,7 +34,7 @@ pub enum Line { } impl Line { - // when we know that it's a FormatLine, as in the ParagraphStream iterator + // When we know that it's a FormatLine, as in the ParagraphStream iterator fn get_formatline(self) -> FileLine { match self { Line::FormatLine(fl) => fl, @@ -44,7 +42,7 @@ impl Line { } } - // when we know that it's a NoFormatLine, as in the ParagraphStream iterator + // When we know that it's a NoFormatLine, as in the ParagraphStream iterator fn get_noformatline(self) -> (String, bool) { match self { Line::NoFormatLine(s, b) => (s, b), @@ -53,18 +51,22 @@ impl Line { } } -// each line's prefix has to be considered to know whether to merge it with +// Each line's prefix has to be considered to know whether to merge it with // the next line or not #[derive(Debug)] pub struct FileLine { line: String, - indent_end: usize, // the end of the indent, always the start of the text - pfxind_end: usize, // the end of the PREFIX's indent, that is, the spaces before the prefix - indent_len: usize, // display length of indent taking into account tabs - prefix_len: usize, // PREFIX indent length taking into account tabs + // The end of the indent, always the start of the text + indent_end: usize, + // The end of the PREFIX's indent, that is, the spaces before the prefix + pfxind_end: usize, + // Display length of indent taking into account tabs + indent_len: usize, + // PREFIX indent length taking into account tabs + prefix_len: usize, } -// iterator that produces a stream of Lines from a file +// Iterator that produces a stream of Lines from a file pub struct FileLines<'a> { opts: &'a FmtOptions, lines: Lines<&'a mut FileOrStdReader>, @@ -72,13 +74,10 @@ 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 + // Returns true if this line should be formatted fn match_prefix(&self, line: &str) -> (bool, usize) { if !self.opts.use_prefix { return (true, 0); @@ -87,7 +86,7 @@ impl<'a> FileLines<'a> { FileLines::match_prefix_generic(&self.opts.prefix[..], line, self.opts.xprefix) } - // returns true if this line should be formatted + // Returns true if this line should be formatted fn match_anti_prefix(&self, line: &str) -> bool { if !self.opts.use_anti_prefix { return true; @@ -109,7 +108,8 @@ impl<'a> FileLines<'a> { } if !exact { - // we do it this way rather than byte indexing to support unicode whitespace chars + // We do it this way rather than byte indexing to support unicode + // whitespace chars for (i, char) in line.char_indices() { if line[i..].starts_with(pfx) { return (true, i); @@ -128,19 +128,20 @@ impl<'a> FileLines<'a> { let mut indent_end = 0; for (os, c) in string.char_indices() { if os == prefix_end { - // we found the end of the prefix, so this is the printed length of the prefix here + // We found the end of the prefix, so this is the printed length + // of the prefix here prefix_len = indent_len; } if (os >= prefix_end) && !c.is_whitespace() { - // found first non-whitespace after prefix, this is indent_end + // Found first non-whitespace after prefix, this is indent_end indent_end = os; break; } else if c == '\t' { - // compute tab length + // Compute tab length indent_len = (indent_len / self.opts.tabwidth + 1) * self.opts.tabwidth; } else { - // non-tab character + // Non-tab character indent_len += char_width(c); } } @@ -160,7 +161,7 @@ impl<'a> Iterator for FileLines<'a> { None => return None, }; - // if this line is entirely whitespace, + // If this line is entirely whitespace, // emit a blank line // Err(true) indicates that this was a linebreak, // which is important to know when detecting mail headers @@ -168,7 +169,7 @@ impl<'a> Iterator for FileLines<'a> { return Some(Line::NoFormatLine("".to_owned(), true)); } - // if this line does not match the prefix, + // If this line does not match the prefix, // emit the line unprocessed and iterate again let (pmatch, poffset) = self.match_prefix(&n[..]); if !pmatch { @@ -177,7 +178,7 @@ impl<'a> Iterator for FileLines<'a> { .chars() .all(|c| c.is_whitespace()) { - // if the line matches the prefix, but is blank after, + // If the line matches the prefix, but is blank after, // don't allow lines to be combined through it (that is, // treat it like a blank line, except that since it's // not truly blank we will not allow mail headers on the @@ -185,13 +186,13 @@ impl<'a> Iterator for FileLines<'a> { return Some(Line::NoFormatLine(n, false)); } - // skip if this line matches the anti_prefix + // Skip if this line matches the anti_prefix // (NOTE definition of match_anti_prefix is TRUE if we should process) if !self.match_anti_prefix(&n[..]) { return Some(Line::NoFormatLine(n, false)); } - // figure out the indent, prefix, and prefixindent ending points + // Figure out the indent, prefix, and prefixindent ending points let prefix_end = poffset + self.opts.prefix.len(); let (indent_end, prefix_len, indent_len) = self.compute_indent(&n[..], prefix_end); @@ -205,23 +206,33 @@ impl<'a> Iterator for FileLines<'a> { } } -// a paragraph : a collection of FileLines that are to be formatted +// A paragraph is a collection of FileLines that are to be formatted // plus info about the paragraph's indentation // (but we only retain the String from the FileLine; the other info // is only there to help us in deciding how to merge lines into Paragraphs #[derive(Debug)] pub struct Paragraph { - lines: Vec, // the lines of the file - pub init_str: String, // string representing the init, that is, the first line's indent - pub init_len: usize, // printable length of the init string considering TABWIDTH - init_end: usize, // byte location of end of init in first line String - pub indent_str: String, // string representing indent - pub indent_len: usize, // length of above - indent_end: usize, // byte location of end of indent (in crown and tagged mode, only applies to 2nd line and onward) - pub mail_header: bool, // we need to know if this is a mail header because we do word splitting differently in that case + // The lines of the file + lines: Vec, + // String representing the init, that is, the first line's indent + pub init_str: String, + // Printable length of the init string considering TABWIDTH + pub init_len: usize, + // Byte location of end of init in first line String + init_end: usize, + // String representing indent + pub indent_str: String, + // Length of above + pub indent_len: usize, + // Byte location of end of indent (in crown and tagged mode, only applies to + // 2nd line and onward) + indent_end: usize, + // We need to know if this is a mail header because we do word splitting + // differently in that case + pub mail_header: bool, } -// an iterator producing a stream of paragraphs from a stream of lines +// An iterator producing a stream of paragraphs from a stream of lines // given a set of options. pub struct ParagraphStream<'a> { lines: Peekable>, @@ -232,7 +243,7 @@ pub struct ParagraphStream<'a> { impl<'a> ParagraphStream<'a> { pub fn new<'b>(opts: &'b FmtOptions, reader: &'b mut FileOrStdReader) -> ParagraphStream<'b> { let lines = FileLines::new(opts, reader.lines()).peekable(); - // at the beginning of the file, we might find mail headers + // At the beginning of the file, we might find mail headers ParagraphStream { lines, next_mail: true, @@ -242,7 +253,7 @@ impl<'a> ParagraphStream<'a> { // detect RFC822 mail header fn is_mail_header(line: &FileLine) -> bool { - // a mail header begins with either "From " (envelope sender line) + // A mail header begins with either "From " (envelope sender line) // or with a sequence of printable ASCII chars (33 to 126, inclusive, // except colon) followed by a colon. if line.indent_end > 0 { @@ -275,7 +286,7 @@ impl<'a> Iterator for ParagraphStream<'a> { type Item = Result; fn next(&mut self) -> Option> { - // return a NoFormatLine in an Err; it should immediately be output + // Return a NoFormatLine in an Err; it should immediately be output let noformat = match self.lines.peek() { None => return None, Some(l) => match *l { @@ -284,14 +295,14 @@ impl<'a> Iterator for ParagraphStream<'a> { }, }; - // found a NoFormatLine, immediately dump it out + // Found a NoFormatLine, immediately dump it out if noformat { let (s, nm) = self.lines.next().unwrap().get_noformatline(); self.next_mail = nm; return Some(Err(s)); } - // found a FormatLine, now build a paragraph + // Found a FormatLine, now build a paragraph let mut init_str = String::new(); let mut init_end = 0; let mut init_len = 0; @@ -303,11 +314,12 @@ impl<'a> Iterator for ParagraphStream<'a> { let mut p_lines = Vec::new(); let mut in_mail = false; - let mut second_done = false; // for when we use crown or tagged mode + // For when we use crown or tagged mode + let mut second_done = false; loop { { - // peek ahead - // need to explicitly force fl out of scope before we can call self.lines.next() + // Peek ahead. We need to explicitly force fl out of scope + // before we can call `self.lines.next()` let fl = match self.lines.peek() { None => break, Some(l) => match *l { @@ -317,13 +329,13 @@ impl<'a> Iterator for ParagraphStream<'a> { }; if p_lines.is_empty() { - // first time through the loop, get things set up + // First time through the loop, get things set up // detect mail header if self.opts.mail && self.next_mail && ParagraphStream::is_mail_header(fl) { in_mail = true; - // there can't be any indent or pfxind because otherwise is_mail_header - // would fail since there cannot be any whitespace before the colon in a - // valid header field + // There can't be any indent or pfxind because otherwise + // `is_mail_header` would fail since there cannot be any + // whitespace before the colon in a valid header field indent_str.push_str(" "); indent_len = 2; } else { @@ -335,44 +347,51 @@ impl<'a> Iterator for ParagraphStream<'a> { second_done = true; } - // these will be overwritten in the 2nd line of crown or tagged mode, but - // we are not guaranteed to get to the 2nd line, e.g., if the next line - // is a NoFormatLine or None. Thus, we set sane defaults the 1st time around + // These will be overwritten in the 2nd line of crown or + // tagged mode, but we are not guaranteed to get to the + // 2nd line, e.g., if the next line is a NoFormatLine or + // None. Thus, we set sane defaults the 1st time around indent_str.push_str(&fl.line[..fl.indent_end]); indent_len = fl.indent_len; indent_end = fl.indent_end; - // save these to check for matching lines + // Save these to check for matching lines prefix_len = fl.prefix_len; pfxind_end = fl.pfxind_end; - // in tagged mode, add 4 spaces of additional indenting by default - // (gnu fmt's behavior is different: it seems to find the closest column to - // indent_end that is divisible by 3. But honestly that behavior seems - // pretty arbitrary. - // Perhaps a better default would be 1 TABWIDTH? But ugh that's so big. + // In tagged mode, add 4 spaces of additional indenting + // by default (gnu fmt's behavior is different: it seems + // to find the closest column to indent_end that is + // divisible by 3. But honestly that behavior seems + // pretty arbitrary. Perhaps a better default would be 1 + // TABWIDTH? But ugh that's so big. if self.opts.tagged { indent_str.push_str(" "); indent_len += 4; } } } else if in_mail { - // lines following mail headers must begin with spaces + // Lines following mail headers must begin with spaces if fl.indent_end == 0 || (self.opts.use_prefix && fl.pfxind_end == 0) { break; // this line does not begin with spaces } } else if !second_done { - // now we have enough info to handle crown margin and tagged mode + // Now we have enough info to handle crown margin and tagged + // mode if prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end { - // in both crown and tagged modes we require that prefix_len is the same + // In both crown and tagged modes we require that + // prefix_len is the same break; - } else if self.opts.tagged && indent_len - 4 == fl.indent_len + } else if self.opts.tagged + && indent_len - 4 == fl.indent_len && indent_end == fl.indent_end { - // in tagged mode, indent has to be *different* on following lines + // In tagged mode, indent has to be *different* on + // following lines break; } else { - // this is part of the same paragraph, get the indent info from this line + // This is part of the same paragraph, get the indent + // info from this line indent_str.clear(); indent_str.push_str(&fl.line[..fl.indent_end]); indent_len = fl.indent_len; @@ -380,8 +399,9 @@ impl<'a> Iterator for ParagraphStream<'a> { } second_done = true; } else { - // detect mismatch - if indent_end != fl.indent_end || pfxind_end != fl.pfxind_end + // Detect mismatch + if indent_end != fl.indent_end + || pfxind_end != fl.pfxind_end || indent_len != fl.indent_len || prefix_len != fl.prefix_len { @@ -392,15 +412,15 @@ impl<'a> Iterator for ParagraphStream<'a> { p_lines.push(self.lines.next().unwrap().get_formatline().line); - // when we're in split-only mode, we never join lines, so stop here + // When we're in split-only mode, we never join lines, so stop here if self.opts.split_only { break; } } - // if this was a mail header, then the next line can be detected as one. Otherwise, it cannot. - // NOTE next_mail is true at ParagraphStream instantiation, and is set to true after a blank - // NoFormatLine. + // If this was a mail header, then the next line can be detected as one. + // Otherwise, it cannot. NOTE next_mail is true at ParagraphStream + // instantiation, and is set to true after a blank NoFormatLine. self.next_mail = in_mail; Some(Ok(Paragraph { @@ -435,9 +455,9 @@ impl<'a> ParaWords<'a> { fn create_words(&mut self) { if self.para.mail_header { - // no extra spacing for mail headers; always exactly 1 space - // safe to trim_left on every line of a mail header, since the - // first line is guaranteed not to have any spaces + // No extra spacing for mail headers; always exactly 1 space safe to + // trim_left on every line of a mail header, since the first line is + // guaranteed not to have any spaces self.words.extend( self.para .lines @@ -446,7 +466,9 @@ impl<'a> ParaWords<'a> { .map(|x| WordInfo { word: x, word_start: 0, - word_nchars: x.len(), // OK for mail headers; only ASCII allowed (unicode is escaped) + // OK for mail headers; only ASCII is allowed (unicode + // is escaped) + word_nchars: x.len(), before_tab: None, after_tab: 0, sentence_start: false, @@ -455,12 +477,13 @@ impl<'a> ParaWords<'a> { }), ); } else { - // first line + // First line self.words.extend(if self.opts.crown || self.opts.tagged { - // crown and tagged mode has the "init" in the first line, so slice from there + // Crown and tagged mode has the "init" in the first line, so + // slice from there WordSplit::new(self.opts, &self.para.lines[0][self.para.init_end..]) } else { - // otherwise we slice from the indent + // Otherwise we slice from the indent WordSplit::new(self.opts, &self.para.lines[0][self.para.indent_end..]) }); @@ -493,8 +516,9 @@ struct WordSplit<'a> { impl<'a> WordSplit<'a> { fn analyze_tabs(&self, string: &str) -> (Option, usize, Option) { - // given a string, determine (length before tab) and (printed length after first tab) - // if there are no tabs, beforetab = -1 and aftertab is the printed length + // Given a string, determine (length before tab) and (printed length + // after first tab) if there are no tabs, beforetab = -1 and aftertab is + // the printed length let mut beforetab = None; let mut aftertab = 0; let mut word_start = None; @@ -519,7 +543,7 @@ impl<'a> WordSplit<'a> { impl<'a> WordSplit<'a> { fn new<'b>(opts: &'b FmtOptions, string: &'b str) -> WordSplit<'b> { - // wordsplits *must* start at a non-whitespace character + // Wordsplits *must* start at a non-whitespace character let trim_string = string.trim_start(); WordSplit { opts, @@ -549,7 +573,7 @@ pub struct WordInfo<'a> { pub new_line: bool, } -// returns (&str, is_start_of_sentence) +// Returns (&str, is_start_of_sentence) impl<'a> Iterator for WordSplit<'a> { type Item = WordInfo<'a>; @@ -561,7 +585,8 @@ impl<'a> Iterator for WordSplit<'a> { let old_position = self.position; let new_line = old_position == 0; - // find the start of the next word, and record if we find a tab character + // Find the start of the next word, and record if we find a tab + // character let (before_tab, after_tab, word_start) = match self.analyze_tabs(&self.string[old_position..]) { (b, a, Some(s)) => (b, a, s + old_position), @@ -571,7 +596,7 @@ impl<'a> Iterator for WordSplit<'a> { } }; - // find the beginning of the next whitespace + // Find the beginning of the next whitespace // note that this preserves the invariant that self.position // points to whitespace character OR end of string let mut word_nchars = 0; @@ -588,11 +613,12 @@ impl<'a> Iterator for WordSplit<'a> { }; let word_start_relative = word_start - old_position; - // if the previous sentence was punctuation and this sentence has >2 whitespace or one tab, is a new sentence. + // Ff the previous sentence was punctuation and this sentence has >2 + // whitespace or one tab, is a new sentence. let is_start_of_sentence = self.prev_punct && (before_tab.is_some() || word_start_relative > 1); - // now record whether this word ends in punctuation + // Now record whether this word ends in punctuation self.prev_punct = match self.string[..self.position].chars().rev().next() { Some(ch) => WordSplit::is_punctuation(ch), _ => panic!("fatal: expected word not to be empty"), diff --git a/src/fold/fold.rs b/src/fold/fold.rs index 8e083df3236..12824f63342 100644 --- a/src/fold/fold.rs +++ b/src/fold/fold.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_fold"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; @@ -70,9 +68,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 +141,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 406429eeae1..d320382d4c9 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 d85403ee68d..d9b885e002b 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 a902290c43c..03143ab9f03 100644 --- a/src/hashsum/hashsum.rs +++ b/src/hashsum/hashsum.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_hashsum"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * (c) Vsevolod Velichko - * (c) Gil Cottle - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// (c) Vsevolod Velichko +// (c) Gil Cottle +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate hex; @@ -318,17 +316,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, @@ -446,7 +434,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); diff --git a/src/head/head.rs b/src/head/head.rs index efc0ab8db54..495a5172c0d 100644 --- a/src/head/head.rs +++ b/src/head/head.rs @@ -1,21 +1,19 @@ #![crate_name = "uu_head"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alan Andrade - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - * - * Synced with: https://raw.github.com/avsm/src/master/usr.bin/head/head.c - */ +// This file is part of the uutils coreutils package. +// +// (c) Alan Andrade +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. +// +// Synced with: https://raw.github.com/avsm/src/master/usr.bin/head/head.c #[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 +88,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 +186,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/hostid/hostid.rs b/src/hostid/hostid.rs index 955868aeaf6..577feda7b6f 100644 --- a/src/hostid/hostid.rs +++ b/src/hostid/hostid.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_hostid"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Maciej Dziardziel - * - * For the full copyright and license information, please view the LICENSE file - * that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Maciej Dziardziel +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate libc; @@ -32,11 +30,9 @@ pub fn uumain(args: Vec) -> i32 { } fn hostid() { - /* - * POSIX says gethostid returns a "32-bit identifier" but is silent - * whether it's sign-extended. Turn off any sign-extension. This - * is a no-op unless unsigned int is wider than 32 bits. - */ + // POSIX says gethostid returns a "32-bit identifier" but is silent + // whether it's sign-extended. Turn off any sign-extension. This + // is a no-op unless unsigned int is wider than 32 bits. let mut result: c_long; unsafe { diff --git a/src/hostname/hostname.rs b/src/hostname/hostname.rs index 7808b6c38c0..20686c71240 100644 --- a/src/hostname/hostname.rs +++ b/src/hostname/hostname.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_hostname"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alan Andrade - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alan Andrade +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; @@ -17,21 +15,21 @@ extern crate winapi; #[macro_use] extern crate uucore; +use getopts::Matches; use std::collections::hash_set::HashSet; -use std::iter::repeat; use std::io; -use std::str; +use std::iter::repeat; use std::net::ToSocketAddrs; -use getopts::Matches; +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; @@ -61,12 +59,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() { @@ -90,9 +104,10 @@ fn display_hostname(matches: Matches) -> i32 { let hostname = return_if_err!(1, xgethostname()); if matches.opt_present("i") { - // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later. - // This was originally supposed to use std::net::lookup_host, but that seems to be - // deprecated. Perhaps we should use the dns-lookup crate? + // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it + // later. This was originally supposed to use std::net::lookup_host, but + // that seems to be deprecated. Perhaps we should use the dns-lookup + // crate? let hostname = hostname + ":1"; match hostname.to_socket_addrs() { Ok(addresses) => { diff --git a/src/id/id.rs b/src/id/id.rs index 0b87fb5ec79..783a052574e 100644 --- a/src/id/id.rs +++ b/src/id/id.rs @@ -10,28 +10,27 @@ // Synced with: // http://ftp-archive.freebsd.org/mirror/FreeBSD-Archive/old-releases/i386/1.0-RELEASE/ports/shellutils/src/id.c // http://www.opensource.apple.com/source/shell_cmds/shell_cmds-118/id/id.c -// #![allow(non_camel_case_types)] #![allow(dead_code)] #[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"))] mod audit { - pub use std::mem::uninitialized; use super::libc::{c_int, c_uint, dev_t, pid_t, uid_t, uint64_t}; + pub use std::mem::uninitialized; pub type au_id_t = uid_t; pub type au_asid_t = pid_t; diff --git a/src/install/install.rs b/src/install/install.rs index 4d7aeb61184..f6e6f720f79 100644 --- a/src/install/install.rs +++ b/src/install/install.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_install"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Ben Eills - * - * For the full copyright and license information, please view the LICENSE file - * that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Ben Eills +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; @@ -57,7 +55,6 @@ impl Behaviour { /// Main install utility function, called from main.rs. /// /// Returns a program return code. -/// pub fn uumain(args: Vec) -> i32 { let matches = parse_opts(args); @@ -92,7 +89,6 @@ pub fn uumain(args: Vec) -> i32 { /// Build a specification of the command line. /// /// Returns a getopts::Options struct. -/// fn parse_opts(args: Vec) -> getopts::Matches { let syntax = format!( "SOURCE DEST @@ -100,49 +96,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) } @@ -153,7 +215,6 @@ fn parse_opts(args: Vec) -> getopts::Matches { /// # Errors /// /// Error datum is a string of the unimplemented argument. -/// fn check_unimplemented(matches: &getopts::Matches) -> Result<(), &str> { if matches.opt_present("backup") { Err("--backup") @@ -195,7 +256,6 @@ fn check_unimplemented(matches: &getopts::Matches) -> Result<(), &str> { /// # Errors /// /// In event of failure, returns an integer intended as a program return code. -/// fn behaviour(matches: &getopts::Matches) -> Result { let main_function = if matches.opt_present("directory") { MainFunction::Directory @@ -257,7 +317,6 @@ fn behaviour(matches: &getopts::Matches) -> Result { /// the specified directories'. /// /// Returns an integer intended as a program return code. -/// fn directory(paths: &[PathBuf], b: Behaviour) -> i32 { if paths.len() < 1 { println!("{} with -d requires at least one argument.", NAME); @@ -303,7 +362,6 @@ fn is_new_file_path(path: &Path) -> bool { /// Perform an install, given a list of paths and behaviour. /// /// Returns an integer intended as a program return code. -/// fn standard(paths: &[PathBuf], b: Behaviour) -> i32 { if paths.len() < 2 { println!("{} requires at least 2 arguments.", NAME); @@ -329,7 +387,6 @@ fn standard(paths: &[PathBuf], b: Behaviour) -> i32 { /// /// _files_ must all exist as non-directories. /// _target_dir_ must be a directory. -/// fn copy_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) -> i32 { if !target_dir.is_dir() { show_error!("target ‘{}’ is not a directory", target_dir.display()); @@ -371,7 +428,6 @@ fn copy_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) - /// /// _file_ must exist as a non-directory. /// _target_ must be a non-directory -/// fn copy_file_to_file(file: &PathBuf, target: &PathBuf, b: &Behaviour) -> i32 { if copy(file, &target, b).is_err() { 1 @@ -389,8 +445,8 @@ fn copy_file_to_file(file: &PathBuf, target: &PathBuf, b: &Behaviour) -> i32 { /// /// # Errors /// -/// If the copy system call fails, we print a verbose error and return an empty error value. -/// +/// If the copy system call fails, we print a verbose error and return an empty +/// error value. fn copy(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<(), ()> { let io_result = fs::copy(from, to); diff --git a/src/install/mode.rs b/src/install/mode.rs index 726b359df99..5daf5a888dd 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; @@ -20,7 +20,6 @@ pub fn parse(mode_string: &str, considering_dir: bool) -> Result { /// chmod a file or directory on UNIX. /// /// Adapted from mkdir.rs. Handles own error printing. -/// #[cfg(any(unix, target_os = "redox"))] pub fn chmod(path: &Path, mode: u32) -> Result<(), ()> { use std::os::unix::fs::PermissionsExt; @@ -32,9 +31,9 @@ pub fn chmod(path: &Path, mode: u32) -> Result<(), ()> { /// chmod a file or directory on Windows. /// /// Adapted from mkdir.rs. -/// #[cfg(windows)] pub fn chmod(path: &Path, mode: u32) -> Result<(), ()> { - // chmod on Windows only sets the readonly flag, which isn't even honored on directories + // chmod on Windows only sets the readonly flag, which isn't even honored on + // directories Ok(()) } diff --git a/src/join/join.rs b/src/join/join.rs index 6d2ccb7ed2d..767043129eb 100755 --- a/src/join/join.rs +++ b/src/join/join.rs @@ -1,23 +1,21 @@ #![crate_name = "uu_join"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Konstantin Pospelov - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Konstantin Pospelov +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. 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 +423,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 739efb8df8a..f02cdfe5f4f 100644 --- a/src/kill/kill.rs +++ b/src/kill/kill.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_kill"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Maciej Dziardziel - * - * For the full copyright and license information, please view the LICENSE file - * that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Maciej Dziardziel +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate libc; @@ -74,7 +72,8 @@ 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.chars().next().unwrap() == '-' && slice.len() > 1 + if slice.chars().next().unwrap() == '-' + && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { let val = &slice[1..]; @@ -85,7 +84,7 @@ fn handle_obsolete(mut args: Vec) -> (Vec, Option) { return (args, Some(val.to_owned())); } } - Err(_) => break, /* getopts will error out for us */ + Err(_) => break, // getopts will error out for us } } i += 1; @@ -95,7 +94,7 @@ fn handle_obsolete(mut args: Vec) -> (Vec, Option) { fn table() { let mut name_width = 0; - /* Compute the maximum width of a signal name. */ + // Compute the maximum width of a signal name. for s in &ALL_SIGNALS { if s.name.len() > name_width { name_width = s.name.len() @@ -104,7 +103,7 @@ fn table() { for (idx, signal) in ALL_SIGNALS.iter().enumerate() { print!("{0: >#2} {1: <#8}", idx + 1, signal.name); - //TODO: obtain max signal width here + // TODO: obtain max signal width here if (idx + 1) % 7 == 0 { println!(""); diff --git a/src/link/link.rs b/src/link/link.rs index 4ff654f4be8..315d90d9ef2 100644 --- a/src/link/link.rs +++ b/src/link/link.rs @@ -1,20 +1,18 @@ #![crate_name = "uu_link"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] 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 263c4de10af..c4eb3628986 100644 --- a/src/ln/ln.rs +++ b/src/ln/ln.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_ln"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Joseph Crail - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Joseph Crail +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[macro_use] extern crate uucore; @@ -67,24 +65,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/logname/logname.rs b/src/logname/logname.rs index f0551c021cf..5cc17061fa8 100644 --- a/src/logname/logname.rs +++ b/src/logname/logname.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_logname"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Benoit Benedetti - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/* last synced with: logname (GNU coreutils) 8.22 */ +// This file is part of the uutils coreutils package. +// +// (c) Benoit Benedetti +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +// last synced with: logname (GNU coreutils) 8.22 extern crate libc; diff --git a/src/ls/ls.rs b/src/ls/ls.rs index 658be8d2cb6..9ff159bb561 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}; @@ -25,20 +25,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; @@ -354,19 +353,17 @@ fn display_items(items: &Vec, strip: Option<&Path>, options: &getopts:: } } 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 { @@ -509,7 +506,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() @@ -593,9 +590,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 c3bc0107e3e..f235eae1ccd 100644 --- a/src/mkdir/mkdir.rs +++ b/src/mkdir/mkdir.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_mkdir"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Nicholas Juszczak - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Nicholas Juszczak +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; @@ -21,9 +19,7 @@ use std::path::Path; static NAME: &str = "mkdir"; static VERSION: &str = env!("CARGO_PKG_VERSION"); -/** - * Handles option parsing - */ +/// Handles option parsing pub fn uumain(args: Vec) -> i32 { let mut opts = getopts::Options::new(); @@ -84,9 +80,7 @@ fn print_help(opts: &getopts::Options) { ); } -/** - * Create the list of new directories - */ +/// Create the list of new directories fn exec(dirs: Vec, recursive: bool, mode: u16, verbose: bool) -> i32 { let mut status = 0; let empty = Path::new(""); @@ -109,11 +103,13 @@ fn exec(dirs: Vec, recursive: bool, mode: u16, verbose: bool) -> i32 { status } -/** - * Wrapper to catch errors, return 1 if failed - */ +/// 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; @@ -125,17 +121,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(mode as u32); if let Err(err) = set_permissions(path, mode) { - show_error!( - "{}: {}", - path.display(), - err - ); + show_error!("{}: {}", path.display(), err); return 1; } 0 @@ -143,7 +135,8 @@ fn mkdir(path: &Path, recursive: bool, mode: u16, verbose: bool) -> i32 { #[cfg(windows)] #[allow(unused_variables)] fn chmod(path: &Path, mode: u16) -> i32 { - // chmod on Windows only sets the readonly flag, which isn't even honored on directories + // chmod on Windows only sets the readonly flag, which isn't even honored on + // directories 0 } chmod(path, mode) diff --git a/src/mkfifo/mkfifo.rs b/src/mkfifo/mkfifo.rs index df101278715..3e35005e848 100644 --- a/src/mkfifo/mkfifo.rs +++ b/src/mkfifo/mkfifo.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_mkfifo"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; diff --git a/src/mknod/mknod.rs b/src/mknod/mknod.rs index 0efd7cc92e7..ce02d2c9903 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)] @@ -50,7 +49,8 @@ pub fn uumain(args: Vec) -> i32 { // Linux-specific options, not implemented // opts.optflag("Z", "", "set the SELinux security context to default type"); - // opts.optopt("", "context", "like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX"); + // opts.optopt("", "context", "like -Z, or if CTX is specified then set the + // SELinux or SMACK security context to CTX"); opts.optopt( "m", "mode", diff --git a/src/mktemp/mktemp.rs b/src/mktemp/mktemp.rs index 7c65d3e41a0..9711378bd41 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; @@ -55,9 +55,6 @@ pub fn uumain(args: Vec) -> i32 { slashes, but mktemp creates only the final component", "DIR", ); - // deprecated option of GNU coreutils - // opts.optflag("t", "", "Generate a template (using the supplied prefix and TMPDIR if set) \ - // to create a filename template"); opts.optflag("", "help", "Print this help and exit"); opts.optflag("", "version", "print the version and exit"); diff --git a/src/mktemp/tempdir.rs b/src/mktemp/tempdir.rs index b3f2e60e1a1..187ade2692d 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 3a121fada75..8f7e25e8c98 100644 --- a/src/more/more.rs +++ b/src/more/more.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_more"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Martin Kysel - * - * For the full copyright and license information, please view the LICENSE file - * that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Martin Kysel +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -15,8 +13,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 b6e6b6870a3..ea2c28e0151 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}; @@ -259,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 } @@ -271,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; } @@ -362,8 +365,7 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> { } if b.update { - if fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? - { + if fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? { return Ok(()); } } @@ -376,7 +378,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", + )); } } } @@ -431,7 +436,9 @@ fn is_empty_dir(path: &PathBuf) -> bool { match fs::read_dir(path) { Ok(contents) => { return contents.peekable().peek().is_none(); - }, - Err(_e) => { return false; } + } + Err(_e) => { + return false; + } } } diff --git a/src/nice/nice.rs b/src/nice/nice.rs index e76165a8e0e..11041db9335 100644 --- a/src/nice/nice.rs +++ b/src/nice/nice.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_nice"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; @@ -22,7 +20,8 @@ use std::io::Error; const NAME: &str = "nice"; const VERSION: &str = env!("CARGO_PKG_VERSION"); -// XXX: PRIO_PROCESS is 0 on at least FreeBSD and Linux. Don't know about Mac OS X. +// XXX: PRIO_PROCESS is 0 on at least FreeBSD and Linux. Don't know about Mac +// OS X. const PRIO_PROCESS: c_int = 0; extern "C" { diff --git a/src/nl/nl.rs b/src/nl/nl.rs index 6359b4b93a6..6d4b5331003 100644 --- a/src/nl/nl.rs +++ b/src/nl/nl.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_nl"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Tobias Bohumir Schottdorf - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - * - */ +// This file is part of the uutils coreutils package. +// +// (c) Tobias Bohumir Schottdorf +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. +// extern crate aho_corasick; extern crate getopts; diff --git a/src/nohup/nohup.rs b/src/nohup/nohup.rs index d9d7de6a376..01ddf7addad 100644 --- a/src/nohup/nohup.rs +++ b/src/nohup/nohup.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_nohup"] -/* - * This file is part of the uutils coreutils package. - * - * (c) 2014 Vsevolod Velichko - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) 2014 Vsevolod Velichko +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; @@ -15,14 +13,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 6a35520cd87..86dbd5efe53 100644 --- a/src/nproc/nproc.rs +++ b/src/nproc/nproc.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_nproc"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate num_cpus; @@ -108,7 +106,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 { @@ -125,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 3c34d4a19ae..109c95c024e 100644 --- a/src/numfmt/numfmt.rs +++ b/src/numfmt/numfmt.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_numfmt"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Yury Krivopalov - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Yury Krivopalov +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -19,7 +17,7 @@ static NAME: &str = "numfmt"; static VERSION: &str = env!("CARGO_PKG_VERSION"); const IEC_BASES: [f64; 10] = [ - //premature optimization + // premature optimization 1., 1024., 1048576., @@ -70,7 +68,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 33f6179100c..5d7ad4cabc0 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 cd4a0feecc6..6b473154acb 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 /// @@ -16,7 +16,8 @@ where /// A memory buffer, it's size is set in `new`. data: Vec, - /// The number of bytes in the buffer reserved for the peek data from `PeekRead`. + /// The number of bytes in the buffer reserved for the peek data from + /// `PeekRead`. reserved_peek_length: usize, /// The number of (valid) bytes in the buffer. @@ -29,8 +30,9 @@ where } impl<'a, I> InputDecoder<'a, I> { - /// Creates a new `InputDecoder` with an allocated buffer of `normal_length` + `peek_length` bytes. - /// `byte_order` determines how to read multibyte formats from the buffer. + /// Creates a new `InputDecoder` with an allocated buffer of `normal_length` + /// + `peek_length` bytes. `byte_order` determines how to read multibyte + /// formats from the buffer. pub fn new( input: &mut I, normal_length: usize, @@ -57,10 +59,12 @@ impl<'a, I> InputDecoder<'a, I> where I: PeekRead, { - /// 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. + /// 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)) => { @@ -109,12 +113,14 @@ impl<'a> MemoryDecoder<'a> { } } - /// Returns the current length of the buffer. (ie. how much valid data it contains.) + /// Returns the current length of the buffer. (ie. how much valid data it + /// contains.) pub fn length(&self) -> usize { self.used_normal_length } - /// Creates a clone of the internal buffer. The clone only contain the valid data. + /// Creates a clone of the internal buffer. The clone only contain the valid + /// data. pub fn clone_buffer(&self, other: &mut Vec) { other.clone_from(&self.data); other.resize(self.used_normal_length, 0); @@ -125,7 +131,8 @@ impl<'a> MemoryDecoder<'a> { &self.data[start..self.used_normal_length] } - /// Returns a slice to the internal buffer including the peek data starting at `start`. + /// Returns a slice to the internal buffer including the peek data starting + /// at `start`. pub fn get_full_buffer(&self, start: usize) -> &[u8] { &self.data[start..self.used_normal_length + self.used_peek_length] } @@ -157,9 +164,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/inputoffset.rs b/src/od/inputoffset.rs index 102f1656b84..ae380ea6e27 100644 --- a/src/od/inputoffset.rs +++ b/src/od/inputoffset.rs @@ -8,12 +8,15 @@ pub enum Radix { /// provides the byte offset printed at the left margin pub struct InputOffset { - /// The radix to print the byte offset. NoPrefix will not print a byte offset. + /// The radix to print the byte offset. NoPrefix will not print a byte + /// offset. radix: Radix, - /// The current position. Initialize at `new`, increase using `increase_position`. + /// The current position. Initialize at `new`, increase using + /// `increase_position`. byte_pos: usize, - /// An optional label printed in parentheses, typically different from `byte_pos`, - /// but will increase with the same value if `byte_pos` in increased. + /// An optional label printed in parentheses, typically different from + /// `byte_pos`, but will increase with the same value if `byte_pos` in + /// increased. label: Option, } diff --git a/src/od/mockstream.rs b/src/od/mockstream.rs index 3523caf5860..4c729232356 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 /// @@ -21,9 +21,11 @@ use std::error::Error as errorError; /// let mut buffer = [0; 5]; /// match r.read(&mut buffer) { /// Err(_) => { -/// if retries == 0 { break; } +/// if retries == 0 { +/// break; +/// } /// retries -= 1; -/// }, +/// } /// Ok(0) => break, /// Ok(n) => count += n, /// } @@ -35,8 +37,8 @@ use std::error::Error as errorError; /// #[test] /// fn test_io_retries() { /// let mut c = Cursor::new(&b"1234"[..]) -/// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3)) -/// .chain(Cursor::new(&b"5678"[..])); +/// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3)) +/// .chain(Cursor::new(&b"5678"[..])); /// /// let sut = CountIo {}; /// // this will fail unless read_data performs at least 3 retries on I/O errors @@ -53,8 +55,9 @@ pub struct FailingMockStream { impl FailingMockStream { /// Creates a FailingMockStream /// - /// When `read` or `write` is called, it will return an error `repeat_count` times. - /// `kind` and `message` can be specified to define the exact error. + /// When `read` or `write` is called, it will return an error `repeat_count` + /// times. `kind` and `message` can be specified to define the exact + /// error. pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream { FailingMockStream { kind: kind, diff --git a/src/od/multifilereader.rs b/src/od/multifilereader.rs index 20dfa1ae1be..143b849e9a1 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> { @@ -80,7 +80,8 @@ impl<'b> io::Read for MultifileReader<'b> { // Returns Ok() // Handles io errors itself, thus always returns OK // Fills the provided buffer completely, unless it has run out of input. - // If any call returns short (< buf.len()), all subsequent calls will return Ok<0> + // If any call returns short (< buf.len()), all subsequent calls will return + // Ok<0> fn read(&mut self, buf: &mut [u8]) -> io::Result { let mut xfrd = 0; // while buffer we are filling is not full.. May go thru several files. @@ -125,8 +126,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 03fd0d55ab4..5f7cb34f3d3 100644 --- a/src/od/od.rs +++ b/src/od/od.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_od"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Ben Hirsch - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Ben Hirsch +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate byteorder; extern crate getopts; @@ -16,36 +14,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 @@ -343,7 +341,8 @@ pub fn uumain(args: Vec) -> i32 { odfunc(&mut input_offset, &mut input_decoder, &output_info) } -/// Loops through the input line by line, calling print_bytes to take care of the output. +/// Loops through the input line by line, calling print_bytes to take care of +/// the output. fn odfunc( input_offset: &mut InputOffset, input_decoder: &mut InputDecoder, @@ -357,7 +356,8 @@ where let line_bytes = output_info.byte_size_line; loop { - // print each line data (or multi-format raster of several lines describing the same data). + // print each line data (or multi-format raster of several lines describing the + // same data). match input_decoder.peek_read() { Ok(mut memory_decoder) => { @@ -368,9 +368,11 @@ where break; } - // not enough byte for a whole element, this should only happen on the last line. + // not enough byte for a whole element, this should only happen on the last + // line. if length != line_bytes { - // set zero bytes in the part of the buffer that will be used, but is not filled. + // set zero bytes in the part of the buffer that will be used, but is not + // filled. let mut max_used = length + output_info.byte_size_block; if max_used > line_bytes { max_used = line_bytes; @@ -379,7 +381,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 { @@ -417,7 +420,8 @@ where } } -/// Outputs a single line of input, into one or more lines human readable output. +/// Outputs a single line of input, into one or more lines human readable +/// output. fn print_bytes(prefix: &str, input_decoder: &MemoryDecoder, output_info: &OutputInfo) { let mut first = true; // First line of a multi-format raster. for f in output_info.spaced_formatters_iter() { @@ -473,7 +477,8 @@ fn print_bytes(prefix: &str, input_decoder: &MemoryDecoder, output_info: &Output } } -/// returns a reader implementing `PeekRead + Read + HasError` providing the combined input +/// returns a reader implementing `PeekRead + Read + HasError` providing the +/// combined input /// /// `skip_bytes` is the number of bytes skipped from the input /// `read_bytes` is an optional limit to the number of bytes to read @@ -482,7 +487,8 @@ fn open_input_peek_reader<'a>( skip_bytes: usize, read_bytes: Option, ) -> PeekReader>> { - // should return "impl PeekRead + Read + HasError" when supported in (stable) rust + // should return "impl PeekRead + Read + HasError" when supported in (stable) + // rust let inputs = input_strings .iter() .map(|w| match w as &str { diff --git a/src/od/output_info.rs b/src/od/output_info.rs index 2ce6596d25b..116efe1b8f8 100644 --- a/src/od/output_info.rs +++ b/src/od/output_info.rs @@ -1,22 +1,25 @@ +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; /// Contains information to output single output line in human readable form pub struct SpacedFormatterItemInfo { - /// Contains a function pointer to output data, and information about the output format. + /// Contains a function pointer to output data, and information about the + /// output format. pub formatter_item_info: FormatterItemInfo, - /// Contains the number of spaces to add to align data with other output formats. + /// Contains the number of spaces to add to align data with other output + /// formats. /// - /// If the corresponding data is a single byte, each entry in this array contains - /// the number of spaces to insert when outputting each byte. If the corresponding - /// data is multi-byte, only the fist byte position is used. For example a 32-bit - /// datatype, could use positions 0, 4, 8, 12, .... - /// As each block is formatted identically, only the spacing for a single block is set. + /// If the corresponding data is a single byte, each entry in this array + /// contains the number of spaces to insert when outputting each byte. + /// If the corresponding data is multi-byte, only the fist byte position + /// is used. For example a 32-bit datatype, could use positions 0, 4, 8, + /// 12, .... As each block is formatted identically, only the spacing + /// for a single block is set. pub spacing: [usize; MAX_BYTES_PER_UNIT], /// if set adds a ascii dump at the end of the line pub add_ascii_dump: bool, @@ -29,9 +32,11 @@ pub struct OutputInfo { /// The width of a line in human readable format. pub print_width_line: usize, - /// The number of bytes in a block. (This is the size of the largest datatype in `spaced_formatters`.) + /// The number of bytes in a block. (This is the size of the largest + /// datatype in `spaced_formatters`.) pub byte_size_block: usize, - /// The width of a block in human readable format. (The size of the largest format.) + /// The width of a block in human readable format. (The size of the largest + /// format.) pub print_width_block: usize, /// All formats. spaced_formatters: Vec, @@ -94,49 +99,53 @@ impl OutputInfo { /// calculates proper alignment for a single line of output /// - /// Multiple representations of the same data, will be right-aligned for easy reading. - /// For example a 64 bit octal and a 32-bit decimal with a 16-bit hexadecimal looks like this: - /// ``` + /// Multiple representations of the same data, will be right-aligned for + /// easy reading. For example a 64 bit octal and a 32-bit decimal with a + /// 16-bit hexadecimal looks like this: ``` /// 1777777777777777777777 1777777777777777777777 /// 4294967295 4294967295 4294967295 4294967295 /// ffff ffff ffff ffff ffff ffff ffff ffff /// ``` - /// In this example is additional spacing before the first and third decimal number, - /// and there is additional spacing before the 1st, 3rd, 5th and 7th hexadecimal number. - /// This way both the octal and decimal, as well as the decimal and hexadecimal numbers - /// left align. Note that the alignment below both octal numbers is identical. + /// In this example is additional spacing before the first and third decimal + /// number, and there is additional spacing before the 1st, 3rd, 5th and + /// 7th hexadecimal number. This way both the octal and decimal, as well + /// as the decimal and hexadecimal numbers left align. Note that the + /// alignment below both octal numbers is identical. /// - /// This function calculates the required spacing for a single line, given the size - /// of a block, and the width of a block. The size of a block is the largest type - /// and the width is width of the the type which needs the most space to print that - /// number of bytes. So both numbers might refer to different types. All widths - /// include a space at the front. For example the width of a 8-bit hexadecimal, + /// This function calculates the required spacing for a single line, given + /// the size of a block, and the width of a block. The size of a block + /// is the largest type and the width is width of the the type which + /// needs the most space to print that number of bytes. So both numbers + /// might refer to different types. All widths include a space at the + /// front. For example the width of a 8-bit hexadecimal, /// is 3 characters, for example " FF". /// - /// This algorithm first calculates how many spaces needs to be added, based the - /// block size and the size of the type, and the widths of the block and the type. - /// The required spaces are spread across the available positions. - /// If the blocksize is 8, and the size of the type is 8 too, there will be just - /// one value in a block, so all spacing will be assigned to position 0. - /// If the blocksize is 8, and the size of the type is 2, the spacing will be - /// spread across position 0, 2, 4, 6. All 4 positions will get an additional - /// space as long as there are more then 4 spaces available. If there are 2 - /// spaces available, they will be assigned to position 0 and 4. If there is - /// 1 space available, it will be assigned to position 0. This will be combined, - /// For example 7 spaces will be assigned to position 0, 2, 4, 6 like: 3, 1, 2, 1. - /// And 7 spaces with 2 positions will be assigned to position 0 and 4 like 4, 3. + /// This algorithm first calculates how many spaces needs to be added, based + /// the block size and the size of the type, and the widths of the block + /// and the type. The required spaces are spread across the available + /// positions. If the blocksize is 8, and the size of the type is 8 too, + /// there will be just one value in a block, so all spacing will be + /// assigned to position 0. If the blocksize is 8, and the size of the + /// type is 2, the spacing will be spread across position 0, 2, 4, 6. + /// All 4 positions will get an additional space as long as there are + /// more then 4 spaces available. If there are 2 spaces available, they + /// will be assigned to position 0 and 4. If there is 1 space available, + /// it will be assigned to position 0. This will be combined, + /// For example 7 spaces will be assigned to position 0, 2, 4, 6 like: 3, 1, + /// 2, 1. And 7 spaces with 2 positions will be assigned to position 0 + /// and 4 like 4, 3. /// - /// Here is another example showing the alignment of 64-bit unsigned decimal numbers, - /// 32-bit hexadecimal number, 16-bit octal numbers and 8-bit hexadecimal numbers: - /// ``` + /// Here is another example showing the alignment of 64-bit unsigned decimal + /// numbers, 32-bit hexadecimal number, 16-bit octal numbers and 8-bit + /// hexadecimal numbers: ``` /// 18446744073709551615 18446744073709551615 /// ffffffff ffffffff ffffffff ffffffff /// 177777 177777 177777 177777 177777 177777 177777 177777 /// ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff /// ``` /// - /// This algorithm assumes the size of all types is a power of 2 (1, 2, 4, 8, 16, ...) - /// Increase MAX_BYTES_PER_UNIT to allow larger types. + /// This algorithm assumes the size of all types is a power of 2 (1, 2, 4, + /// 8, 16, ...) Increase MAX_BYTES_PER_UNIT to allow larger types. fn calculate_alignment( sf: &TypeSizeInfo, byte_size_block: usize, diff --git a/src/od/parse_formats.rs b/src/od/parse_formats.rs index f8c3659f000..e669f4b386e 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 { @@ -541,7 +541,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 63af6eba551..a5b07e4aca6 100644 --- a/src/od/parse_inputs.rs +++ b/src/od/parse_inputs.rs @@ -81,8 +81,9 @@ pub fn parse_inputs(matches: &CommandLineOpts) -> Result) -> Result { match input_strings.len() { 0 => Ok(CommandLineInputs::FileNames(vec!["-".to_string()])), @@ -166,8 +167,9 @@ mod tests { /// A mock for the commandline options type /// - /// `inputs` are all commandline parameters which do not belong to an option. - /// `option_names` are the names of the options on the commandline. + /// `inputs` are all commandline parameters which do not belong to an + /// option. `option_names` are the names of the options on the + /// commandline. struct MockOptions<'a> { inputs: Vec, option_names: Vec<&'a str>, @@ -292,7 +294,8 @@ mod tests { #[test] fn test_parse_inputs_traditional() { - // it should not return FileAndOffset to signal no offset was entered on the commandline. + // it should not return FileAndOffset to signal no offset was entered on the + // commandline. assert_eq!( CommandLineInputs::FileNames(vec!["-".to_string()]), parse_inputs(&MockOptions::new(vec![], vec!["traditional"])).unwrap() @@ -328,23 +331,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 42bca6428f0..5bffa72a0f0 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. @@ -77,9 +77,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 825335f20fd..f97367ff71e 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. @@ -10,7 +10,6 @@ use multifilereader::HasError; /// Like `std::io::Read`, it allows to read data from a stream, with /// the additional possibility to reserve a part of the returned data /// with the data which will be read in subsequent calls. -/// pub trait PeekRead { /// Reads data into a buffer. /// diff --git a/src/od/prn_char.rs b/src/od/prn_char.rs index 4caf068fa13..3f47e64e4cc 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 19ba3cca396..e1d2bf3de2a 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 cc47a16e79b..366ac90ee35 100644 --- a/src/od/prn_int.rs +++ b/src/od/prn_int.rs @@ -1,23 +1,35 @@ 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}" }} -/// format string to print decimal using `int_writer_unsigned` or `int_writer_signed` -macro_rules! DEC { () => { " {:width$}" }} +macro_rules! HEX { + () => { + " {:0width$x}" + }; +} +/// format string to print decimal using `int_writer_unsigned` or +/// `int_writer_signed` +macro_rules! DEC { + () => { + " {:width$}" + }; +} /// defines a static struct of type `FormatterItemInfo` called `$NAME` /// -/// Used to format unsigned integer types with help of a function called `$function` -/// `$byte_size` is the size of the type, `$print_width` is the maximum width in -/// human-readable format. `$format_str` is one of OCT, HEX or DEC +/// Used to format unsigned integer types with help of a function called +/// `$function` `$byte_size` is the size of the type, `$print_width` is the +/// maximum width in human-readable format. `$format_str` is one of OCT, HEX or +/// DEC 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,21 +37,19 @@ macro_rules! int_writer_unsigned { print_width: $print_width, formatter: FormatWriter::IntWriter($function), }; - } + }; } /// defines a static struct of type `FormatterItemInfo` called `$NAME` /// -/// Used to format signed integer types with help of a function called `$function` -/// `$byte_size` is the size of the type, `$print_width` is the maximum width in -/// human-readable format. `$format_str` should be DEC +/// Used to format signed integer types with help of a function called +/// `$function` `$byte_size` is the size of the type, `$print_width` is the +/// maximum width in human-readable format. `$format_str` should be DEC 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 +57,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 8ad29568b25..38a7588b6e2 100644 --- a/src/paste/paste.rs +++ b/src/paste/paste.rs @@ -1,22 +1,20 @@ #![crate_name = "uu_paste"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. 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"; diff --git a/src/pathchk/pathchk.rs b/src/pathchk/pathchk.rs index 8159c24c931..cb308d85760 100644 --- a/src/pathchk/pathchk.rs +++ b/src/pathchk/pathchk.rs @@ -1,14 +1,12 @@ #![allow(unused_must_use)] // because we of writeln! #![crate_name = "uu_pathchk"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Inokentiy Babushkin - * - * For the full copyright and license information, please view the LICENSE file - * that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Inokentiy Babushkin +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; @@ -234,12 +232,14 @@ fn check_searchable(path: &String) -> 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 0edf3e0f2a8..b3164f2866e 100644 --- a/src/pinky/pinky.rs +++ b/src/pinky/pinky.rs @@ -5,15 +5,14 @@ // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -// #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #[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; @@ -103,7 +102,7 @@ The utmp file will be {}", // if true, use the "short" output format. let do_short_format = !matches.opt_present("l"); - /* if true, display the ut_host field. */ + // if true, display the ut_host field. let mut include_where = true; if matches.opt_present("w") { diff --git a/src/printenv/printenv.rs b/src/printenv/printenv.rs index 56ca0a6530f..68e73136e62 100644 --- a/src/printenv/printenv.rs +++ b/src/printenv/printenv.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_printenv"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. -/* last synced with: printenv (GNU coreutils) 8.13 */ +// last synced with: printenv (GNU coreutils) 8.13 extern crate getopts; diff --git a/src/printf/cli.rs b/src/printf/cli.rs index e69cdf3c9f5..6a7dbee2ecd 100644 --- a/src/printf/cli.rs +++ b/src/printf/cli.rs @@ -1,8 +1,7 @@ //! stdio convenience fns +use std::env; #[allow(unused_must_use)] - use std::io::{stderr, stdout, Write}; -use std::env; 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 e5a05cf0ea6..7dc0502f3f9 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 0570b74896d..f6f12f501df 100644 --- a/src/printf/tokenize/mod.rs +++ b/src/printf/tokenize/mod.rs @@ -1,4 +1,4 @@ -pub mod token; +mod num_format; pub mod sub; +pub mod token; pub mod unescaped_text; -mod num_format; diff --git a/src/printf/tokenize/num_format/formatter.rs b/src/printf/tokenize/num_format/formatter.rs index aa5cf18a7f0..f770823de1c 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/mod.rs b/src/printf/tokenize/num_format/formatters/base_conv/mod.rs index 5e46a6c5147..062b8a62c64 100644 --- a/src/printf/tokenize/num_format/formatters/base_conv/mod.rs +++ b/src/printf/tokenize/num_format/formatters/base_conv/mod.rs @@ -247,7 +247,7 @@ pub fn str_to_arrnum(src: &str, radix_def_src: &RadixDef) -> Vec { Some(u) => { intermed_in.push(u); } - None => {} //todo err msg on incorrect + None => {} // todo err msg on incorrect } } intermed_in @@ -260,7 +260,7 @@ pub fn arrnum_to_str(src: &Vec, radix_def_dest: &RadixDef) -> String { Some(c) => { str_out.push(c); } - None => {} //todo + None => {} // todo } } str_out 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 b69dcdb653d..55e7fdfca9c 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 9d226818ce3..b8c43c6646d 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, @@ -38,9 +38,15 @@ impl Formatter for CninetyNineHexFloatf { } } -// c99 hex has unique requirements of all floating point subs in pretty much every part of building a primitive, from prefix and suffix to need for base conversion (in all other cases if you don't have decimal you must have decimal, here it's the other way around) +// c99 hex has unique requirements of all floating point subs in pretty much +// every part of building a primitive, from prefix and suffix to need for base +// conversion (in all other cases if you don't have decimal you must have +// decimal, here it's the other way around) -// on the todo list is to have a trait for get_primitive that is implemented by each float formatter and can override a default. when that happens we can take the parts of get_primitive_dec specific to dec and spin them out to their own functions that can be overridden. +// on the todo list is to have a trait for get_primitive that is implemented by +// each float formatter and can override a default. when that happens we can +// take the parts of get_primitive_dec specific to dec and spin them out to +// their own functions that can be overridden. #[allow(unused_variables)] #[allow(unused_assignments)] fn get_primitive_hex( diff --git a/src/printf/tokenize/num_format/formatters/float_common.rs b/src/printf/tokenize/num_format/formatters/float_common.rs index 0b4a54b30b0..76c48d7d329 100644 --- a/src/printf/tokenize/num_format/formatters/float_common.rs +++ b/src/printf/tokenize/num_format/formatters/float_common.rs @@ -25,7 +25,7 @@ fn has_enough_digits( if hex_input { ((string_position - 1) - starting_position >= limit) } else { - false //undecidable without converting + false // undecidable without converting } } else { if hex_input { @@ -74,7 +74,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); diff --git a/src/printf/tokenize/num_format/formatters/intf.rs b/src/printf/tokenize/num_format/formatters/intf.rs index 498df3fc2ed..49e9b63a056 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, @@ -136,16 +137,14 @@ impl Intf { // - a string that begins with a non-zero digit, and proceeds // with zero or more following digits until the end of the string // - a radix to interpret those digits as - // - a char that communicates: - // whether to interpret+output the string as an i64 or u64 - // what radix to write the parsed number as. + // - a char that communicates: whether to interpret+output the string as an i64 + // or u64 what radix to write the parsed number as. // 2. parses it as a rust integral type // 3. outputs FormatPrimitive with: - // - if the string falls within bounds: - // number parsed and written in the correct radix - // - if the string falls outside bounds: - // for i64 output, the int minimum or int max (depending on sign) - // for u64 output, the u64 max in the output radix + // - if the string falls within bounds: number parsed and written in the correct + // radix + // - if the string falls outside bounds: for i64 output, the int minimum or int + // max (depending on sign) for u64 output, the u64 max in the output radix fn conv_from_segment(segment: &str, radix_in: Base, fchar: char, sign: i8) -> FormatPrimitive { match fchar { 'i' | 'd' => match i64::from_str_radix(segment, radix_in as u32) { diff --git a/src/printf/tokenize/num_format/formatters/mod.rs b/src/printf/tokenize/num_format/formatters/mod.rs index 329e36d87f3..f6e2e7389cb 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 911fabb6a64..3ef7919fa32 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: &String) { // important: keep println here not print diff --git a/src/printf/tokenize/sub.rs b/src/printf/tokenize/sub.rs index 7e52757d417..e475be15619 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: &String) { @@ -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(); @@ -305,7 +293,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); diff --git a/src/printf/tokenize/token.rs b/src/printf/tokenize/token.rs index 378702682da..c2fc3cb4fc2 100644 --- a/src/printf/tokenize/token.rs +++ b/src/printf/tokenize/token.rs @@ -1,10 +1,9 @@ //! Traits and enums dealing with Tokenization of printf Format String +use itertools::PutBackN; #[allow(unused_must_use)] - use std::iter::Peekable; -use std::str::Chars; use std::slice::Iter; -use itertools::PutBackN; +use std::str::Chars; // A token object is an object that can print the expected output // of a contiguous segment of the format string, and diff --git a/src/printf/tokenize/unescaped_text.rs b/src/printf/tokenize/unescaped_text.rs index 3ea0038b1b6..2733c9ef1a0 100644 --- a/src/printf/tokenize/unescaped_text.rs +++ b/src/printf/tokenize/unescaped_text.rs @@ -3,14 +3,14 @@ //! and escaped character literals (of allowed escapes), //! into an unescaped text byte array +use super::token; +use cli; +use itertools::PutBackN; +use std::char::from_u32; use std::iter::Peekable; +use std::process::exit; use std::slice::Iter; use std::str::Chars; -use std::char::from_u32; -use std::process::exit; -use cli; -use itertools::PutBackN; -use super::token; pub struct UnescapedText(Vec); impl UnescapedText { @@ -48,7 +48,7 @@ impl UnescapedText { } if found < min_chars { // only ever expected for hex - println!("missing hexadecimal number in escape"); //todo stderr + println!("missing hexadecimal number in escape"); // todo stderr exit(cli::EXIT_ERR); } retval @@ -70,7 +70,7 @@ impl UnescapedText { preface, val, leading_zeros ); if (val < 159 && (val != 36 && val != 64 && val != 96)) || (val > 55296 && val < 57343) { - println!("{}", err_msg); //todo stderr + println!("{}", err_msg); // todo stderr exit(cli::EXIT_ERR); } } diff --git a/src/ptx/ptx.rs b/src/ptx/ptx.rs index cc30242d5fa..5cb07521539 100644 --- a/src/ptx/ptx.rs +++ b/src/ptx/ptx.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_ptx"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Dorota Kapturkiewicz - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Dorota Kapturkiewicz +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate aho_corasick; extern crate getopts; diff --git a/src/pwd/pwd.rs b/src/pwd/pwd.rs index e4658989dc4..56c2a8e711d 100644 --- a/src/pwd/pwd.rs +++ b/src/pwd/pwd.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_pwd"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Derek Chiang - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Derek Chiang +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -15,8 +13,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 +28,8 @@ pub fn absolute_path(path: &Path) -> io::Result { .as_path() .to_string_lossy() .trim_left_matches(r"\\?\"), - ).to_path_buf(); + ) + .to_path_buf(); Ok(path_buf) } diff --git a/src/readlink/readlink.rs b/src/readlink/readlink.rs index b4971e27fe0..6e0cfdf6434 100644 --- a/src/readlink/readlink.rs +++ b/src/readlink/readlink.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_readlink"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Haitao Li - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Haitao Li +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/realpath/realpath.rs b/src/realpath/realpath.rs index 80e6052daef..3ba2270cbc7 100644 --- a/src/realpath/realpath.rs +++ b/src/realpath/realpath.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_realpath"] -/* - * This file is part of the uutils coreutils package. - * - * (c) 2014 Vsevolod Velichko - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) 2014 Vsevolod Velichko +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/relpath/relpath.rs b/src/relpath/relpath.rs index 8e0bb401217..9c32646ddf8 100644 --- a/src/relpath/relpath.rs +++ b/src/relpath/relpath.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_relpath"] -/* - * This file is part of the uutils coreutils package. - * - * (c) 2014 Vsevolod Velichko - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) 2014 Vsevolod Velichko +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/rm/rm.rs b/src/rm/rm.rs index 8c2fc08ba18..042996591f2 100644 --- a/src/rm/rm.rs +++ b/src/rm/rm.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_rm"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate remove_dir_all; @@ -16,12 +14,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)] @@ -153,7 +151,8 @@ pub fn uumain(args: Vec) -> i32 { 0 } -// TODO: implement one-file-system (this may get partially implemented in walkdir) +// TODO: implement one-file-system (this may get partially implemented in +// walkdir) fn remove(files: Vec, options: Options) -> bool { let mut had_err = false; @@ -181,7 +180,8 @@ fn remove(files: Vec, options: Options) -> bool { false } } - }.bitor(had_err); + } + .bitor(had_err); } had_err @@ -193,8 +193,8 @@ fn handle_dir(path: &Path, options: &Options) -> bool { let is_root = path.has_root() && path.parent().is_none(); if options.recursive && (!is_root || !options.preserve_root) { if options.interactive != InteractiveMode::InteractiveAlways { - // we need the extra crate because apparently fs::remove_dir_all() does not function - // correctly on Windows + // we need the extra crate because apparently fs::remove_dir_all() does not + // function correctly on Windows if let Err(e) = remove_dir_all(path) { had_err = true; show_error!("could not remove '{}': {}", path.display(), e); @@ -249,9 +249,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; @@ -270,9 +272,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; @@ -322,5 +326,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/rmdir/rmdir.rs b/src/rmdir/rmdir.rs index 2ef50e5bdc1..e1ca2db8eb7 100644 --- a/src/rmdir/rmdir.rs +++ b/src/rmdir/rmdir.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_rmdir"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/shred/shred.rs b/src/shred/shred.rs index 65005b91606..f53f4ae1631 100644 --- a/src/shred/shred.rs +++ b/src/shred/shred.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_shred"] -/* -* This file is part of the uutils coreutils package. -* -* (c) Michael Rosenberg <42micro@gmail.com> -* (c) Fort -* -* For the full copyright and license information, please view the LICENSE -* file that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) Michael Rosenberg <42micro@gmail.com> +// (c) Fort +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate rand; @@ -18,8 +16,8 @@ use std::cell::{Cell, RefCell}; use std::fs; use std::fs::{File, OpenOptions}; use std::io; -use std::io::SeekFrom; use std::io::prelude::*; +use std::io::SeekFrom; use std::path::{Path, PathBuf}; #[macro_use] @@ -62,10 +60,12 @@ enum PassType<'a> { Random, } -// Used to generate all possible filenames of a certain length using NAMESET as an alphabet +// Used to generate all possible filenames of a certain length using NAMESET as +// an alphabet struct FilenameGenerator { name_len: usize, - nameset_indices: RefCell>, // Store the indices of the letters of our filename in NAMESET + // Store the indices of the letters of our filename in NAMESET + nameset_indices: RefCell>, exhausted: Cell, } @@ -118,8 +118,8 @@ impl Iterator for FilenameGenerator { } } -// Used to generate blocks of bytes of size <= BLOCK_SIZE based on either a give pattern -// or randomness +// Used to generate blocks of bytes of size <= BLOCK_SIZE based on either a give +// pattern or randomness struct BytesGenerator<'a> { total_bytes: u64, bytes_generated: Cell, @@ -151,8 +151,8 @@ impl<'a> Iterator for BytesGenerator<'a> { type Item = Box<[u8]>; fn next(&mut self) -> Option> { - // We go over the total_bytes limit when !self.exact and total_bytes isn't a multiple - // of self.block_size + // We go over the total_bytes limit when !self.exact and total_bytes + // isn't a multiple of self.block_size if self.bytes_generated.get() >= self.total_bytes { return None; } @@ -190,7 +190,8 @@ impl<'a> Iterator for BytesGenerator<'a> { (pattern.len() as u64 % self.bytes_generated.get()) as usize } }; - // Same range as 0..this_block_size but we start with the right index + // Same range as 0..this_block_size but we start with the right + // index for i in skip..this_block_size + skip { let index = i % pattern.len(); bytes.push(pattern[index]); @@ -269,7 +270,8 @@ pub fn uumain(args: Vec) -> i32 { }; let remove = matches.opt_present("remove"); let size = get_size(matches.opt_str("size")); - let exact = matches.opt_present("exact") && size.is_none(); // if -s is given, ignore -x + // if -s is given, ignore -x + let exact = matches.opt_present("exact") && size.is_none(); let zero = matches.opt_present("zero"); let verbose = matches.opt_present("verbose"); for path_str in matches.free.into_iter() { @@ -418,27 +420,34 @@ fn wipe_file( } // First fill it with Patterns, shuffle it, then evenly distribute Random else { - let n_full_arrays = n_passes / PATTERNS.len(); // How many times can we go through all the patterns? - let remainder = n_passes % PATTERNS.len(); // How many do we get through on our last time through? + // How many times can we go through all the patterns? + let n_full_arrays = n_passes / PATTERNS.len(); + // How many do we get through on our last time through? + let remainder = n_passes % PATTERNS.len(); for _ in 0..n_full_arrays { for p in &PATTERNS { pass_sequence.push(PassType::Pattern(*p)); } } + for i in 0..remainder { pass_sequence.push(PassType::Pattern(PATTERNS[i])); } - rand::thread_rng().shuffle(&mut pass_sequence[..]); // randomize the order of application - let n_random = 3 + n_passes / 10; // Minimum 3 random passes; ratio of 10 after - // Evenly space random passes; ensures one at the beginning and end + // randomize the order of application + rand::thread_rng().shuffle(&mut pass_sequence[..]); + + // Minimum 3 random passes; ratio of 10 after + // Evenly space random passes; ensures one at the beginning and end + let n_random = 3 + n_passes / 10; for i in 0..n_random { pass_sequence[i * (n_passes - 1) / (n_random - 1)] = PassType::Random; } } - // --zero specifies whether we want one final pass of 0x00 on our file + // The `--zero` flag specifies whether we want one final pass of 0x00 on our + // file if zero { pass_sequence.push(PassType::Pattern(b"\x00")); } @@ -474,8 +483,10 @@ fn wipe_file( ); } } - // size is an optional argument for exactly how many bytes we want to shred - do_pass(&mut file, path, *pass_type, size, exact).expect("File write pass failed"); // Ignore failed writes; just keep trying + // Size is an optional argument for exactly how many bytes we want + // to shred + do_pass(&mut file, path, *pass_type, size, exact).expect("File write pass failed"); + // Ignore failed writes; just keep trying... } } @@ -513,8 +524,8 @@ fn get_file_size(path: &Path) -> Result { Ok(size) } -// Repeatedly renames the file with strings of decreasing length (most likely all 0s) -// Return the path of the file after its last renaming or None if error +// Repeatedly renames the file with strings of decreasing length (most likely +// all 0s) Return the path of the file after its last renaming or None if error fn wipe_name(orig_path: &Path, verbose: bool) -> Option { let file_name_len: usize = orig_path.file_name().unwrap().to_str().unwrap().len(); @@ -560,7 +571,9 @@ fn wipe_name(orig_path: &Path, verbose: bool) -> Option { return None; } } - } // If every possible filename already exists, just reduce the length and try again + // If every possible filename already exists, just reduce the length + // and try again... + } } Some(last_path) diff --git a/src/shuf/shuf.rs b/src/shuf/shuf.rs index 6f5e0ee286c..4367afd0c29 100644 --- a/src/shuf/shuf.rs +++ b/src/shuf/shuf.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_shuf"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate rand; @@ -170,8 +168,8 @@ fn find_seps(data: &mut Vec<&[u8]>, sep: u8) { // * We don't care about the order of the result. This lets us slice the slices // without making a new vector. // * Starting from the end of the vector, we examine each element. - // * If that element contains the separator, we remove it from the vector, - // and then sub-slice it into slices that do not contain the separator. + // * If that element contains the separator, we remove it from the vector, and + // then sub-slice it into slices that do not contain the separator. // * We maintain the invariant throughout that each element in the vector past // the ith element does not have any separators remaining. for i in (0..data.len()).rev() { @@ -221,7 +219,8 @@ fn shuf_bytes( None => WrappedRng::RngDefault(rand::thread_rng()), }; - // we're generating a random usize. To keep things fair, we take this number mod ceil(log2(length+1)) + // we're generating a random usize. To keep things fair, we take this number mod + // ceil(log2(length+1)) let mut len_mod = 1; let mut len = input.len(); while len > 0 { diff --git a/src/sleep/sleep.rs b/src/sleep/sleep.rs index f27c42be5a4..d9752cbb3f9 100644 --- a/src/sleep/sleep.rs +++ b/src/sleep/sleep.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_sleep"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -63,12 +61,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 c21802d49e2..0c58c4ac2b0 100644 --- a/src/sort/sort.rs +++ b/src/sort/sort.rs @@ -1,12 +1,10 @@ #![crate_name = "uu_sort"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Yin - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Yin +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #![allow(dead_code)] extern crate getopts; @@ -16,15 +14,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"); @@ -243,7 +241,7 @@ With no FILE, or when FILE is -, read standard input.", let mut files = matches.free; if files.is_empty() { - /* if no file, default to stdin */ + // if no file, default to stdin files.push("-".to_owned()); } else if settings.check && files.len() != 1 { crash!(1, "sort: extra operand `{}' not allowed with -c", files[1]) @@ -376,22 +374,21 @@ fn compare_by(a: &String, b: &String, settings: &Settings) -> Ordering { return Ordering::Equal; } -/// Parse the beginning string into an f64, returning -inf instead of NaN on errors. +/// Parse the beginning string into an f64, returning -inf instead of NaN on +/// errors. fn permissive_f64_parse(a: &str) -> f64 { // Maybe should be split on non-digit, but then 10e100 won't parse properly. // On the flip side, this will give NEG_INFINITY for "1,234", which might be OK - // because there's no way to handle both CSV and thousands separators without a new flag. - // GNU sort treats "1,234" as "1" in numeric, so maybe it's fine. + // because there's no way to handle both CSV and thousands separators without a + // new flag. GNU sort treats "1,234" as "1" in numeric, so maybe it's fine. // 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, + }, } } @@ -465,7 +462,8 @@ enum Month { /// Parse the beginning string into a Month, returning Month::Unknown on errors. fn month_parse(line: &String) -> 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 e32467bb25e..52a66bf46ea 100644 --- a/src/split/split.rs +++ b/src/split/split.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_split"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Akira Hayakawa - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Akira Hayakawa +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -320,7 +318,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 b76451740e5..89f038bfdd7 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 { @@ -135,22 +137,44 @@ pub fn pretty_access(mode: mode_t) -> String { result } -use std::mem::{self, transmute}; -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::{self, transmute}; +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 { diff --git a/src/stat/stat.rs b/src/stat/stat.rs index 7b65c7a24ec..e1d23e60188 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: &'static str = "stat"; @@ -212,32 +214,38 @@ pub struct Stater { fn print_it(arg: &str, otype: OutputType, flag: u8, width: usize, precision: i32) { // If the precision is given as just '.', the precision is taken to be zero. // A negative precision is taken as if the precision were omitted. - // This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, - // the maximum number of characters to be printed from a string for s and S conversions. + // This gives the minimum number of digits to appear for d, i, o, u, x, and X + // conversions, the maximum number of characters to be printed from a string + // for s and S conversions. // # // The value should be converted to an "alternate form". - // For o conversions, the first character of the output string is made zero (by prefixing a 0 if it was not zero already). - // For x and X conversions, a nonzero result has the string "0x" (or "0X" for X conversions) prepended to it. + // For o conversions, the first character of the output string is made zero + // (by prefixing a 0 if it was not zero already). For x and X conversions, + // a nonzero result has the string "0x" (or "0X" for X conversions) prepended to + // it. // 0 // The value should be zero padded. - // For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. - // If the 0 and - flags both appear, the 0 flag is ignored. - // If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. + // For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted + // value is padded on the left with zeros rather than blanks. If the 0 and - + // flags both appear, the 0 flag is ignored. If a precision is given with + // a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. // For other conversions, the behavior is undefined. // - - // The converted value is to be left adjusted on the field boundary. (The default is right justification.) - // The converted value is padded on the right with blanks, rather than on the left with blanks or zeros. + // The converted value is to be left adjusted on the field boundary. (The + // default is right justification.) The converted value is padded on the + // right with blanks, rather than on the left with blanks or zeros. // A - overrides a 0 if both are given. // ' ' (a space) - // A blank should be left before a positive number (or empty string) produced by a signed conversion. + // A blank should be left before a positive number (or empty string) produced by + // a signed conversion. // + - // A sign (+ or -) should always be placed before a number produced by a signed conversion. - // By default, a sign is used only for negative numbers. + // A sign (+ or -) should always be placed before a number produced by a signed + // conversion. By default, a sign is used only for negative numbers. // A + overrides a space if both are used. if otype == OutputType::Unknown { diff --git a/src/stdbuf/libstdbuf/libstdbuf.rs b/src/stdbuf/libstdbuf/libstdbuf.rs index 1e290d00574..5b2f412448d 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 1b58ad5a245..4a1afdcdb49 100644 --- a/src/stdbuf/stdbuf.rs +++ b/src/stdbuf/stdbuf.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_stdbuf"] -/* -* This file is part of the uutils coreutils package. -* -* (c) Dorota Kapturkiewicz -* -* For the full copyright and license information, please view the LICENSE -* file that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) Dorota Kapturkiewicz +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate tempdir; @@ -16,12 +14,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 +49,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 +64,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/sum/sum.rs b/src/sum/sum.rs index 3f506ab4029..e004eef15d9 100644 --- a/src/sum/sum.rs +++ b/src/sum/sum.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_sum"] -/* -* This file is part of the uutils coreutils package. -* -* (c) T. Jameson Little -* -* For the full copyright and license information, please view the LICENSE file -* that was distributed with this source code. -*/ +// This file is part of the uutils coreutils package. +// +// (c) T. Jameson Little +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/sync/sync.rs b/src/sync/sync.rs index c9608e519b4..e22771ab634 100644 --- a/src/sync/sync.rs +++ b/src/sync/sync.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_sync"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alexander Fomin - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alexander Fomin +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. -/* Last synced with: sync (GNU coreutils) 8.13 */ +// Last synced with: sync (GNU coreutils) 8.13 extern crate getopts; extern crate libc; @@ -42,27 +40,29 @@ mod platform { mod platform { extern crate kernel32; extern crate winapi; - use std::mem; + 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 std::fs::OpenOptions; + use std::mem; use std::os::windows::prelude::*; use uucore::wide::{FromWide, ToWide}; - 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; 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/tac/tac.rs b/src/tac/tac.rs index bc14d926b47..b94c18321c6 100644 --- a/src/tac/tac.rs +++ b/src/tac/tac.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_tac"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/tail/platform/mod.rs b/src/tail/platform/mod.rs index 010c5c4ac1e..14d590aa59e 100644 --- a/src/tail/platform/mod.rs +++ b/src/tail/platform/mod.rs @@ -1,11 +1,9 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Alexander Batischev - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alexander Batischev +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[cfg(unix)] pub use self::unix::{supports_pid_checks, Pid, ProcessChecker}; diff --git a/src/tail/platform/redox.rs b/src/tail/platform/redox.rs index c0d43cb1cd9..a3a8c5fa039 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/unix.rs b/src/tail/platform/unix.rs index 7f64207f407..fb5397d558f 100644 --- a/src/tail/platform/unix.rs +++ b/src/tail/platform/unix.rs @@ -1,11 +1,9 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Alexander Batischev - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alexander Batischev +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate libc; diff --git a/src/tail/platform/windows.rs b/src/tail/platform/windows.rs index ebab7d32bed..ab93f42a9f1 100644 --- a/src/tail/platform/windows.rs +++ b/src/tail/platform/windows.rs @@ -1,18 +1,16 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Alexander Batischev - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alexander Batischev +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate kernel32; 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 c6bbbfdf22c..fecbd2de043 100755 --- a/src/tail/tail.rs +++ b/src/tail/tail.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_tail"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Morten Olsen Lysgaard - * (c) Alexander Batischev - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - * - */ +// This file is part of the uutils coreutils package. +// +// (c) Morten Olsen Lysgaard +// (c) Alexander Batischev +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. +// extern crate getopts; extern crate libc; diff --git a/src/tee/tee.rs b/src/tee/tee.rs index dfc72ef74b5..2846b03c824 100644 --- a/src/tee/tee.rs +++ b/src/tee/tee.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_tee"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Aleksander Bielawski - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Aleksander Bielawski +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; diff --git a/src/test/test.rs b/src/test/test.rs index 907b4488810..142d09ad192 100644 --- a/src/test/test.rs +++ b/src/test/test.rs @@ -1,21 +1,19 @@ #![crate_name = "uu_test"] -/* - * This file is part of the uutils coreutils package. - * - * (c) mahkoh (ju.orth [at] gmail [dot] com) - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) mahkoh (ju.orth [at] gmail [dot] com) +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate libc; #[cfg(target_os = "redox")] 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 +23,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 +148,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 +343,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,15 +363,17 @@ 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 } else if gid == metadata.gid() { metadata.mode() & ((p as u32) << 3) != 0 } else { - metadata.mode() & ((p as u32)) != 0 + metadata.mode() & (p as u32) != 0 } }; @@ -382,7 +385,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/timeout/timeout.rs b/src/timeout/timeout.rs index cd896595526..c5f57f65b06 100644 --- a/src/timeout/timeout.rs +++ b/src/timeout/timeout.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_timeout"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate libc; diff --git a/src/touch/touch.rs b/src/touch/touch.rs index ed75a767651..2b7cb2c27a4 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; diff --git a/src/tr/expand.rs b/src/tr/expand.rs index d9d38688ab5..f3857269e53 100644 --- a/src/tr/expand.rs +++ b/src/tr/expand.rs @@ -1,13 +1,11 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * (c) kwantam - * 20150428 created `expand` module to eliminate most allocs during setup - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// (c) kwantam +// 20150428 created `expand` module to eliminate most allocs during setup +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. use std::char::from_u32; use std::cmp::min; @@ -88,10 +86,13 @@ 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 diff --git a/src/tr/tr.rs b/src/tr/tr.rs index 1fe08d4545e..0b42f263a4f 100644 --- a/src/tr/tr.rs +++ b/src/tr/tr.rs @@ -1,16 +1,14 @@ #![crate_name = "uu_tr"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * (c) kwantam - * 20150428 created `expand` module to eliminate most allocs during setup - * (c) Sergey "Shnatsel" Davidoff - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// (c) kwantam +// 20150428 created `expand` module to eliminate most allocs during setup +// (c) Sergey "Shnatsel" Davidoff +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate bit_set; extern crate fnv; @@ -20,9 +18,9 @@ extern crate getopts; extern crate uucore; use bit_set::BitSet; +use fnv::FnvHashMap; use getopts::Options; use std::io::{stdin, stdout, BufRead, BufWriter, Write}; -use fnv::FnvHashMap; use expand::ExpandSet; diff --git a/src/true/true.rs b/src/true/true.rs index d1d3d70b9cb..2c12a3a5e61 100644 --- a/src/true/true.rs +++ b/src/true/true.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_true"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. pub fn uumain(_: Vec) -> i32 { 0 diff --git a/src/truncate/truncate.rs b/src/truncate/truncate.rs index 47070d9a7bf..77a012001aa 100644 --- a/src/truncate/truncate.rs +++ b/src/truncate/truncate.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_truncate"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Alex Lyon - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Alex Lyon +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -149,16 +147,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, }; @@ -181,7 +183,7 @@ fn parse_size(size: &str) -> (u64, TruncateMode) { '>' => TruncateMode::AtLeast, '/' => TruncateMode::RoundDown, '*' => TruncateMode::RoundUp, - _ => TruncateMode::Reference, /* assume that the size is just a number */ + _ => TruncateMode::Reference, // assume that the size is just a number }; let bytes = { let mut slice = if mode == TruncateMode::Reference { @@ -196,14 +198,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 f930e620d50..d74b6e8a28d 100644 --- a/src/tsort/tsort.rs +++ b/src/tsort/tsort.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_tsort"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Ben Eggers - * (c) Akira Hayakawa - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Ben Eggers +// (c) Akira Hayakawa +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -79,7 +77,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/tty/tty.rs b/src/tty/tty.rs index eaff78c964b..f87cd0404a4 100644 --- a/src/tty/tty.rs +++ b/src/tty/tty.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_tty"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - * - * Synced with http://lingrok.org/xref/coreutils/src/tty.c - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. +// +// Synced with http://lingrok.org/xref/coreutils/src/tty.c extern crate getopts; extern crate libc; diff --git a/src/uname/uname.rs b/src/uname/uname.rs index 7adc1b4e985..26b90efa489 100644 --- a/src/uname/uname.rs +++ b/src/uname/uname.rs @@ -29,9 +29,9 @@ const OPT_KERNELVERSION: &str = "kernel-version"; const OPT_KERNELRELEASE: &str = "kernel-release"; const OPT_MACHINE: &str = "machine"; -//FIXME: unimplemented options -//const OPT_PROCESSOR: &'static str = "processor"; -//const OPT_HWPLATFORM: &'static str = "hardware-platform"; +// FIXME: unimplemented options +// const OPT_PROCESSOR: &'static str = "processor"; +// const OPT_HWPLATFORM: &'static str = "hardware-platform"; const OPT_OS: &str = "operating-system"; #[cfg(target_os = "linux")] diff --git a/src/unexpand/unexpand.rs b/src/unexpand/unexpand.rs index 5df0dfda064..8e5d82486b5 100644 --- a/src/unexpand/unexpand.rs +++ b/src/unexpand/unexpand.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_unexpand"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Virgile Andreani - * (c) kwantam - * 20150428 updated to work with both UTF-8 and non-UTF-8 encodings - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Virgile Andreani +// (c) kwantam +// 20150428 updated to work with both UTF-8 and non-UTF-8 encodings +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; extern crate unicode_width; @@ -42,7 +40,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/uniq/uniq.rs b/src/uniq/uniq.rs index f82704b8b05..1474d1c2b36 100644 --- a/src/uniq/uniq.rs +++ b/src/uniq/uniq.rs @@ -1,14 +1,12 @@ #![crate_name = "uu_uniq"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Chirag B Jadwani - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - * - */ +// This file is part of the uutils coreutils package. +// +// (c) Chirag B Jadwani +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. +// extern crate getopts; @@ -118,7 +116,8 @@ impl Uniq { let slice_start = self.slice_start.unwrap_or(0); let slice_stop = self.slice_stop.unwrap_or(len); if len > 0 { - // fast path: avoid doing any work if there is no need to skip or map to lower-case + // fast path: avoid doing any work if there is no need to skip or map to + // lower-case if !self.ignore_case && slice_start == 0 && slice_stop == len { return closure(&mut fields_to_check.chars()); } @@ -131,7 +130,8 @@ impl Uniq { })); } - // fast path: we can avoid mapping chars to upper-case, if we don't want to ignore the case + // fast path: we can avoid mapping chars to upper-case, if we don't want to + // ignore the case if !self.ignore_case { return closure(&mut fields_to_check.chars().skip(slice_start).take(slice_stop)); } diff --git a/src/unlink/unlink.rs b/src/unlink/unlink.rs index 9bca5e585bf..f77bb023306 100644 --- a/src/unlink/unlink.rs +++ b/src/unlink/unlink.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_unlink"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Colin Warren - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Colin Warren +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. -/* last synced with: unlink (GNU coreutils) 8.21 */ +// last synced with: unlink (GNU coreutils) 8.21 extern crate getopts; extern crate libc; @@ -18,11 +16,11 @@ extern crate libc; extern crate uucore; use getopts::Options; -use libc::{S_IFLNK, S_IFMT, S_IFREG}; use libc::{lstat, stat, unlink}; +use libc::{S_IFLNK, S_IFMT, S_IFREG}; +use std::ffi::CString; use std::io::{Error, ErrorKind}; use std::mem::uninitialized; -use std::ffi::CString; static NAME: &str = "unlink"; static VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -72,12 +70,7 @@ pub fn uumain(args: Vec) -> i32 { let st_mode = { let mut buf: stat = unsafe { 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 8d9d48ab44b..65dfe53fd94 100644 --- a/src/uptime/uptime.rs +++ b/src/uptime/uptime.rs @@ -1,16 +1,14 @@ #![crate_name = "uu_uptime"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * (c) Jian Zeng - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/* last synced with: cat (GNU coreutils) 8.13 */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// (c) Jian Zeng +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +// last synced with: cat (GNU coreutils) 8.13 extern crate getopts; extern crate time; @@ -18,8 +16,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; @@ -106,8 +104,8 @@ fn print_loadavg() { #[cfg(windows)] fn print_loadavg() { - // XXX: currently this is a noop as Windows does not seem to have anything comparable to - // getloadavg() + // XXX: currently this is a noop as Windows does not seem to have anything + // comparable to getloadavg() } #[cfg(unix)] diff --git a/src/users/users.rs b/src/users/users.rs index 10fb5eca5ca..e601c243ca0 100644 --- a/src/users/users.rs +++ b/src/users/users.rs @@ -1,16 +1,14 @@ #![crate_name = "uu_users"] -/* - * This file is part of the uutils coreutils package. - * - * (c) KokaKiwi - * (c) Jian Zeng - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/* last synced with: whoami (GNU coreutils) 8.22 */ - +// This file is part of the uutils coreutils package. +// +// (c) KokaKiwi +// (c) Jian Zeng +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. +// / +// +// 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 a2481bcf73e..a93f49b6b7e 100644 --- a/src/uutils/uutils.rs +++ b/src/uutils/uutils.rs @@ -1,19 +1,18 @@ #![crate_name = "uutils"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Michael Gehring - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Michael Gehring +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. include!(concat!(env!("OUT_DIR"), "/uutils_crates.rs")); use std::collections::hash_map::HashMap; -use std::path::Path; +use std::env; use std::io::Write; +use std::path::Path; extern crate uucore; @@ -50,8 +49,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 db1ee0ebd4d..d5b305e73fa 100644 --- a/src/wc/wc.rs +++ b/src/wc/wc.rs @@ -1,13 +1,11 @@ #![crate_name = "uu_wc"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Boden Garman - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Boden Garman +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. extern crate getopts; @@ -40,7 +38,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; @@ -153,8 +154,8 @@ fn wc(files: Vec, settings: &Settings) -> StdResult<(), i32> { let mut longest_line_length: usize = 0; let mut raw_line = Vec::new(); - // reading from a TTY seems to raise a condition on, rather than return Some(0) like a file. - // hence the option wrapped in a result here + // reading from a TTY seems to raise a condition on, rather than return Some(0) + // like a file. hence the option wrapped in a result here while match reader.read_until(LF, &mut raw_line) { Ok(n) if n > 0 => true, Err(ref e) if !raw_line.is_empty() => { diff --git a/src/who/who.rs b/src/who/who.rs index 99f0cb9a016..6aa8ba7edb4 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"); @@ -263,7 +268,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() @@ -296,7 +302,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; } @@ -528,14 +539,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/mod.rs b/src/whoami/platform/mod.rs index 12d85ec08b8..b0fd4eec145 100644 --- a/src/whoami/platform/mod.rs +++ b/src/whoami/platform/mod.rs @@ -1,11 +1,9 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. #[cfg(unix)] pub use self::unix::getusername; diff --git a/src/whoami/platform/unix.rs b/src/whoami/platform/unix.rs index ab7c42ff639..4472d45e118 100644 --- a/src/whoami/platform/unix.rs +++ b/src/whoami/platform/unix.rs @@ -1,16 +1,14 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * (c) Jian Zeng - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// (c) Jian Zeng +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. 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 b321b93befa..a88bda5bda0 100644 --- a/src/whoami/platform/windows.rs +++ b/src/whoami/platform/windows.rs @@ -1,22 +1,20 @@ -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. 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 { let mut buffer: [winnt::WCHAR; lmcons::UNLEN as usize + 1] = mem::uninitialized(); diff --git a/src/whoami/whoami.rs b/src/whoami/whoami.rs index 886126cbf2b..8bf304bca09 100644 --- a/src/whoami/whoami.rs +++ b/src/whoami/whoami.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_whoami"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/* last synced with: whoami (GNU coreutils) 8.21 */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +// last synced with: whoami (GNU coreutils) 8.21 #[macro_use] extern crate clap; diff --git a/src/yes/yes.rs b/src/yes/yes.rs index b8e7971fd13..b82b273d478 100644 --- a/src/yes/yes.rs +++ b/src/yes/yes.rs @@ -1,15 +1,13 @@ #![crate_name = "uu_yes"] -/* - * This file is part of the uutils coreutils package. - * - * (c) Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ +// This file is part of the uutils coreutils package. +// +// (c) Jordi Boggiano +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. -/* last synced with: yes (GNU coreutils) 8.13 */ +// last synced with: yes (GNU coreutils) 8.13 #[macro_use] extern crate clap; @@ -17,15 +15,15 @@ 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"); -// it's possible that using a smaller or larger buffer might provide better performance on some -// systems, but honestly this is good enough +// it's possible that using a smaller or larger buffer might provide better +// performance on some systems, but honestly this is good enough const BUF_SIZE: usize = 16 * 1024; pub fn uumain(args: Vec) -> i32 { diff --git a/tests/common/macros.rs b/tests/common/macros.rs index e36fdffdc5b..645cfcc67be 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 43e83f1e64e..f56f89ab13a 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"; @@ -45,9 +45,10 @@ pub fn repeat_str(s: &str, n: u32) -> String { } /// A command result is the outputs of a command (streams and status code) -/// within a struct which has convenience assertion functions about those outputs +/// within a struct which has convenience assertion functions about those +/// outputs pub struct CmdResult { - //tmpd is used for convenience functions for asserts against fixtures + // tmpd is used for convenience functions for asserts against fixtures tmpd: Option>, pub success: bool, pub stdout: String, @@ -55,58 +56,58 @@ pub struct CmdResult { } impl CmdResult { - /// asserts that the command resulted in a success (zero) status code + /// Asserts that the command resulted in a success (zero) status code pub fn success(&self) -> Box<&CmdResult> { assert!(self.success); Box::new(self) } - /// asserts that the command resulted in a failure (non-zero) status code + /// Asserts that the command resulted in a failure (non-zero) status code pub fn failure(&self) -> Box<&CmdResult> { assert!(!self.success); Box::new(self) } - /// asserts that the command resulted in empty (zero-length) stderr stream output - /// generally, it's better to use stdout_only() instead, + /// Asserts that the command resulted in empty (zero-length) stderr stream + /// output generally, it's better to use stdout_only() instead, /// but you might find yourself using this function if - /// 1. you can not know exactly what stdout will be - /// or 2. you know that stdout will also be empty + /// 1. You can not know exactly what stdout will be; or + /// 2. You know that stdout will also be empty pub fn no_stderr(&self) -> Box<&CmdResult> { assert_eq!("", self.stderr); Box::new(self) } - /// asserts that the command resulted in empty (zero-length) stderr stream output - /// unless asserting there was neither stdout or stderr, stderr_only is usually a better choice - /// generally, it's better to use stderr_only() instead, - /// but you might find yourself using this function if - /// 1. you can not know exactly what stderr will be - /// or 2. you know that stderr will also be empty + /// Asserts that the command resulted in empty (zero-length) stderr stream + /// output unless asserting there was neither stdout or stderr, + /// stderr_only is usually a better choice generally, it's better to use + /// stderr_only() instead, but you might find yourself using this + /// function if: + /// 1. You can not know exactly what stderr will be; or + /// 2. You know that stderr will also be empty pub fn no_stdout(&self) -> Box<&CmdResult> { assert_eq!("", self.stdout); Box::new(self) } - /// asserts that the command resulted in stdout stream output that equals the - /// 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 + /// Asserts that the command resulted in stdout stream output that equals + /// the 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!( - String::from(msg.as_ref()), - self.stdout - ); + assert_eq!(String::from(msg.as_ref()), self.stdout); Box::new(self) } - /// like stdout_is(...), but expects the contents of the file at the provided relative path + /// Like stdout_is(...), but expects the contents of the file at the + /// provided relative path pub fn stdout_is_fixture>(&self, file_rel_path: T) -> Box<&CmdResult> { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stdout_is(contents) } - /// asserts that the command resulted in stderr stream output that equals the - /// passed in value, when both are trimmed of trailing whitespace + /// Asserts that the command resulted in stderr stream output that equals + /// the passed in value, when both are trimmed of trailing whitespace /// stderr_only is a better choice unless stdout may or will be non-empty pub fn stderr_is>(&self, msg: T) -> Box<&CmdResult> { assert_eq!( @@ -116,35 +117,38 @@ impl CmdResult { Box::new(self) } - /// like stderr_is(...), but expects the contents of the file at the provided relative path + /// Like stderr_is(...), but expects the contents of the file at the + /// provided relative path pub fn stderr_is_fixture>(&self, file_rel_path: T) -> Box<&CmdResult> { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stderr_is(contents) } - /// asserts that - /// 1. the command resulted in stdout stream output that equals the - /// passed in value, when both are trimmed of trailing whitespace - /// and 2. the command resulted in empty (zero-length) stderr stream output + /// Asserts that: + /// 1. The command resulted in stdout stream output that equals the + /// passed in value, when both are trimmed of trailing whitespace; and + /// 2. The command resulted in empty (zero-length) stderr stream output pub fn stdout_only>(&self, msg: T) -> Box<&CmdResult> { self.no_stderr().stdout_is(msg) } - /// like stdout_only(...), but expects the contents of the file at the provided relative path + /// like stdout_only(...), but expects the contents of the file at the + /// provided relative path pub fn stdout_only_fixture>(&self, file_rel_path: T) -> Box<&CmdResult> { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stdout_only(contents) } - /// asserts that - /// 1. the command resulted in stderr stream output that equals the - /// passed in value, when both are trimmed of trailing whitespace - /// and 2. the command resulted in empty (zero-length) stdout stream output + /// Asserts that: + /// 1. The command resulted in stderr stream output that equals the + /// passed in value, when both are trimmed of trailing whitespace; and + /// 2. The command resulted in empty (zero-length) stdout stream output pub fn stderr_only>(&self, msg: T) -> Box<&CmdResult> { self.no_stdout().stderr_is(msg) } - /// like stderr_only(...), but expects the contents of the file at the provided relative path + /// Like stderr_only(...), but expects the contents of the file at the + /// provided relative path pub fn stderr_only_fixture>(&self, file_rel_path: T) -> Box<&CmdResult> { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.stderr_only(contents) @@ -357,15 +361,17 @@ 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() .unwrap() .to_owned(); - // Due to canonicalize()'s use of GetFinalPathNameByHandleW() on Windows, the resolved path - // starts with '\\?\' to extend the limit of a given path to 32,767 wide characters. + // Due to canonicalize()'s use of GetFinalPathNameByHandleW() on Windows, the + // resolved path starts with '\\?\' to extend the limit of a given path + // to 32,767 wide characters. // // To address this issue, we remove this prepended string if available. // @@ -380,10 +386,12 @@ impl AtPath { } } -/// An environment for running a single uutils test case, serves three functions: -/// 1. centralizes logic for locating the uutils binary and calling the utility -/// 2. provides a temporary directory for the test case -/// 3. copies over fixtures for the utility to the temporary directory +/// An environment for running a single uutils test case, serves three +/// functions: +/// 1. Centralizes logic for locating the uutils binary and calling +/// the utility +/// 2. Provides a temporary directory for the test case +/// 3. Copies over fixtures for the utility to the temporary directory pub struct TestScenario { bin_path: PathBuf, util_name: String, @@ -441,12 +449,16 @@ impl TestScenario { } } -/// A `UCommand` is a wrapper around an individual Command that provides several additional features -/// 1. it has convenience functions that are more ergonomic to use for piping in stdin, spawning the command -/// and asserting on the results. -/// 2. it tracks arguments provided so that in test cases which may provide variations of an arg in loops -/// the test failure can display the exact call which preceded an assertion failure. -/// 3. it provides convenience construction arguments to set the Command working directory and/or clear its environment. +/// A `UCommand` is a wrapper around an individual Command that provides several +/// additional features: +/// 1. It has convenience functions that are more ergonomic +/// to use for piping in stdin, spawning the command and asserting on the +/// results. +/// 2. It tracks arguments provided so that in test cases which may +/// provide variations of an arg in loops the test failure can display the +/// exact call which preceded an assertion failure. +/// 3. It provides convenience construction arguments to set the Command working +/// directory and/or clear its environment. #[derive(Debug)] pub struct UCommand { pub raw: Command, @@ -468,8 +480,10 @@ impl UCommand { if cfg!(windows) { // %SYSTEMROOT% is required on Windows to initialize crypto provider // ... and crypto provider is required for std::rand - // From procmon: RegQueryValue HKLM\SOFTWARE\Microsoft\Cryptography\Defaults\Provider\Microsoft Strong Cryptographic Provider\Image Path - // SUCCESS Type: REG_SZ, Length: 66, Data: %SystemRoot%\system32\rsaenh.dll" + // From procmon: RegQueryValue + // HKLM\SOFTWARE\Microsoft\Cryptography\Defaults\Provider\Microsoft Strong + // Cryptographic Provider\Image Path SUCCESS Type: + // REG_SZ, Length: 66, Data: %SystemRoot%\system32\rsaenh.dll" for (key, _) in env::vars_os() { if key.as_os_str() != "SYSTEMROOT" { cmd.env_remove(key); @@ -503,7 +517,8 @@ impl UCommand { Box::new(self) } - /// like arg(...), but uses the contents of the file at the provided relative path as the argument + /// Like arg(...), but uses the contents of the file at the provided + /// relative path as the argument pub fn arg_fixture>(&mut self, file_rel_path: S) -> Box<&mut UCommand> { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.arg(contents) @@ -522,7 +537,7 @@ impl UCommand { Box::new(self) } - /// provides stdinput to feed in to the command when spawned + /// Provides stdinput to feed in to the command when spawned pub fn pipe_in>>(&mut self, input: T) -> Box<&mut UCommand> { if self.stdin.is_some() { panic!(MULTIPLE_STDIN_MEANINGLESS); @@ -531,7 +546,8 @@ impl UCommand { Box::new(self) } - /// like pipe_in(...), but uses the contents of the file at the provided relative path as the piped in data + /// Like pipe_in(...), but uses the contents of the file at the provided + /// relative path as the piped in data pub fn pipe_in_fixture>(&mut self, file_rel_path: S) -> Box<&mut UCommand> { let contents = read_scenario_fixture(&self.tmpd, file_rel_path); self.pipe_in(contents) @@ -557,7 +573,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()) @@ -592,8 +609,8 @@ impl UCommand { /// Spawns the command, feeding the passed in stdin, waits for the result /// and returns a command result. - /// It is recommended that, instead of this, you use a combination of pipe_in() - /// with succeeds() or fails() + /// It is recommended that, instead of this, you use a combination of + /// pipe_in() with succeeds() or fails() pub fn run_piped_stdin>>(&mut self, input: T) -> CmdResult { self.pipe_in(input).run() }