1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-27 11:07:44 +00:00

cargo fmt

This commit is contained in:
Roy Ivy III 2020-01-27 23:14:11 -06:00
parent 15722e3ace
commit 5af8503a5e
119 changed files with 1270 additions and 923 deletions

View file

@ -16,8 +16,8 @@ pub fn main() {
if val == "1" && key.starts_with(feature_prefix) { if val == "1" && key.starts_with(feature_prefix) {
let krate = key[feature_prefix.len()..].to_lowercase(); let krate = key[feature_prefix.len()..].to_lowercase();
match krate.as_ref() { match krate.as_ref() {
"default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic" | "windows" | "windows_legacy" "default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic"
| "nightly" | "test_unimplemented" => continue, | "windows" | "windows_legacy" | "nightly" | "test_unimplemented" => continue,
_ => {} _ => {}
} }
crates.push(krate.to_string()); crates.push(krate.to_string());
@ -35,7 +35,8 @@ pub fn main() {
fn util_map() -> UtilityMap { fn util_map() -> UtilityMap {
let mut map: UtilityMap = HashMap::new();\n" let mut map: UtilityMap = HashMap::new();\n"
.as_bytes(), .as_bytes(),
).unwrap(); )
.unwrap();
for krate in crates { for krate in crates {
cf.write_all(format!("extern crate uu_{krate};\n", krate = krate).as_bytes()) 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(\"shake128sum\", uu_hashsum::uumain);
map.insert(\"shake256sum\", uu_hashsum::uumain);\n" map.insert(\"shake256sum\", uu_hashsum::uumain);\n"
.as_bytes(), .as_bytes(),
).unwrap(); )
.unwrap();
} }
_ => mf.write_all( _ => mf
format!( .write_all(
"map.insert(\"{krate}\", uu_{krate}::uumain);\n", format!(
krate = krate "map.insert(\"{krate}\", uu_{krate}::uumain);\n",
).as_bytes(), krate = krate
).unwrap(), )
.as_bytes(),
)
.unwrap(),
} }
} }

View file

@ -1,6 +1,6 @@
use std::env; use std::env;
use std::io::Write;
use std::fs::File; use std::fs::File;
use std::io::Write;
use std::path::Path; use std::path::Path;
static TEMPLATE: &'static str = "\ static TEMPLATE: &'static str = "\

View file

@ -16,8 +16,7 @@ use uucore::encoding::Format;
mod base_common; mod base_common;
static SYNTAX: &str = "[OPTION]... [FILE]"; static SYNTAX: &str = "[OPTION]... [FILE]";
static SUMMARY: &str = static SUMMARY: &str = "Base32 encode or decode FILE, or standard input, to standard output.";
"Base32 encode or decode FILE, or standard input, to standard output.";
static LONG_HELP: &str = " static LONG_HELP: &str = "
With no FILE, or when FILE is -, read standard input. With no FILE, or when FILE is -, read standard input.

View file

@ -16,8 +16,7 @@ use uucore::encoding::Format;
mod base_common; mod base_common;
static SYNTAX: &str = "[OPTION]... [FILE]"; static SYNTAX: &str = "[OPTION]... [FILE]";
static SUMMARY: &str = static SUMMARY: &str = "Base64 encode or decode FILE, or standard input, to standard output.";
"Base64 encode or decode FILE, or standard input, to standard output.";
static LONG_HELP: &str = " static LONG_HELP: &str = "
With no FILE, or when FILE is -, read standard input. With no FILE, or when FILE is -, read standard input.

View file

@ -36,13 +36,11 @@ pub fn execute(
"COLS", "COLS",
) )
.parse(args); .parse(args);
let line_wrap = matches.opt_str("wrap").map(|s| { let line_wrap = matches.opt_str("wrap").map(|s| match s.parse() {
match s.parse() { Ok(n) => n,
Ok(n) => n, Err(e) => {
Err(e) => { crash!(1, "invalid wrap size: {}: {}", s, e);
crash!(1, "invalid wrap size: {}: {}", s, e);
}
} }
}); });
let ignore_garbage = matches.opt_present("ignore-garbage"); let ignore_garbage = matches.opt_present("ignore-garbage");
@ -55,7 +53,13 @@ pub fn execute(
if matches.free.is_empty() || &matches.free[0][..] == "-" { if matches.free.is_empty() || &matches.free[0][..] == "-" {
let stdin_raw = stdin(); 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 { } else {
let path = Path::new(matches.free[0].as_str()); let path = Path::new(matches.free[0].as_str());
let file_buf = safe_unwrap!(File::open(&path)); let file_buf = safe_unwrap!(File::open(&path));
@ -73,8 +77,7 @@ fn handle_input<R: Read>(
ignore_garbage: bool, ignore_garbage: bool,
decode: bool, decode: bool,
) { ) {
let mut data = Data::new(input, format) let mut data = Data::new(input, format).ignore_garbage(ignore_garbage);
.ignore_garbage(ignore_garbage);
if let Some(wrap) = line_wrap { if let Some(wrap) = line_wrap {
data = data.line_wrap(wrap); data = data.line_wrap(wrap);
} }
@ -88,4 +91,4 @@ fn handle_input<R: Read>(
Err(_) => crash!(1, "invalid input"), Err(_) => crash!(1, "invalid input"),
} }
} }
} }

View file

@ -168,7 +168,10 @@ pub fn uumain(args: Vec<String>) -> i32 {
files.push("-".to_owned()); files.push("-".to_owned());
} }
let can_write_fast = !(show_tabs || show_nonprint || show_ends || squeeze_blank let can_write_fast = !(show_tabs
|| show_nonprint
|| show_ends
|| squeeze_blank
|| number_mode != NumberingMode::None); || number_mode != NumberingMode::None);
let success = if can_write_fast { let success = if can_write_fast {
@ -190,7 +193,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
write_lines(files, &options).is_ok() 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 /// Classifies the `InputType` of file at `path` if possible
@ -205,25 +212,13 @@ fn get_input_type(path: &str) -> CatResult<InputType> {
match metadata(path).context(path)?.file_type() { match metadata(path).context(path)?.file_type() {
#[cfg(unix)] #[cfg(unix)]
ft if ft.is_block_device() => ft if ft.is_block_device() => Ok(InputType::BlockDevice),
{
Ok(InputType::BlockDevice)
}
#[cfg(unix)] #[cfg(unix)]
ft if ft.is_char_device() => ft if ft.is_char_device() => Ok(InputType::CharacterDevice),
{
Ok(InputType::CharacterDevice)
}
#[cfg(unix)] #[cfg(unix)]
ft if ft.is_fifo() => ft if ft.is_fifo() => Ok(InputType::Fifo),
{
Ok(InputType::Fifo)
}
#[cfg(unix)] #[cfg(unix)]
ft if ft.is_socket() => ft if ft.is_socket() => Ok(InputType::Socket),
{
Ok(InputType::Socket)
}
ft if ft.is_dir() => Ok(InputType::Directory), ft if ft.is_dir() => Ok(InputType::Directory),
ft if ft.is_file() => Ok(InputType::File), ft if ft.is_file() => Ok(InputType::File),
ft if ft.is_symlink() => Ok(InputType::SymLink), ft if ft.is_symlink() => Ok(InputType::SymLink),
@ -282,12 +277,14 @@ fn write_fast(files: Vec<String>) -> CatResult<()> {
for file in files { for file in files {
match open(&file[..]) { match open(&file[..]) {
Ok(mut handle) => while let Ok(n) = handle.reader.read(&mut in_buf) { Ok(mut handle) => {
if n == 0 { while let Ok(n) = handle.reader.read(&mut in_buf) {
break; if n == 0 {
break;
}
writer.write_all(&in_buf[..n]).context(&file[..])?;
} }
writer.write_all(&in_buf[..n]).context(&file[..])?; }
},
Err(error) => { Err(error) => {
writeln!(&mut stderr(), "{}", error)?; writeln!(&mut stderr(), "{}", error)?;
error_count += 1; error_count += 1;
@ -421,10 +418,7 @@ fn write_to_end<W: Write>(in_buf: &[u8], writer: &mut W) -> usize {
fn write_tab_to_end<W: Write>(mut in_buf: &[u8], writer: &mut W) -> usize { fn write_tab_to_end<W: Write>(mut in_buf: &[u8], writer: &mut W) -> usize {
let mut count = 0; let mut count = 0;
loop { loop {
match in_buf match in_buf.iter().position(|c| *c == b'\n' || *c == b'\t') {
.iter()
.position(|c| *c == b'\n' || *c == b'\t')
{
Some(p) => { Some(p) => {
writer.write_all(&in_buf[..p]).unwrap(); writer.write_all(&in_buf[..p]).unwrap();
if in_buf[p] == b'\n' { if in_buf[p] == b'\n' {
@ -458,7 +452,8 @@ fn write_nonprint_to_end<W: Write>(in_buf: &[u8], writer: &mut W, tab: &[u8]) ->
128..=159 => writer.write_all(&[b'M', b'-', b'^', byte - 64]), 128..=159 => writer.write_all(&[b'M', b'-', b'^', byte - 64]),
160..=254 => writer.write_all(&[b'M', b'-', byte - 128]), 160..=254 => writer.write_all(&[b'M', b'-', byte - 128]),
_ => writer.write_all(&[b'M', b'-', b'^', 63]), _ => writer.write_all(&[b'M', b'-', b'^', 63]),
}.unwrap(); }
.unwrap();
count += 1; count += 1;
} }
if count != in_buf.len() { if count != in_buf.len() {

View file

@ -10,15 +10,15 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use uucore::libc::{self, gid_t, lchown};
pub use uucore::entries; pub use uucore::entries;
use uucore::fs::resolve_relative_path; use uucore::fs::resolve_relative_path;
use uucore::libc::{self, gid_t, lchown};
extern crate walkdir; extern crate walkdir;
use walkdir::WalkDir; use walkdir::WalkDir;
use std::io::Result as IOResult;
use std::io::Error as IOError; use std::io::Error as IOError;
use std::io::Result as IOResult;
use std::fs; use std::fs;
use std::fs::Metadata; use std::fs::Metadata;
@ -183,12 +183,12 @@ struct Chgrper {
} }
macro_rules! unwrap { macro_rules! unwrap {
($m:expr, $e:ident, $err:block) => ( ($m:expr, $e:ident, $err:block) => {
match $m { match $m {
Ok(meta) => meta, Ok(meta) => meta,
Err($e) => $err, Err($e) => $err,
} }
) };
} }
impl Chgrper { impl Chgrper {

View file

@ -19,10 +19,10 @@ extern crate uucore;
use std::fs; use std::fs;
use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::Path; use std::path::Path;
use walker::Walker; use uucore::fs::display_permissions_unix;
#[cfg(not(windows))] #[cfg(not(windows))]
use uucore::mode; use uucore::mode;
use uucore::fs::display_permissions_unix; use walker::Walker;
const NAME: &str = "chmod"; const NAME: &str = "chmod";
static SUMMARY: &str = "Change the mode of each FILE to MODE. static SUMMARY: &str = "Change the mode of each FILE to MODE.
@ -39,14 +39,31 @@ pub fn uumain(mut args: Vec<String>) -> i32 {
NAME NAME
); );
let mut opts = new_coreopts!(&syntax, SUMMARY, LONG_HELP); let mut opts = new_coreopts!(&syntax, SUMMARY, LONG_HELP);
opts.optflag("c", "changes", "like verbose but report only when a change is made") opts.optflag(
// TODO: support --silent (can be done using clap) "c",
.optflag("f", "quiet", "suppress most error messages") "changes",
.optflag("v", "verbose", "output a diagnostic for every file processed") "like verbose but report only when a change is made",
.optflag("", "no-preserve-root", "do not treat '/' specially (the default)") )
.optflag("", "preserve-root", "fail to operate recursively on '/'") // TODO: support --silent (can be done using clap)
.optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE") .optflag("f", "quiet", "suppress most error messages")
.optflag("R", "recursive", "change files and directories recursively"); .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 // sanitize input for - at beginning (e.g. chmod -x testfile). Remove
// the option and save it for later, after parsing is finished. // the option and save it for later, after parsing is finished.
@ -148,17 +165,19 @@ impl Chmoder {
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One // 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 // possible fix is to use CStrings rather than Strings in the args
// to chmod() and chmod_file(). // to chmod() and chmod_file().
r = self.chmod( r = self
walk_dir .chmod(
.filter_map(|x| match x { walk_dir
Ok(o) => match o.path().into_os_string().to_str() { .filter_map(|x| match x {
Some(s) => Some(s.to_owned()), Ok(o) => match o.path().into_os_string().to_str() {
None => None, Some(s) => Some(s.to_owned()),
}, None => None,
Err(_) => None, },
}) Err(_) => None,
.collect(), })
).and(r); .collect(),
)
.and(r);
r = self.chmod_file(&file, filename).and(r); r = self.chmod_file(&file, filename).and(r);
} }
} else { } else {
@ -230,7 +249,12 @@ impl Chmoder {
fn change_file(&self, fperm: u32, mode: u32, file: &Path, path: &str) -> Result<(), i32> { fn change_file(&self, fperm: u32, mode: u32, file: &Path, path: &str) -> Result<(), i32> {
if fperm == mode { if fperm == mode {
if self.verbose && !self.changes { 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(()) Ok(())
} else if let Err(err) = } else if let Err(err) =

View file

@ -11,9 +11,9 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use uucore::libc::{self, gid_t, lchown, uid_t};
pub use uucore::entries::{self, Group, Locate, Passwd}; pub use uucore::entries::{self, Group, Locate, Passwd};
use uucore::fs::resolve_relative_path; use uucore::fs::resolve_relative_path;
use uucore::libc::{self, gid_t, lchown, uid_t};
extern crate walkdir; extern crate walkdir;
use walkdir::WalkDir; use walkdir::WalkDir;
@ -24,8 +24,8 @@ use std::os::unix::fs::MetadataExt;
use std::io; use std::io;
use std::io::Result as IOResult; use std::io::Result as IOResult;
use std::path::Path;
use std::convert::AsRef; use std::convert::AsRef;
use std::path::Path;
use std::ffi::CString; use std::ffi::CString;
use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStrExt;
@ -253,12 +253,12 @@ struct Chowner {
} }
macro_rules! unwrap { macro_rules! unwrap {
($m:expr, $e:ident, $err:block) => ( ($m:expr, $e:ident, $err:block) => {
match $m { match $m {
Ok(meta) => meta, Ok(meta) => meta,
Err($e) => $err, Err($e) => $err,
} }
) };
} }
impl Chowner { impl Chowner {

View file

@ -14,8 +14,8 @@ extern crate getopts;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use uucore::libc::{self, chroot, setgid, setgroups, setuid};
use uucore::entries; use uucore::entries;
use uucore::libc::{self, chroot, setgid, setgroups, setuid};
use std::ffi::CString; use std::ffi::CString;
use std::io::Error; use std::io::Error;
@ -140,10 +140,7 @@ fn enter_chroot(root: &Path) {
let root_str = root.display(); let root_str = root.display();
std::env::set_current_dir(root).unwrap(); std::env::set_current_dir(root).unwrap();
let err = unsafe { let err = unsafe {
chroot(CString::new(".") chroot(CString::new(".").unwrap().as_bytes_with_nul().as_ptr() as *const libc::c_char)
.unwrap()
.as_bytes_with_nul()
.as_ptr() as *const libc::c_char)
}; };
if err != 0 { if err != 0 {
crash!( crash!(

View file

@ -32,7 +32,8 @@ fn main() {
&file, &file,
"#[allow(clippy::unreadable_literal)]\nconst CRC_TABLE: [u32; {}] = {:?};", "#[allow(clippy::unreadable_literal)]\nconst CRC_TABLE: [u32; {}] = {:?};",
CRC_TABLE_LEN, table CRC_TABLE_LEN, table
).unwrap(); )
.unwrap();
} }
#[inline] #[inline]

View file

@ -1,5 +1,4 @@
#![crate_name = "uu_cp"] #![crate_name = "uu_cp"]
#![allow(clippy::missing_safety_doc)] #![allow(clippy::missing_safety_doc)]
/* /*
@ -29,35 +28,35 @@ extern crate xattr;
#[cfg(windows)] #[cfg(windows)]
extern crate kernel32; extern crate kernel32;
#[cfg(windows)] #[cfg(windows)]
use kernel32::GetFileInformationByHandle;
#[cfg(windows)]
use kernel32::CreateFileW; use kernel32::CreateFileW;
#[cfg(windows)] #[cfg(windows)]
use kernel32::GetFileInformationByHandle;
#[cfg(windows)]
extern crate winapi; extern crate winapi;
use std::mem; use clap::{App, Arg, ArgMatches};
use filetime::FileTime;
use quick_error::ResultExt;
use std::collections::HashSet;
#[cfg(not(windows))] #[cfg(not(windows))]
use std::ffi::CString; use std::ffi::CString;
#[cfg(windows)] #[cfg(windows)]
use std::ffi::OsStr; use std::ffi::OsStr;
use clap::{App, Arg, ArgMatches};
use quick_error::ResultExt;
use std::collections::HashSet;
use std::fs; 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;
use std::io::{stdin, stdout, Write};
use std::mem;
#[cfg(target_os = "linux")]
use std::os::unix::io::IntoRawFd;
#[cfg(windows)] #[cfg(windows)]
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf, StripPrefixError}; use std::path::{Path, PathBuf, StripPrefixError};
use std::str::FromStr; use std::str::FromStr;
use uucore::fs::{canonicalize, CanonicalizeMode}; use uucore::fs::{canonicalize, CanonicalizeMode};
use walkdir::WalkDir; 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)] #[cfg(unix)]
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
@ -584,7 +583,8 @@ impl Options {
} }
} }
let recursive = matches.is_present(OPT_RECURSIVE) || matches.is_present(OPT_RECURSIVE_ALIAS) let recursive = matches.is_present(OPT_RECURSIVE)
|| matches.is_present(OPT_RECURSIVE_ALIAS)
|| matches.is_present(OPT_ARCHIVE); || matches.is_present(OPT_ARCHIVE);
let backup = matches.is_present(OPT_BACKUP) || (matches.occurrences_of(OPT_SUFFIX) > 0); let backup = matches.is_present(OPT_BACKUP) || (matches.occurrences_of(OPT_SUFFIX) > 0);
@ -731,7 +731,8 @@ fn preserve_hardlinks(
"cannot stat {:?}: {}", "cannot stat {:?}: {}",
src_path, src_path,
std::io::Error::last_os_error() std::io::Error::last_os_error()
).into()); )
.into());
} }
inode = stat.st_ino as u64; inode = stat.st_ino as u64;
nlinks = stat.st_nlink as u64; nlinks = stat.st_nlink as u64;
@ -755,7 +756,8 @@ fn preserve_hardlinks(
"cannot get file information {:?}: {}", "cannot get file information {:?}: {}",
source, source,
std::io::Error::last_os_error() std::io::Error::last_os_error()
).into()); )
.into());
} }
inode = ((*stat).nFileIndexHigh as u64) << 32 | (*stat).nFileIndexLow as u64; inode = ((*stat).nFileIndexHigh as u64) << 32 | (*stat).nFileIndexLow as u64;
nlinks = (*stat).nNumberOfLinks as u64; nlinks = (*stat).nNumberOfLinks as u64;
@ -836,7 +838,8 @@ fn construct_dest_path(
return Err(format!( return Err(format!(
"cannot overwrite directory '{}' with non-directory", "cannot overwrite directory '{}' with non-directory",
target.display() target.display()
).into()); )
.into());
} }
Ok(match *target_type { Ok(match *target_type {
@ -1140,7 +1143,8 @@ fn copy_helper(source: &Path, dest: &Path, options: &Options) -> CopyResult<()>
source, source,
dest, dest,
std::io::Error::last_os_error() std::io::Error::last_os_error()
).into()); )
.into());
} else { } else {
return Ok(()); return Ok(());
} }
@ -1169,7 +1173,8 @@ pub fn verify_target_type(target: &Path, target_type: &TargetType) -> CopyResult
(&TargetType::File, true) => Err(format!( (&TargetType::File, true) => Err(format!(
"cannot overwrite directory '{}' with non-directory", "cannot overwrite directory '{}' with non-directory",
target.display() target.display()
).into()), )
.into()),
_ => Ok(()), _ => Ok(()),
} }
} }
@ -1205,6 +1210,8 @@ fn test_cp_localize_to_target() {
&Path::new("a/source/"), &Path::new("a/source/"),
&Path::new("a/source/c.txt"), &Path::new("a/source/c.txt"),
&Path::new("target/") &Path::new("target/")
).unwrap() == Path::new("target/c.txt") )
.unwrap()
== Path::new("target/c.txt")
) )
} }

View file

@ -10,8 +10,8 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
use std::io::{BufRead, BufReader, Read, Write};
use std::io::Result as IoResult; use std::io::Result as IoResult;
use std::io::{BufRead, BufReader, Read, Write};
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub mod Bytes { pub mod Bytes {

View file

@ -466,8 +466,8 @@ pub fn uumain(args: Vec<String>) -> i32 {
) )
}) })
} }
(None, None, Some(field_ranges)) => list_to_ranges(&field_ranges[..], complement) (None, None, Some(field_ranges)) => {
.and_then(|ranges| { list_to_ranges(&field_ranges[..], complement).and_then(|ranges| {
let out_delim = match matches.opt_str("output-delimiter") { let out_delim = match matches.opt_str("output-delimiter") {
Some(s) => { Some(s) => {
if s.is_empty() { if s.is_empty() {
@ -519,11 +519,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
}, },
)), )),
} }
}), })
}
(ref b, ref c, ref f) if b.is_some() || c.is_some() || f.is_some() => Err( (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)"), msg_expects_no_more_than_one_of!("--fields (-f)", "--chars (-c)", "--bytes (-b)"),
), ),
_ => Err(msg_expects_one_of!("--fields (-f)", "--chars (-c)", "--bytes (-b)")), _ => Err(msg_expects_one_of!(
"--fields (-f)",
"--chars (-c)",
"--bytes (-b)"
)),
}; };
let mode_parse = match mode_parse { let mode_parse = match mode_parse {

View file

@ -42,10 +42,7 @@ impl FromStr for Range {
(Some(n), Some(m)) if m.is_empty() => { (Some(n), Some(m)) if m.is_empty() => {
if let Ok(low) = n.parse::<usize>() { if let Ok(low) = n.parse::<usize>() {
if low > 0 { if low > 0 {
Ok(Range { Ok(Range { low, high: MAX - 1 })
low,
high: MAX - 1,
})
} else { } else {
Err(field) Err(field)
} }
@ -67,10 +64,7 @@ impl FromStr for Range {
(Some(n), Some(m)) => match (n.parse::<usize>(), m.parse::<usize>()) { (Some(n), Some(m)) => match (n.parse::<usize>(), m.parse::<usize>()) {
(Ok(low), Ok(high)) => { (Ok(low), Ok(high)) => {
if low > 0 && low <= high { if low > 0 && low <= high {
Ok(Range { Ok(Range { low, high })
low,
high,
})
} else if low == 0 { } else if low == 0 {
Err(field) Err(field)
} else { } else {

View file

@ -14,8 +14,8 @@ extern crate chrono;
extern crate clap; extern crate clap;
extern crate uucore; extern crate uucore;
use chrono::{DateTime, FixedOffset, Local, Offset};
use chrono::offset::Utc; use chrono::offset::Utc;
use chrono::{DateTime, FixedOffset, Local, Offset};
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::path::PathBuf; use std::path::PathBuf;
@ -210,12 +210,11 @@ fn parse_cli(args: Vec<String>) -> Settings {
"set time described by STRING") "set time described by STRING")
(@arg utc: -u --utc --universal (@arg utc: -u --utc --universal
"print or set Coordinated Universal Time (UTC)")) "print or set Coordinated Universal Time (UTC)"))
// TODO: Decide whether this is appropriate. // TODO: Decide whether this is appropriate.
// The GNU date command has an explanation of all formatting options, // The GNU date command has an explanation of all formatting options,
// but the `chrono` crate has a few differences (most notably, the %Z option) // but the `chrono` crate has a few differences (most notably, the %Z option)
// (after_help: include_str!("usage.txt"))) // (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 format = if let Some(form) = matches.value_of("custom_format") {
let form = form[1..].into(); let form = form[1..].into();

View file

@ -1,5 +1,4 @@
pub const INTERNAL_DB: &str = pub const INTERNAL_DB: &str = r#"# Configuration file for dircolors, a utility to help you set the
r#"# Configuration file for dircolors, a utility to help you set the
# LS_COLORS environment variable used by GNU ls with the --color option. # LS_COLORS environment variable used by GNU ls with the --color option.
# Copyright (C) 1996-2016 Free Software Foundation, Inc. # Copyright (C) 1996-2016 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification, # Copying and distribution of this file, with or without modification,

View file

@ -13,10 +13,10 @@ extern crate glob;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::borrow::Borrow; use std::borrow::Borrow;
use std::env; use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};
static SYNTAX: &str = "[OPTION]... [FILE]"; static SYNTAX: &str = "[OPTION]... [FILE]";
static SUMMARY: &str = "Output commands to set the LS_COLORS environment variable."; static SUMMARY: &str = "Output commands to set the LS_COLORS environment variable.";
@ -68,8 +68,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
.optflag("p", "print-database", "print the byte counts") .optflag("p", "print-database", "print the byte counts")
.parse(args); .parse(args);
if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") if (matches.opt_present("csh")
|| matches.opt_present("bourne-shell")) && matches.opt_present("print-database") || matches.opt_present("c-shell")
|| matches.opt_present("sh")
|| matches.opt_present("bourne-shell"))
&& matches.opt_present("print-database")
{ {
disp_err!( disp_err!(
"the options to output dircolors' internal database and\nto select a shell \ "the options to output dircolors' internal database and\nto select a shell \
@ -291,7 +294,7 @@ where
} else if key.starts_with('*') { } else if key.starts_with('*') {
result.push_str(format!("{}={}:", key, val).as_str()); result.push_str(format!("{}={}:", key, val).as_str());
} else if lower == "options" || lower == "color" || lower == "eightbit" { } else if lower == "options" || lower == "color" || lower == "eightbit" {
// Slackware only. Ignore // Slackware only. Ignore
} else if let Some(s) = table.get(lower.as_str()) { } else if let Some(s) = table.get(lower.as_str()) {
result.push_str(format!("{}={}:", s, val).as_str()); result.push_str(format!("{}={}:", s, val).as_str());
} else { } else {

View file

@ -163,40 +163,36 @@ fn du(
for f in read { for f in read {
match f { match f {
Ok(entry) => { Ok(entry) => match Stat::new(entry.path()) {
match Stat::new(entry.path()) { Ok(this_stat) => {
Ok(this_stat) => { if this_stat.is_dir {
if this_stat.is_dir { futures.push(du(this_stat, options, depth + 1, inodes));
futures.push(du(this_stat, options, depth + 1, inodes)); } else {
} else { if inodes.contains(&this_stat.inode) {
if inodes.contains(&this_stat.inode) { continue;
continue; }
} inodes.insert(this_stat.inode);
inodes.insert(this_stat.inode); my_stat.size += this_stat.size;
my_stat.size += this_stat.size; my_stat.blocks += this_stat.blocks;
my_stat.blocks += this_stat.blocks; if options.all {
if options.all { stats.push(this_stat);
stats.push(this_stat);
}
} }
} }
Err(error) => show_error!("{}", error),
} }
} Err(error) => show_error!("{}", error),
},
Err(error) => show_error!("{}", error), Err(error) => show_error!("{}", error),
} }
} }
} }
stats.extend(futures.into_iter().flatten().rev().filter( stats.extend(futures.into_iter().flatten().rev().filter(|stat| {
|stat| { if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path {
if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path { my_stat.size += stat.size;
my_stat.size += stat.size; my_stat.blocks += stat.blocks;
my_stat.blocks += stat.blocks; }
} options.max_depth == None || depth < options.max_depth.unwrap()
options.max_depth == None || depth < options.max_depth.unwrap() }));
},
));
stats.push(my_stat); stats.push(my_stat);
Box::new(stats.into_iter()) Box::new(stats.into_iter())
} }
@ -220,7 +216,10 @@ fn convert_size_k(size: u64, multiplier: u64, _block_size: u64) -> String {
} }
fn convert_size_m(size: u64, multiplier: u64, _block_size: u64) -> String { 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 { fn convert_size_other(size: u64, _multiplier: u64, block_size: u64) -> String {
@ -235,66 +234,109 @@ pub fn uumain(args: Vec<String>) -> i32 {
NAME NAME
); );
let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP)
// In task // In task
.optflag("a", "all", " write counts for all files, not just directories") .optflag(
// In main "a",
.optflag("", "apparent-size", "print apparent sizes, rather than disk usage "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 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 ('sparse') files, internal fragmentation, indirect blocks, and the like",
// In main )
.optopt("B", "block-size", "scale sizes by SIZE before printing them. // 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.", E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.",
"SIZE") "SIZE",
// In main )
.optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'") // In main
// In main .optflag(
"b",
"bytes",
"equivalent to '--apparent-size --block-size=1'",
)
// In main
.optflag("c", "total", "produce a grand total") .optflag("c", "total", "produce a grand total")
// In task // In task
// opts.optflag("D", "dereference-args", "dereference only symlinks that are listed // opts.optflag("D", "dereference-args", "dereference only symlinks that are listed
// on the command line"), // on the command line"),
// In main // In main
// opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file // opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file
// names specified in file F; // names specified in file F;
// If F is - then read names from standard input", "F"), // If F is - then read names from standard input", "F"),
// // In task // // In task
// opts.optflag("H", "", "equivalent to --dereference-args (-D)"), // opts.optflag("H", "", "equivalent to --dereference-args (-D)"),
// In main // In main
.optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)") .optflag(
// In main "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") .optflag("", "si", "like -h, but use powers of 1000 not 1024")
// In main // In main
.optflag("k", "", "like --block-size=1K") .optflag("k", "", "like --block-size=1K")
// In task // In task
.optflag("l", "count-links", "count sizes many times if hard linked") .optflag("l", "count-links", "count sizes many times if hard linked")
// // In main // // In main
.optflag("m", "", "like --block-size=1M") .optflag("m", "", "like --block-size=1M")
// // In task // // In task
// opts.optflag("L", "dereference", "dereference all symbolic links"), // opts.optflag("L", "dereference", "dereference all symbolic links"),
// // In task // // In task
// opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"), // opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"),
// // In main // // In main
.optflag("0", "null", "end each output line with 0 byte rather than newline") .optflag(
// In main "0",
.optflag("S", "separate-dirs", "do not include size of subdirectories") "null",
// In main "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") .optflag("s", "summarize", "display only a total for each argument")
// // In task // // In task
// opts.optflag("x", "one-file-system", "skip directories on different file systems"), // opts.optflag("x", "one-file-system", "skip directories on different file systems"),
// // In task // // In task
// opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"), // opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"),
// // In task // // In task
// opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"), // opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"),
// In main // In main
.optopt("d", "max-depth", "print the total for a directory (or file, with --all) .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 only if it is N or fewer levels below the command
line argument; --max-depth=0 is the same as --summarize", "N") line argument; --max-depth=0 is the same as --summarize",
// In main "N",
.optflagopt("", "time", "show time of the last modification of any file in the )
// 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 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") of modification time: atime, access, use, ctime or status",
// In main "WORD",
.optopt("", "time-style", "show times using style STYLE: )
full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE") // In main
.optopt(
"",
"time-style",
"show times using style STYLE:
full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'",
"STYLE",
)
.parse(args); .parse(args);
let summarize = matches.opt_present("summarize"); let summarize = matches.opt_present("summarize");
@ -350,26 +392,24 @@ pub fn uumain(args: Vec<String>) -> i32 {
let convert_size = |size| convert_size_fn(size, multiplier, block_size); let convert_size = |size| convert_size_fn(size, multiplier, block_size);
let time_format_str = match matches.opt_str("time-style") { let time_format_str = match matches.opt_str("time-style") {
Some(s) => { Some(s) => match &s[..] {
match &s[..] { "full-iso" => "%Y-%m-%d %H:%M:%S.%f %z",
"full-iso" => "%Y-%m-%d %H:%M:%S.%f %z", "long-iso" => "%Y-%m-%d %H:%M",
"long-iso" => "%Y-%m-%d %H:%M", "iso" => "%Y-%m-%d",
"iso" => "%Y-%m-%d", _ => {
_ => { show_error!(
show_error!( "invalid argument '{}' for 'time style'
"invalid argument '{}' for 'time style'
Valid arguments are: Valid arguments are:
- 'full-iso' - 'full-iso'
- 'long-iso' - 'long-iso'
- 'iso' - 'iso'
Try '{} --help' for more information.", Try '{} --help' for more information.",
s, s,
NAME NAME
); );
return 1; return 1;
}
} }
} },
None => "%Y-%m-%d %H:%M", None => "%Y-%m-%d %H:%M",
}; };
@ -397,23 +437,21 @@ Try '{} --help' for more information.",
let tm = { let tm = {
let (secs, nsecs) = { let (secs, nsecs) = {
let time = match matches.opt_str("time") { let time = match matches.opt_str("time") {
Some(s) => { Some(s) => match &s[..] {
match &s[..] { "accessed" => stat.accessed,
"accessed" => stat.accessed, "created" => stat.created,
"created" => stat.created, "modified" => stat.modified,
"modified" => stat.modified, _ => {
_ => { show_error!(
show_error!( "invalid argument 'modified' for '--time'
"invalid argument 'modified' for '--time'
Valid arguments are: Valid arguments are:
- 'accessed', 'created', 'modified' - 'accessed', 'created', 'modified'
Try '{} --help' for more information.", Try '{} --help' for more information.",
NAME NAME
); );
return 1; return 1;
}
} }
} },
None => stat.modified, None => stat.modified,
}; };
((time / 1000) as i64, (time % 1000 * 1_000_000) as i32) ((time / 1000) as i64, (time % 1000 * 1_000_000) as i32)

View file

@ -71,8 +71,8 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
'b' => '\x08', 'b' => '\x08',
'c' => { 'c' => {
should_stop = true; should_stop = true;
break break;
}, }
'e' => '\x1b', 'e' => '\x1b',
'f' => '\x0c', 'f' => '\x0c',
'n' => '\n', 'n' => '\n',
@ -90,7 +90,7 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
_ => { _ => {
start = 0; start = 0;
next next
}, }
}; };
} }
} }
@ -110,7 +110,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
let matches = new_coreopts!(SYNTAX, SUMMARY, HELP) let matches = new_coreopts!(SYNTAX, SUMMARY, HELP)
.optflag("n", "", "do not output the trailing newline") .optflag("n", "", "do not output the trailing newline")
.optflag("e", "", "enable interpretation of backslash escapes") .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); .parse(args);
let no_newline = matches.opt_present("n"); let no_newline = matches.opt_present("n");

3
src/env/env.rs vendored
View file

@ -89,7 +89,8 @@ fn load_config_file(opts: &mut Options) -> Result<(), i32> {
} }
}; };
for (_, prop) in &conf { // ignore all INI section lines (treat them as comments) for (_, prop) in &conf {
// ignore all INI section lines (treat them as comments)
for (key, value) in prop { for (key, value) in prop {
env::set_var(key, value); env::set_var(key, value);
} }

View file

@ -45,7 +45,8 @@ fn tabstops_parse(s: String) -> Vec<usize> {
crash!(1, "{}\n", "tab size cannot be 0"); 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)) .fold((true, 0), |(acc, last), &n| (acc && last <= n, n))
{ {
crash!(1, "{}\n", "tab sizes must be ascending"); crash!(1, "{}\n", "tab sizes must be ascending");

View file

@ -13,8 +13,8 @@ extern crate onig;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
mod tokens;
mod syntax_tree; mod syntax_tree;
mod tokens;
static NAME: &str = "expr"; static NAME: &str = "expr";
static VERSION: &str = env!("CARGO_PKG_VERSION"); static VERSION: &str = env!("CARGO_PKG_VERSION");

View file

@ -12,8 +12,8 @@
//! * https://en.wikipedia.org/wiki/Shunting-yard_algorithm //! * https://en.wikipedia.org/wiki/Shunting-yard_algorithm
//! //!
use tokens::Token;
use onig::{Regex, RegexOptions, Syntax}; use onig::{Regex, RegexOptions, Syntax};
use tokens::Token;
type TokenStack = Vec<(usize, Token)>; type TokenStack = Vec<(usize, Token)>;
pub type OperandsList = Vec<Box<ASTNode>>; pub type OperandsList = Vec<Box<ASTNode>>;
@ -85,25 +85,27 @@ impl ASTNode {
ASTNode::Node { ref op_type, .. } => match self.operand_values() { ASTNode::Node { ref op_type, .. } => match self.operand_values() {
Err(reason) => Err(reason), Err(reason) => Err(reason),
Ok(operand_values) => match op_type.as_ref() { Ok(operand_values) => match op_type.as_ref() {
"+" => infix_operator_two_ints(|a: i64, b: i64| { "+" => infix_operator_two_ints(
checked_binop(|| a.checked_add(b), "+") |a: i64, b: i64| checked_binop(|| a.checked_add(b), "+"),
}, &operand_values &operand_values,
), ),
"-" => infix_operator_two_ints(|a: i64, b: i64| { "-" => infix_operator_two_ints(
checked_binop(|| a.checked_sub(b), "-") |a: i64, b: i64| checked_binop(|| a.checked_sub(b), "-"),
}, &operand_values &operand_values,
), ),
"*" => infix_operator_two_ints(|a: i64, b: i64| { "*" => infix_operator_two_ints(
checked_binop(|| a.checked_mul(b), "*") |a: i64, b: i64| checked_binop(|| a.checked_mul(b), "*"),
}, &operand_values &operand_values,
), ),
"/" => infix_operator_two_ints(|a: i64, b: i64| { "/" => infix_operator_two_ints(
|a: i64, b: i64| {
if b == 0 { if b == 0 {
Err("division by zero".to_owned()) Err("division by zero".to_owned())
} else { } else {
checked_binop(|| a.checked_div(b), "/") checked_binop(|| a.checked_div(b), "/")
} }
}, &operand_values },
&operand_values,
), ),
"%" => infix_operator_two_ints( "%" => infix_operator_two_ints(
|a: i64, b: i64| { |a: i64, b: i64| {
@ -299,18 +301,29 @@ fn push_token_to_either_stack(
op_stack: &mut TokenStack, op_stack: &mut TokenStack,
) -> Result<(), String> { ) -> Result<(), String> {
let result = match *token { let result = match *token {
Token::Value { .. } => { out_stack.push((token_idx, token.clone())); Ok(()) }, Token::Value { .. } => {
out_stack.push((token_idx, token.clone()));
Ok(())
}
Token::InfixOp { .. } => if op_stack.is_empty() { Token::InfixOp { .. } => {
if op_stack.is_empty() {
op_stack.push((token_idx, token.clone()));
Ok(())
} else {
push_op_to_stack(token_idx, token, out_stack, op_stack)
}
}
Token::PrefixOp { .. } => {
op_stack.push((token_idx, token.clone())); op_stack.push((token_idx, token.clone()));
Ok(()) Ok(())
} else { }
push_op_to_stack(token_idx, token, out_stack, op_stack)
},
Token::PrefixOp { .. } => { op_stack.push((token_idx, token.clone())); Ok(()) }, Token::ParOpen => {
op_stack.push((token_idx, token.clone()));
Token::ParOpen => { op_stack.push((token_idx, token.clone())); Ok(()) }, Ok(())
}
Token::ParClose => move_till_match_paren(out_stack, op_stack), Token::ParClose => move_till_match_paren(out_stack, op_stack),
}; };
@ -352,7 +365,10 @@ fn push_op_to_stack(
{ {
loop { loop {
match op_stack.last() { match op_stack.last() {
None => { op_stack.push((token_idx, token.clone())); return Ok(()) }, None => {
op_stack.push((token_idx, token.clone()));
return Ok(());
}
Some(&(_, Token::ParOpen)) => { Some(&(_, Token::ParOpen)) => {
op_stack.push((token_idx, token.clone())); op_stack.push((token_idx, token.clone()));
@ -365,12 +381,14 @@ fn push_op_to_stack(
precedence: prev_prec, precedence: prev_prec,
.. ..
}, },
)) => if la && prev_prec >= prec || !la && prev_prec > prec { )) => {
out_stack.push(op_stack.pop().unwrap()) if la && prev_prec >= prec || !la && prev_prec > prec {
} else { out_stack.push(op_stack.pop().unwrap())
op_stack.push((token_idx, token.clone())); } else {
return Ok(()); op_stack.push((token_idx, token.clone()));
}, return Ok(());
}
}
Some(&(_, Token::PrefixOp { .. })) => { Some(&(_, Token::PrefixOp { .. })) => {
op_stack.push((token_idx, token.clone())); op_stack.push((token_idx, token.clone()));

View file

@ -141,12 +141,7 @@ fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) {
} }
} }
fn push_token_if_not_escaped( fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
acc: &mut Vec<(usize, Token)>,
tok_idx: usize,
token: Token,
s: &str,
) {
// Smells heuristics... :( // Smells heuristics... :(
let prev_is_plus = match acc.last() { let prev_is_plus = match acc.last() {
None => false, None => false,

View file

@ -115,7 +115,8 @@ fn main() {
file, file,
"\n];\n\n#[allow(dead_code)]\npub const NEXT_PRIME: u64 = {};\n", "\n];\n\n#[allow(dead_code)]\npub const NEXT_PRIME: u64 = {};\n",
x x
).unwrap(); )
.unwrap();
} }
#[test] #[test]

View file

@ -20,12 +20,12 @@ extern crate uucore;
use numeric::*; use numeric::*;
use rand::distributions::{Distribution, Uniform}; use rand::distributions::{Distribution, Uniform};
use rand::{SeedableRng, thread_rng};
use rand::rngs::SmallRng; use rand::rngs::SmallRng;
use rand::{thread_rng, SeedableRng};
use std::cmp::{max, min}; use std::cmp::{max, min};
use std::io::{stdin, BufRead}; use std::io::{stdin, BufRead};
use std::num::Wrapping;
use std::mem::swap; use std::mem::swap;
use std::num::Wrapping;
mod numeric; mod numeric;
@ -155,7 +155,10 @@ fn print_factors(num: u64) {
} }
fn print_factors_str(num_str: &str) { fn print_factors_str(num_str: &str) {
if let Err(e) = num_str.parse::<u64>().and_then(|x| { print_factors(x); Ok(()) }) { if let Err(e) = num_str.parse::<u64>().and_then(|x| {
print_factors(x);
Ok(())
}) {
show_warning!("{}: {}", num_str, e); show_warning!("{}: {}", num_str, e);
} }
} }

View file

@ -9,8 +9,8 @@
* that was distributed with this source code. * that was distributed with this source code.
*/ */
use std::u64::MAX as MAX_U64;
use std::num::Wrapping; use std::num::Wrapping;
use std::u64::MAX as MAX_U64;
pub fn big_add(a: u64, b: u64, m: u64) -> u64 { pub fn big_add(a: u64, b: u64, m: u64) -> u64 {
let Wrapping(msb_mod_m) = Wrapping(MAX_U64) - Wrapping(m) + Wrapping(1); let Wrapping(msb_mod_m) = Wrapping(MAX_U64) - Wrapping(m) + Wrapping(1);

View file

@ -14,12 +14,12 @@ extern crate unicode_width;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::cmp;
use std::io::{BufReader, BufWriter, Read};
use std::fs::File;
use std::io::{stdin, stdout, Write};
use linebreak::break_lines; use linebreak::break_lines;
use parasplit::ParagraphStream; use parasplit::ParagraphStream;
use std::cmp;
use std::fs::File;
use std::io::{stdin, stdout, Write};
use std::io::{BufReader, BufWriter, Read};
macro_rules! silent_unwrap( macro_rules! silent_unwrap(
($exp:expr) => ( ($exp:expr) => (

View file

@ -7,12 +7,12 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
use FmtOptions;
use parasplit::{ParaWords, Paragraph, WordInfo}; use parasplit::{ParaWords, Paragraph, WordInfo};
use std::io::{BufWriter, Stdout, Write};
use std::i64;
use std::cmp; use std::cmp;
use std::i64;
use std::io::{BufWriter, Stdout, Write};
use std::mem; use std::mem;
use FmtOptions;
struct BreakArgs<'a> { struct BreakArgs<'a> {
opts: &'a FmtOptions, opts: &'a FmtOptions,
@ -58,18 +58,19 @@ pub fn break_lines(para: &Paragraph, opts: &FmtOptions, ostream: &mut BufWriter<
} }
}; };
// print the init, if it exists, and get its length // print the init, if it exists, and get its length
let p_init_len = w_len + if opts.crown || opts.tagged { let p_init_len = w_len
// handle "init" portion + if opts.crown || opts.tagged {
silent_unwrap!(ostream.write_all(para.init_str.as_bytes())); // handle "init" portion
para.init_len silent_unwrap!(ostream.write_all(para.init_str.as_bytes()));
} else if !para.mail_header { para.init_len
// for non-(crown, tagged) that's the same as a normal indent } else if !para.mail_header {
silent_unwrap!(ostream.write_all(p_indent.as_bytes())); // for non-(crown, tagged) that's the same as a normal indent
p_indent_len silent_unwrap!(ostream.write_all(p_indent.as_bytes()));
} else { p_indent_len
// except that mail headers get no indent at all } else {
0 // except that mail headers get no indent at all
}; 0
};
// write first word after writing init // write first word after writing init
silent_unwrap!(ostream.write_all(w.as_bytes())); silent_unwrap!(ostream.write_all(w.as_bytes()));
@ -218,17 +219,15 @@ fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
) -> Vec<(&'a WordInfo<'a>, bool)> { ) -> Vec<(&'a WordInfo<'a>, bool)> {
let mut iter = iter.peekable(); let mut iter = iter.peekable();
// set up the initial null linebreak // set up the initial null linebreak
let mut linebreaks = vec![ let mut linebreaks = vec![LineBreak {
LineBreak { prev: 0,
prev: 0, linebreak: None,
linebreak: None, break_before: false,
break_before: false, demerits: 0,
demerits: 0, prev_rat: 0.0f32,
prev_rat: 0.0f32, length: args.init_len,
length: args.init_len, fresh: false,
fresh: false, }];
},
];
// this vec holds the current active linebreaks; next_ holds the breaks that will be active for // this vec holds the current active linebreaks; next_ holds the breaks that will be active for
// the next word // the next word
let active_breaks = &mut vec![0]; let active_breaks = &mut vec![0];
@ -275,7 +274,9 @@ fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
} }
// get the new length // 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; + active.length;
// if tlen is longer than args.opts.width, we drop this break from the active list // if tlen is longer than args.opts.width, we drop this break from the active list
@ -304,7 +305,8 @@ fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
// do not even consider adding a line that has too many demerits // do not even consider adding a line that has too many demerits
// also, try to detect overflow by checking signum // also, try to detect overflow by checking signum
let total_demerits = new_demerits + active.demerits; 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() && active.demerits.signum() <= new_demerits.signum()
{ {
ld_new = total_demerits; ld_new = total_demerits;

View file

@ -7,8 +7,8 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
use std::iter::Peekable;
use std::io::{BufRead, Lines}; use std::io::{BufRead, Lines};
use std::iter::Peekable;
use std::slice::Iter; use std::slice::Iter;
use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthChar;
use FileOrStdReader; use FileOrStdReader;
@ -72,10 +72,7 @@ pub struct FileLines<'a> {
impl<'a> FileLines<'a> { impl<'a> FileLines<'a> {
fn new<'b>(opts: &'b FmtOptions, lines: Lines<&'b mut FileOrStdReader>) -> FileLines<'b> { fn new<'b>(opts: &'b FmtOptions, lines: Lines<&'b mut FileOrStdReader>) -> FileLines<'b> {
FileLines { FileLines { opts, lines }
opts,
lines,
}
} }
// returns true if this line should be formatted // returns true if this line should be formatted
@ -363,8 +360,9 @@ impl<'a> Iterator for ParagraphStream<'a> {
} }
} else if !second_done { } 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 // in both crown and tagged modes we require that prefix_len is the same 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
prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end
|| ||
// in tagged mode, indent has to be *different* on following lines // in tagged mode, indent has to be *different* on following lines
self.opts.tagged && indent_len - 4 == fl.indent_len && indent_end == fl.indent_end self.opts.tagged && indent_len - 4 == fl.indent_len && indent_end == fl.indent_end
@ -380,7 +378,8 @@ impl<'a> Iterator for ParagraphStream<'a> {
second_done = true; second_done = true;
} else { } else {
// detect mismatch // detect mismatch
if indent_end != fl.indent_end || pfxind_end != fl.pfxind_end if indent_end != fl.indent_end
|| pfxind_end != fl.pfxind_end
|| indent_len != fl.indent_len || indent_len != fl.indent_len
|| prefix_len != fl.prefix_len || prefix_len != fl.prefix_len
{ {

View file

@ -70,9 +70,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) { fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
for (i, arg) in args.iter().enumerate() { for (i, arg) in args.iter().enumerate() {
let slice = &arg; let slice = &arg;
if slice.starts_with('-') && slice.len() > 1 if slice.starts_with('-') && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
&& slice.chars().nth(1).unwrap().is_digit(10)
{
let mut v = args.to_vec(); let mut v = args.to_vec();
v.remove(i); v.remove(i);
return (v, Some(slice[1..].to_owned())); return (v, Some(slice[1..].to_owned()));
@ -145,11 +143,13 @@ fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width:
let ncount = routput.chars().fold(0, |out, ch: char| { let ncount = routput.chars().fold(0, |out, ch: char| {
out + match ch { out + match ch {
'\t' => 8, '\t' => 8,
'\x08' => if out > 0 { '\x08' => {
!0 if out > 0 {
} else { !0
0 } else {
}, 0
}
}
'\r' => return 0, '\r' => return 0,
_ => 1, _ => 1,
} }

View file

@ -12,7 +12,7 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use uucore::entries::{get_groups, Locate, Passwd, gid2grp}; use uucore::entries::{get_groups, gid2grp, Locate, Passwd};
static SYNTAX: &str = "[user]"; static SYNTAX: &str = "[user]";
static SUMMARY: &str = "display current group names"; static SUMMARY: &str = "display current group names";

View file

@ -71,7 +71,7 @@ impl Digest for sha1::Sha1 {
// Implements the Digest trait for sha2 / sha3 algorithms with fixed ouput // Implements the Digest trait for sha2 / sha3 algorithms with fixed ouput
macro_rules! impl_digest_sha { macro_rules! impl_digest_sha {
($type: ty, $size: expr) => ( ($type: ty, $size: expr) => {
impl Digest for $type { impl Digest for $type {
fn new() -> Self { fn new() -> Self {
Self::default() Self::default()
@ -89,14 +89,16 @@ macro_rules! impl_digest_sha {
*self = Self::new(); *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 // Implements the Digest trait for sha2 / sha3 algorithms with variable ouput
macro_rules! impl_digest_shake { macro_rules! impl_digest_shake {
($type: ty) => ( ($type: ty) => {
impl Digest for $type { impl Digest for $type {
fn new() -> Self { fn new() -> Self {
Self::default() Self::default()
@ -114,9 +116,11 @@ macro_rules! impl_digest_shake {
*self = Self::new(); *self = Self::new();
} }
fn output_bits(&self) -> usize { 0 } fn output_bits(&self) -> usize {
0
}
} }
) };
} }
impl_digest_sha!(sha2::Sha224, 224); impl_digest_sha!(sha2::Sha224, 224);

View file

@ -65,10 +65,26 @@ fn detect_algo(
"sha512sum" => ("SHA512", Box::new(Sha512::new()) as Box<dyn Digest>, 512), "sha512sum" => ("SHA512", Box::new(Sha512::new()) as Box<dyn Digest>, 512),
"sha3sum" => match matches.opt_str("bits") { "sha3sum" => match matches.opt_str("bits") {
Some(bits_str) => match usize::from_str_radix(&bits_str, 10) { Some(bits_str) => match usize::from_str_radix(&bits_str, 10) {
Ok(224) => ("SHA3-224", Box::new(Sha3_224::new()) as Box<dyn Digest>, 224), Ok(224) => (
Ok(256) => ("SHA3-256", Box::new(Sha3_256::new()) as Box<dyn Digest>, 256), "SHA3-224",
Ok(384) => ("SHA3-384", Box::new(Sha3_384::new()) as Box<dyn Digest>, 384), Box::new(Sha3_224::new()) as Box<dyn Digest>,
Ok(512) => ("SHA3-512", Box::new(Sha3_512::new()) as Box<dyn Digest>, 512), 224,
),
Ok(256) => (
"SHA3-256",
Box::new(Sha3_256::new()) as Box<dyn Digest>,
256,
),
Ok(384) => (
"SHA3-384",
Box::new(Sha3_384::new()) as Box<dyn Digest>,
384,
),
Ok(512) => (
"SHA3-512",
Box::new(Sha3_512::new()) as Box<dyn Digest>,
512,
),
Ok(_) => crash!( Ok(_) => crash!(
1, 1,
"Invalid output size for SHA3 (expected 224, 256, 384, or 512)" "Invalid output size for SHA3 (expected 224, 256, 384, or 512)"
@ -77,20 +93,44 @@ fn detect_algo(
}, },
None => crash!(1, "--bits required for SHA3"), None => crash!(1, "--bits required for SHA3"),
}, },
"sha3-224sum" => ("SHA3-224", Box::new(Sha3_224::new()) as Box<dyn Digest>, 224), "sha3-224sum" => (
"sha3-256sum" => ("SHA3-256", Box::new(Sha3_256::new()) as Box<dyn Digest>, 256), "SHA3-224",
"sha3-384sum" => ("SHA3-384", Box::new(Sha3_384::new()) as Box<dyn Digest>, 384), Box::new(Sha3_224::new()) as Box<dyn Digest>,
"sha3-512sum" => ("SHA3-512", Box::new(Sha3_512::new()) as Box<dyn Digest>, 512), 224,
),
"sha3-256sum" => (
"SHA3-256",
Box::new(Sha3_256::new()) as Box<dyn Digest>,
256,
),
"sha3-384sum" => (
"SHA3-384",
Box::new(Sha3_384::new()) as Box<dyn Digest>,
384,
),
"sha3-512sum" => (
"SHA3-512",
Box::new(Sha3_512::new()) as Box<dyn Digest>,
512,
),
"shake128sum" => match matches.opt_str("bits") { "shake128sum" => match matches.opt_str("bits") {
Some(bits_str) => match usize::from_str_radix(&bits_str, 10) { Some(bits_str) => match usize::from_str_radix(&bits_str, 10) {
Ok(bits) => ("SHAKE128", Box::new(Shake128::new()) as Box<dyn Digest>, bits), Ok(bits) => (
"SHAKE128",
Box::new(Shake128::new()) as Box<dyn Digest>,
bits,
),
Err(err) => crash!(1, "{}", err), Err(err) => crash!(1, "{}", err),
}, },
None => crash!(1, "--bits required for SHAKE-128"), None => crash!(1, "--bits required for SHAKE-128"),
}, },
"shake256sum" => match matches.opt_str("bits") { "shake256sum" => match matches.opt_str("bits") {
Some(bits_str) => match usize::from_str_radix(&bits_str, 10) { Some(bits_str) => match usize::from_str_radix(&bits_str, 10) {
Ok(bits) => ("SHAKE256", Box::new(Shake256::new()) as Box<dyn Digest>, bits), Ok(bits) => (
"SHAKE256",
Box::new(Shake256::new()) as Box<dyn Digest>,
bits,
),
Err(err) => crash!(1, "{}", err), Err(err) => crash!(1, "{}", err),
}, },
None => crash!(1, "--bits required for SHAKE-256"), None => crash!(1, "--bits required for SHAKE-256"),
@ -319,17 +359,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
matches.free matches.free
}; };
match hashsum( match hashsum(
name, name, algo, files, binary, check, tag, status, quiet, strict, warn, bits,
algo,
files,
binary,
check,
tag,
status,
quiet,
strict,
warn,
bits,
) { ) {
Ok(()) => return 0, Ok(()) => return 0,
Err(e) => return e, Err(e) => return e,
@ -449,7 +479,8 @@ fn hashsum(
&mut ckf, &mut ckf,
binary_check, binary_check,
output_bits output_bits
)).to_ascii_lowercase(); ))
.to_ascii_lowercase();
if sum == real_sum { if sum == real_sum {
if !quiet { if !quiet {
println!("{}: OK", ck_filename); println!("{}: OK", ck_filename);
@ -472,8 +503,12 @@ fn hashsum(
} }
if !status { if !status {
match bad_format.cmp(&1) { match bad_format.cmp(&1) {
std::cmp::Ordering::Equal => show_warning!("{} line is improperly formatted", bad_format), std::cmp::Ordering::Equal => {
std::cmp::Ordering::Greater => show_warning!("{} lines are improperly formatted", bad_format), show_warning!("{} line is improperly formatted", bad_format)
}
std::cmp::Ordering::Greater => {
show_warning!("{} lines are improperly formatted", bad_format)
}
_ => {} _ => {}
}; };
if failed > 0 { if failed > 0 {

View file

@ -14,8 +14,8 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::io::{stdin, BufRead, BufReader, Read};
use std::fs::File; use std::fs::File;
use std::io::{stdin, BufRead, BufReader, Read};
use std::path::Path; use std::path::Path;
use std::str::from_utf8; use std::str::from_utf8;
@ -90,12 +90,14 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
} }
} }
None => if let Some(count) = matches.opt_str("c") { None => {
match count.parse::<usize>() { if let Some(count) = matches.opt_str("c") {
Ok(m) => settings.mode = FilterMode::Bytes(m), match count.parse::<usize>() {
Err(e) => { Ok(m) => settings.mode = FilterMode::Bytes(m),
show_error!("invalid byte count '{}': {}", count, e); Err(e) => {
return 1; show_error!("invalid byte count '{}': {}", count, e);
return 1;
}
} }
} }
} }
@ -186,12 +188,16 @@ fn obsolete(options: &[String]) -> (Vec<String>, Option<usize>) {
// TODO: handle errors on read // TODO: handle errors on read
fn head<T: Read>(reader: &mut BufReader<T>, settings: &Settings) -> bool { fn head<T: Read>(reader: &mut BufReader<T>, settings: &Settings) -> bool {
match settings.mode { match settings.mode {
FilterMode::Bytes(count) => for byte in reader.bytes().take(count) { FilterMode::Bytes(count) => {
print!("{}", byte.unwrap() as char); 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::Lines(count) => {
for line in reader.lines().take(count) {
println!("{}", line.unwrap());
}
}
} }
true true
} }

View file

@ -17,21 +17,21 @@ extern crate winapi;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::collections::hash_set::HashSet;
use std::iter::repeat;
use std::io;
use std::str;
use std::net::ToSocketAddrs;
use getopts::Matches; use getopts::Matches;
use std::collections::hash_set::HashSet;
use std::io;
use std::iter::repeat;
use std::net::ToSocketAddrs;
use std::str;
#[cfg(windows)] #[cfg(windows)]
use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup}; use uucore::wide::*;
#[cfg(windows)]
use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW};
#[cfg(windows)] #[cfg(windows)]
use winapi::shared::minwindef::MAKEWORD; use winapi::shared::minwindef::MAKEWORD;
#[cfg(windows)] #[cfg(windows)]
use uucore::wide::*; use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW};
#[cfg(windows)]
use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup};
#[cfg(not(windows))] #[cfg(not(windows))]
use libc::gethostname; use libc::gethostname;
@ -63,12 +63,28 @@ pub fn uumain(args: Vec<String>) -> i32 {
fn execute(args: Vec<String>) -> i32 { fn execute(args: Vec<String>) -> i32 {
let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.optflag("d", "domain", "Display the name of the DNS domain if possible") .optflag(
.optflag("i", "ip-address", "Display the network address(es) of the host") "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 // TODO: support --long
.optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)") .optflag(
.optflag("s", "short", "Display the short hostname (the portion before the first dot) if \ "f",
possible") "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); .parse(args);
match matches.free.len() { match matches.free.len() {

View file

@ -16,16 +16,16 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::ffi::CStr;
use uucore::entries::{self, Group, Locate, Passwd};
pub use uucore::libc; pub use uucore::libc;
use uucore::libc::{getlogin, uid_t}; use uucore::libc::{getlogin, uid_t};
use uucore::entries::{self, Group, Locate, Passwd};
use uucore::process::{getegid, geteuid, getgid, getuid}; use uucore::process::{getegid, geteuid, getgid, getuid};
use std::ffi::CStr;
macro_rules! cstr2cow { macro_rules! cstr2cow {
($v:expr) => ( ($v:expr) => {
unsafe { CStr::from_ptr($v).to_string_lossy() } unsafe { CStr::from_ptr($v).to_string_lossy() }
) };
} }
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]

View file

@ -101,49 +101,115 @@ fn parse_opts(args: Vec<String>) -> getopts::Matches {
NAME NAME
); );
new_coreopts!(&syntax, SUMMARY, LONG_HELP) new_coreopts!(&syntax, SUMMARY, LONG_HELP)
// TODO implement flag // TODO implement flag
.optflagopt("", "backup", "(unimplemented) make a backup of each existing destination\n \ .optflagopt(
file", "CONTROL") "",
// TODO implement flag "backup",
.optflag("b", "", "(unimplemented) like --backup but does not accept an argument") "(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") .optflag("c", "", "ignored")
// TODO implement flag // TODO implement flag
.optflag("C", "compare", "(unimplemented) compare each pair of source and destination\n \ .optflag(
files, and in some cases, do not modify the destination at all") "C",
.optflag("d", "directory", "treat all arguments as directory names.\n \ "compare",
create all components of the specified directories") "(unimplemented) compare each pair of source and destination\n \
// TODO implement flag files, and in some cases, do not modify the destination at all",
.optflag("D", "", "(unimplemented) create all leading components of DEST except the\n \ )
last, then copy SOURCE to DEST") .optflag(
// TODO implement flag "d",
.optflagopt("g", "group", "(unimplemented) set group ownership, instead of process'\n \ "directory",
current group", "GROUP") "treat all arguments as directory names.\n \
.optflagopt("m", "mode", "set permission mode (as in chmod), instead\n \ create all components of the specified directories",
of rwxr-xr-x", "MODE") )
// TODO implement flag // TODO implement flag
.optflagopt("o", "owner", "(unimplemented) set ownership (super-user only)", .optflag(
"OWNER") "D",
// TODO implement flag "",
.optflag("p", "preserve-timestamps", "(unimplemented) apply access/modification times\n \ "(unimplemented) create all leading components of DEST except the\n \
of SOURCE files to corresponding destination files") last, then copy SOURCE to DEST",
// TODO implement flag )
// 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") .optflag("s", "strip", "(unimplemented) strip symbol tables")
// TODO implement flag // TODO implement flag
.optflagopt("", "strip-program", "(unimplemented) program used to strip binaries", .optflagopt(
"PROGRAM") "",
// TODO implement flag "strip-program",
.optopt("S", "suffix", "(unimplemented) override the usual backup suffix", "SUFFIX") "(unimplemented) program used to strip binaries",
// TODO implement flag "PROGRAM",
.optopt("t", "target-directory", "(unimplemented) move all SOURCE arguments into\n \ )
DIRECTORY", "DIRECTORY") // TODO implement flag
// TODO implement flag .optopt(
.optflag("T", "no-target-directory", "(unimplemented) treat DEST as a normal file") "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") .optflag("v", "verbose", "explain what is being done")
// TODO implement flag // TODO implement flag
.optflag("P", "preserve-context", "(unimplemented) preserve security context") .optflag(
// TODO implement flag "P",
.optflagopt("Z", "context", "(unimplemented) set security context of files and\n \ "preserve-context",
directories", "CONTEXT") "(unimplemented) preserve security context",
)
// TODO implement flag
.optflagopt(
"Z",
"context",
"(unimplemented) set security context of files and\n \
directories",
"CONTEXT",
)
.parse(args) .parse(args)
} }

View file

@ -1,7 +1,7 @@
extern crate libc; extern crate libc;
use std::path::Path;
use std::fs; use std::fs;
use std::path::Path;
#[cfg(not(windows))] #[cfg(not(windows))]
use uucore::mode; use uucore::mode;

View file

@ -14,10 +14,10 @@ extern crate clap;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use clap::{App, Arg};
use std::cmp::{min, Ordering};
use std::fs::File; use std::fs::File;
use std::io::{stdin, BufRead, BufReader, Lines, Stdin}; use std::io::{stdin, BufRead, BufReader, Lines, Stdin};
use std::cmp::{min, Ordering};
use clap::{App, Arg};
static NAME: &str = "join"; static NAME: &str = "join";
static VERSION: &str = env!("CARGO_PKG_VERSION"); static VERSION: &str = env!("CARGO_PKG_VERSION");
@ -425,11 +425,13 @@ impl<'a> State<'a> {
if repr.uses_format() { if repr.uses_format() {
repr.print_format(|spec| match *spec { repr.print_format(|spec| match *spec {
Spec::Key => line.get_field(self.key), Spec::Key => line.get_field(self.key),
Spec::Field(file_num, field_num) => if file_num == self.file_num { Spec::Field(file_num, field_num) => {
line.get_field(field_num) if file_num == self.file_num {
} else { line.get_field(field_num)
None } else {
}, None
}
}
}); });
} else { } else {
repr.print_field(line.get_field(self.key)); repr.print_field(line.get_field(self.key));

View file

@ -74,9 +74,7 @@ fn handle_obsolete(mut args: Vec<String>) -> (Vec<String>, Option<String>) {
while i < args.len() { while i < args.len() {
// this is safe because slice is valid when it is referenced // this is safe because slice is valid when it is referenced
let slice = &args[i].clone(); let slice = &args[i].clone();
if slice.starts_with('-') && slice.len() > 1 if slice.starts_with('-') && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
&& slice.chars().nth(1).unwrap().is_digit(10)
{
let val = &slice[1..]; let val = &slice[1..];
match val.parse() { match val.parse() {
Ok(num) => { Ok(num) => {

View file

@ -13,8 +13,8 @@
extern crate uucore; extern crate uucore;
use std::fs::hard_link; use std::fs::hard_link;
use std::path::Path;
use std::io::Error; use std::io::Error;
use std::path::Path;
static SYNTAX: &str = "[OPTIONS] FILE1 FILE2"; static SYNTAX: &str = "[OPTIONS] FILE1 FILE2";
static SUMMARY: &str = "Create a link named FILE2 to FILE1"; static SUMMARY: &str = "Create a link named FILE2 to FILE1";

View file

@ -67,24 +67,45 @@ pub fn uumain(args: Vec<String>) -> i32 {
NAME NAME
); );
let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP) let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP)
.optflag("b", "", "make a backup of each file that would otherwise be overwritten or \ .optflag(
removed") "b",
.optflagopt("", "backup", "make a backup of each file that would otherwise be overwritten \ "",
or removed", "METHOD") "make a backup of each file that would otherwise be overwritten or \
// TODO: opts.optflag("d", "directory", "allow users with appropriate privileges to attempt \ removed",
// to make hard links to directories"); )
.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("f", "force", "remove existing destination files")
.optflag("i", "interactive", "prompt whether to remove existing destination files") .optflag(
// TODO: opts.optflag("L", "logical", "dereference TARGETs that are symbolic links"); "i",
// TODO: opts.optflag("n", "no-dereference", "treat LINK_NAME as a normal file if it is a \ "interactive",
// symbolic link to a directory"); "prompt whether to remove existing destination files",
// TODO: opts.optflag("P", "physical", "make hard links directly to symbolic links"); )
// TODO: opts.optflag("r", "relative", "create symbolic links relative to link location"); // 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") .optflag("s", "symbolic", "make symbolic links instead of hard links")
.optopt("S", "suffix", "override the usual backup suffix", "SUFFIX") .optopt("S", "suffix", "override the usual backup suffix", "SUFFIX")
.optopt("t", "target-directory", "specify the DIRECTORY in which to create the links", .optopt(
"DIRECTORY") "t",
.optflag("T", "no-target-directory", "treat LINK_NAME as a normal file always") "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") .optflag("v", "verbose", "print name of each linked file")
.parse(args); .parse(args);

View file

@ -9,12 +9,12 @@
// //
extern crate getopts; extern crate getopts;
extern crate number_prefix;
extern crate term_grid; extern crate term_grid;
extern crate termsize; extern crate termsize;
extern crate time; extern crate time;
extern crate unicode_width; extern crate unicode_width;
extern crate number_prefix; use number_prefix::{decimal_prefix, Prefixed, Standalone};
use number_prefix::{Standalone, Prefixed, decimal_prefix};
use term_grid::{Cell, Direction, Filling, Grid, GridOptions}; use term_grid::{Cell, Direction, Filling, Grid, GridOptions};
use time::{strftime, Timespec}; use time::{strftime, Timespec};
@ -30,20 +30,19 @@ extern crate lazy_static;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
#[cfg(unix)] #[cfg(unix)]
use uucore::libc::{mode_t, S_ISGID, S_ISUID, S_ISVTX, S_IWOTH, use uucore::libc::{mode_t, S_ISGID, S_ISUID, S_ISVTX, S_IWOTH, S_IXGRP, S_IXOTH, S_IXUSR};
S_IXGRP, S_IXOTH, S_IXUSR};
use std::fs;
use std::fs::{DirEntry, FileType, Metadata};
use std::path::{Path, PathBuf};
use std::cmp::Reverse; use std::cmp::Reverse;
#[cfg(unix)] #[cfg(unix)]
use std::collections::HashMap; 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)] #[cfg(unix)]
use std::os::unix::fs::FileTypeExt; use std::os::unix::fs::FileTypeExt;
#[cfg(any(unix, target_os = "redox"))]
use std::os::unix::fs::MetadataExt;
#[cfg(unix)] #[cfg(unix)]
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
@ -63,7 +62,8 @@ static DEFAULT_COLORS: &str = "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do
#[cfg(unix)] #[cfg(unix)]
lazy_static! { lazy_static! {
static ref LS_COLORS: String = std::env::var("LS_COLORS").unwrap_or_else(|_| DEFAULT_COLORS.to_string()); static ref LS_COLORS: String =
std::env::var("LS_COLORS").unwrap_or_else(|_| DEFAULT_COLORS.to_string());
static ref COLOR_MAP: HashMap<&'static str, &'static str> = { static ref COLOR_MAP: HashMap<&'static str, &'static str> = {
let codes = LS_COLORS.split(':'); let codes = LS_COLORS.split(':');
let mut map = HashMap::new(); let mut map = HashMap::new();
@ -163,7 +163,12 @@ pub fn uumain(args: Vec<String>) -> i32 {
directory. This is especially useful when listing very large directories, \ directory. This is especially useful when listing very large directories, \
since not doing any sorting can be noticeably faster.", since not doing any sorting can be noticeably faster.",
) )
.optflagopt("", "color", "Color output based on file type.", "always|auto|never") .optflagopt(
"",
"color",
"Color output based on file type.",
"always|auto|never",
)
.parse(args); .parse(args);
list(matches); list(matches);
@ -357,19 +362,17 @@ fn display_items(items: &[PathBuf], strip: Option<&Path>, options: &getopts::Mat
} }
} else { } else {
if !options.opt_present("1") { if !options.opt_present("1") {
let names = items let names = items.iter().filter_map(|i| {
.iter() let md = get_metadata(i, options);
.filter_map(|i| { match md {
let md = get_metadata(i, options); Err(e) => {
match md { let filename = get_file_name(i, strip);
Err(e) => { show_error!("{}: {}", filename, e);
let filename = get_file_name(i, strip); None
show_error!("{}: {}", filename, e);
None
}
Ok(md) => Some(display_file_name(&i, strip, &md, options)),
} }
}); Ok(md) => Some(display_file_name(&i, strip, &md, options)),
}
});
if let Some(size) = termsize::get() { if let Some(size) = termsize::get() {
let mut grid = Grid::new(GridOptions { let mut grid = Grid::new(GridOptions {
@ -512,7 +515,7 @@ fn display_file_size(metadata: &Metadata, options: &getopts::Matches) -> String
if options.opt_present("human-readable") { if options.opt_present("human-readable") {
match decimal_prefix(metadata.len() as f64) { match decimal_prefix(metadata.len() as f64) {
Standalone(bytes) => bytes.to_string(), Standalone(bytes) => bytes.to_string(),
Prefixed(prefix, bytes) => format!("{:.2}{}", bytes, prefix).to_uppercase() Prefixed(prefix, bytes) => format!("{:.2}{}", bytes, prefix).to_uppercase(),
} }
} else { } else {
metadata.len().to_string() metadata.len().to_string()
@ -596,9 +599,9 @@ fn color_name(name: String, typ: &str) -> String {
#[cfg(unix)] #[cfg(unix)]
macro_rules! has { macro_rules! has {
($mode:expr, $perm:expr) => ( ($mode:expr, $perm:expr) => {
$mode & ($perm as mode_t) != 0 $mode & ($perm as mode_t) != 0
) };
} }
#[cfg(unix)] #[cfg(unix)]

View file

@ -60,10 +60,10 @@ pub fn uumain(args: Vec<String>) -> i32 {
let res: Option<u16> = u16::from_str_radix(&m, 8).ok(); let res: Option<u16> = u16::from_str_radix(&m, 8).ok();
match res { match res {
Some(r) => r, Some(r) => r,
_ => crash!(1, "no mode given") _ => crash!(1, "no mode given"),
} }
}, }
_ => 0o755 as u16 _ => 0o755 as u16,
}; };
let dirs = matches.free; let dirs = matches.free;
@ -112,7 +112,11 @@ fn exec(dirs: Vec<String>, recursive: bool, mode: u16, verbose: bool) -> i32 {
* 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 { 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) { if let Err(e) = create_dir(path) {
show_info!("{}: {}", path.display(), e.to_string()); show_info!("{}: {}", path.display(), e.to_string());
return 1; return 1;
@ -124,17 +128,13 @@ fn mkdir(path: &Path, recursive: bool, mode: u16, verbose: bool) -> i32 {
#[cfg(any(unix, target_os = "redox"))] #[cfg(any(unix, target_os = "redox"))]
fn chmod(path: &Path, mode: u16) -> i32 { fn chmod(path: &Path, mode: u16) -> i32 {
use fs::{Permissions, set_permissions}; use fs::{set_permissions, Permissions};
use std::os::unix::fs::{PermissionsExt}; use std::os::unix::fs::PermissionsExt;
let mode = Permissions::from_mode(u32::from(mode)); let mode = Permissions::from_mode(u32::from(mode));
if let Err(err) = set_permissions(path, mode) { if let Err(err) = set_permissions(path, mode) {
show_error!( show_error!("{}: {}", path.display(), err);
"{}: {}",
path.display(),
err
);
return 1; return 1;
} }
0 0

View file

@ -77,10 +77,7 @@ Create a FIFO with the given name.",
for f in &matches.free { for f in &matches.free {
let err = unsafe { let err = unsafe {
let name = CString::new(f.as_bytes()).unwrap(); let name = CString::new(f.as_bytes()).unwrap();
mkfifo( mkfifo(name.as_ptr(), mode as libc::mode_t)
name.as_ptr(),
mode as libc::mode_t,
)
}; };
if err == -1 { if err == -1 {
show_error!( show_error!(

View file

@ -31,8 +31,7 @@ const MODE_RW_UGO: mode_t = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_
#[inline(always)] #[inline(always)]
fn makedev(maj: u64, min: u64) -> dev_t { fn makedev(maj: u64, min: u64) -> dev_t {
// pick up from <sys/sysmacros.h> // pick up from <sys/sysmacros.h>
((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32)) ((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32)) as dev_t
as dev_t
} }
#[cfg(windows)] #[cfg(windows)]

View file

@ -17,9 +17,9 @@ extern crate tempfile;
extern crate uucore; extern crate uucore;
use std::env; use std::env;
use std::path::{is_separator, PathBuf};
use std::mem::forget;
use std::iter; use std::iter;
use std::mem::forget;
use std::path::{is_separator, PathBuf};
use rand::Rng; use rand::Rng;
use tempfile::NamedTempFileOptions; use tempfile::NamedTempFileOptions;

View file

@ -1,8 +1,8 @@
// Mainly taken from crate `tempdir` // Mainly taken from crate `tempdir`
extern crate rand; extern crate rand;
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric; use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::io::Result as IOResult; use std::io::Result as IOResult;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};

View file

@ -15,8 +15,8 @@ extern crate getopts;
extern crate uucore; extern crate uucore;
use getopts::Options; use getopts::Options;
use std::io::{stdout, Read, Write};
use std::fs::File; use std::fs::File;
use std::io::{stdout, Read, Write};
#[cfg(all(unix, not(target_os = "fuchsia")))] #[cfg(all(unix, not(target_os = "fuchsia")))]
extern crate nix; extern crate nix;

View file

@ -14,8 +14,8 @@ extern crate getopts;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::fs;
use std::env; use std::env;
use std::fs;
use std::io::{stdin, Result}; use std::io::{stdin, Result};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -202,7 +202,9 @@ fn determine_backup_suffix(backup_mode: BackupMode, matches: &getopts::Matches)
); );
} }
} }
} else if let (Ok(s), BackupMode::SimpleBackup) = (env::var("SIMPLE_BACKUP_SUFFIX"), backup_mode) { } else if let (Ok(s), BackupMode::SimpleBackup) =
(env::var("SIMPLE_BACKUP_SUFFIX"), backup_mode)
{
s s
} else { } else {
"~".to_owned() "~".to_owned()
@ -257,7 +259,9 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 {
Err(e) => { Err(e) => {
show_error!( show_error!(
"cannot move {} to {}: {}", "cannot move {} to {}: {}",
source.display(), target.display(), e source.display(),
target.display(),
e
); );
1 1
} }
@ -269,7 +273,8 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 {
} else if target.exists() && source.is_dir() { } else if target.exists() && source.is_dir() {
show_error!( show_error!(
"cannot overwrite non-directory {} with directory {}", "cannot overwrite non-directory {} with directory {}",
target.display(), source.display() target.display(),
source.display()
); );
return 1; return 1;
} }
@ -359,8 +364,7 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> {
fs::rename(to, p)?; fs::rename(to, p)?;
} }
if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? {
{
return Ok(()); return Ok(());
} }
} }
@ -372,7 +376,10 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> {
if is_empty_dir(to) { if is_empty_dir(to) {
fs::remove_dir(to)? fs::remove_dir(to)?
} else { } else {
return Err(std::io::Error::new(std::io::ErrorKind::Other, "Directory not empty")); return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Directory not empty",
));
} }
} }
} }
@ -425,9 +432,7 @@ fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf {
fn is_empty_dir(path: &PathBuf) -> bool { fn is_empty_dir(path: &PathBuf) -> bool {
match fs::read_dir(path) { match fs::read_dir(path) {
Ok(contents) => { Ok(contents) => contents.peekable().peek().is_none(),
contents.peekable().peek().is_none() Err(_e) => false,
},
Err(_e) => { false }
} }
} }

View file

@ -336,7 +336,9 @@ fn nl<T: Read>(reader: &mut BufReader<T>, settings: &Settings) {
// A line number is to be printed. // A line number is to be printed.
let w = if settings.number_width > line_no_width { let w = if settings.number_width > line_no_width {
settings.number_width - line_no_width settings.number_width - line_no_width
} else { 0 }; } else {
0
};
let fill: String = repeat(fill_char).take(w).collect(); let fill: String = repeat(fill_char).take(w).collect();
match settings.number_format { match settings.number_format {
NumberFormat::Left => println!( NumberFormat::Left => println!(

View file

@ -15,14 +15,14 @@ extern crate libc;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use libc::{c_char, execvp, signal, dup2}; use libc::{c_char, dup2, execvp, signal};
use libc::{SIGHUP, SIG_IGN}; use libc::{SIGHUP, SIG_IGN};
use std::env;
use std::ffi::CString; use std::ffi::CString;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::Error; use std::io::Error;
use std::os::unix::prelude::*; use std::os::unix::prelude::*;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::env;
use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive}; use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive};
static NAME: &str = "nohup"; static NAME: &str = "nohup";

View file

@ -108,7 +108,12 @@ Print the number of cores available to the current process.",
0 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 { fn num_cpus_all() -> usize {
let nprocs = unsafe { libc::sysconf(_SC_NPROCESSORS_CONF) }; let nprocs = unsafe { libc::sysconf(_SC_NPROCESSORS_CONF) };
if nprocs == 1 { if nprocs == 1 {
@ -123,8 +128,12 @@ fn num_cpus_all() -> usize {
} }
// Other platform(e.g., windows), num_cpus::get() directly. // Other platform(e.g., windows), num_cpus::get() directly.
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd", #[cfg(not(any(
target_os = "netbsd")))] target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "netbsd"
)))]
fn num_cpus_all() -> usize { fn num_cpus_all() -> usize {
num_cpus::get() num_cpus::get()
} }

View file

@ -70,7 +70,8 @@ impl fmt::Display for DisplayableSuffix {
RawSuffix::E => write!(f, "E"), RawSuffix::E => write!(f, "E"),
RawSuffix::Z => write!(f, "Z"), RawSuffix::Z => write!(f, "Z"),
RawSuffix::Y => write!(f, "Y"), RawSuffix::Y => write!(f, "Y"),
}.and_then(|()| match with_i { }
.and_then(|()| match with_i {
true => write!(f, "i"), true => write!(f, "i"),
false => Ok(()), false => Ok(()),
}) })

View file

@ -1,8 +1,8 @@
// workaround until https://github.com/BurntSushi/byteorder/issues/41 has been fixed // 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 // 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::ByteOrder as ByteOrderTrait;
use byteorder::{BigEndian, LittleEndian, NativeEndian};
#[derive(Copy, Clone, Debug, Eq, PartialEq)] #[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ByteOrder { pub enum ByteOrder {

View file

@ -1,8 +1,8 @@
use std::io;
use byteorder_io::ByteOrder; use byteorder_io::ByteOrder;
use half::f16;
use multifilereader::HasError; use multifilereader::HasError;
use peekreader::PeekRead; use peekreader::PeekRead;
use half::f16; use std::io;
/// Processes an input and provides access to the data read in various formats /// Processes an input and provides access to the data read in various formats
/// ///
@ -60,7 +60,8 @@ where
/// calls `peek_read` on the internal stream to (re)fill the buffer. Returns a /// 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. /// MemoryDecoder providing access to the result or returns an i/o error.
pub fn peek_read(&mut self) -> io::Result<MemoryDecoder> { pub fn peek_read(&mut self) -> io::Result<MemoryDecoder> {
match self.input match self
.input
.peek_read(self.data.as_mut_slice(), self.reserved_peek_length) .peek_read(self.data.as_mut_slice(), self.reserved_peek_length)
{ {
Ok((n, p)) => { Ok((n, p)) => {
@ -157,9 +158,9 @@ impl<'a> MemoryDecoder<'a> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::io::Cursor;
use peekreader::PeekReader;
use byteorder_io::ByteOrder; use byteorder_io::ByteOrder;
use peekreader::PeekReader;
use std::io::Cursor;
#[test] #[test]
fn smoke_test() { fn smoke_test() {

View file

@ -1,7 +1,7 @@
// https://github.com/lazy-bitfield/rust-mockstream/pull/2 // 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::error::Error as errorError;
use std::io::{Cursor, Error, ErrorKind, Read, Result};
/// `FailingMockStream` mocks a stream which will fail upon read or write /// `FailingMockStream` mocks a stream which will fail upon read or write
/// ///

View file

@ -1,7 +1,7 @@
use std; use std;
use std::fs::File;
use std::io; use std::io;
use std::io::BufReader; use std::io::BufReader;
use std::fs::File;
use std::vec::Vec; use std::vec::Vec;
pub enum InputSource<'a> { pub enum InputSource<'a> {
@ -125,8 +125,8 @@ impl<'b> HasError for MultifileReader<'b> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::io::{Cursor, ErrorKind, Read};
use mockstream::*; use mockstream::*;
use std::io::{Cursor, ErrorKind, Read};
#[test] #[test]
fn test_multi_file_reader_one_read() { fn test_multi_file_reader_one_read() {

View file

@ -16,36 +16,36 @@ extern crate half;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
mod multifilereader;
mod partialreader;
mod peekreader;
mod byteorder_io; mod byteorder_io;
mod formatteriteminfo; 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 inputdecoder;
mod output_info; mod inputoffset;
#[cfg(test)] #[cfg(test)]
mod mockstream; 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 byteorder_io::*;
use formatteriteminfo::*;
use inputdecoder::{InputDecoder, MemoryDecoder};
use inputoffset::{InputOffset, Radix};
use multifilereader::*; 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 partialreader::*;
use peekreader::*; 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 prn_char::format_ascii_dump;
use parse_inputs::{parse_inputs, CommandLineInputs}; use std::cmp;
use inputoffset::{InputOffset, Radix};
use inputdecoder::{InputDecoder, MemoryDecoder};
use output_info::OutputInfo;
static VERSION: &str = env!("CARGO_PKG_VERSION"); static VERSION: &str = env!("CARGO_PKG_VERSION");
const PEEK_BUFFER_SIZE: usize = 4; // utf-8 can be 4 bytes const PEEK_BUFFER_SIZE: usize = 4; // utf-8 can be 4 bytes
@ -379,7 +379,8 @@ where
memory_decoder.zero_out_buffer(length, max_used); 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[..] && memory_decoder.get_buffer(0) == &previous_bytes[..]
{ {
if !duplicate_line { if !duplicate_line {

View file

@ -1,7 +1,7 @@
use formatteriteminfo::FormatterItemInfo;
use parse_formats::ParsedFormatterItemInfo;
use std::cmp; use std::cmp;
use std::slice::Iter; 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. /// Size in bytes of the max datatype. ie set to 16 for 128-bit numbers.
const MAX_BYTES_PER_UNIT: usize = 8; const MAX_BYTES_PER_UNIT: usize = 8;

View file

@ -1,7 +1,7 @@
use formatteriteminfo::FormatterItemInfo; use formatteriteminfo::FormatterItemInfo;
use prn_int::*;
use prn_char::*; use prn_char::*;
use prn_float::*; use prn_float::*;
use prn_int::*;
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct ParsedFormatterItemInfo { pub struct ParsedFormatterItemInfo {
@ -539,7 +539,8 @@ fn test_mixed_formats() {
"--".to_string(), "--".to_string(),
"-h".to_string(), "-h".to_string(),
"--format=f8".to_string(), "--format=f8".to_string(),
]).unwrap(), ])
.unwrap(),
vec![ vec![
ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC64S, false), // I ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC64S, false), // I
ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC8U, true), // tu1z ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC8U, true), // tu1z

View file

@ -323,23 +323,27 @@ mod tests {
parse_inputs(&MockOptions::new( parse_inputs(&MockOptions::new(
vec!["file1", "10", "10"], vec!["file1", "10", "10"],
vec!["traditional"] vec!["traditional"]
)).unwrap() ))
.unwrap()
); );
parse_inputs(&MockOptions::new( parse_inputs(&MockOptions::new(
vec!["10", "file1", "10"], vec!["10", "file1", "10"],
vec!["traditional"], vec!["traditional"],
)).unwrap_err(); ))
.unwrap_err();
parse_inputs(&MockOptions::new( parse_inputs(&MockOptions::new(
vec!["10", "10", "file1"], vec!["10", "10", "file1"],
vec!["traditional"], vec!["traditional"],
)).unwrap_err(); ))
.unwrap_err();
parse_inputs(&MockOptions::new( parse_inputs(&MockOptions::new(
vec!["10", "10", "10", "10"], vec!["10", "10", "10", "10"],
vec!["traditional"], vec!["traditional"],
)).unwrap_err(); ))
.unwrap_err();
} }
fn parse_offset_operand_str(s: &str) -> Result<usize, &'static str> { fn parse_offset_operand_str(s: &str) -> Result<usize, &'static str> {

View file

@ -1,7 +1,7 @@
use multifilereader::HasError;
use std::cmp; use std::cmp;
use std::io; use std::io;
use std::io::Read; use std::io::Read;
use multifilereader::HasError;
/// When a large number of bytes must be skipped, it will be read into a /// 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. /// dynamically allocated buffer. The buffer will be limited to this size.
@ -21,11 +21,7 @@ impl<R> PartialReader<R> {
/// `skip` bytes, and limits the output to `limit` bytes. Set `limit` /// `skip` bytes, and limits the output to `limit` bytes. Set `limit`
/// to `None` if there should be no limit. /// to `None` if there should be no limit.
pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self { pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self {
PartialReader { PartialReader { inner, skip, limit }
inner,
skip,
limit,
}
} }
} }
@ -77,9 +73,9 @@ impl<R: HasError> HasError for PartialReader<R> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::io::{Cursor, ErrorKind, Read};
use std::error::Error;
use mockstream::*; use mockstream::*;
use std::error::Error;
use std::io::{Cursor, ErrorKind, Read};
#[test] #[test]
fn test_read_without_limits() { fn test_read_without_limits() {

View file

@ -1,8 +1,8 @@
//! Contains the trait `PeekRead` and type `PeekReader` implementing it. //! Contains the trait `PeekRead` and type `PeekReader` implementing it.
use multifilereader::HasError;
use std::io; use std::io;
use std::io::{Read, Write}; use std::io::{Read, Write};
use multifilereader::HasError;
/// A trait which supplies a function to peek into a stream without /// A trait which supplies a function to peek into a stream without
/// actually reading it. /// actually reading it.

View file

@ -1,5 +1,5 @@
use std::str::from_utf8;
use formatteriteminfo::*; use formatteriteminfo::*;
use std::str::from_utf8;
pub static FORMAT_ITEM_A: FormatterItemInfo = FormatterItemInfo { pub static FORMAT_ITEM_A: FormatterItemInfo = FormatterItemInfo {
byte_size: 1, byte_size: 1,

View file

@ -1,8 +1,8 @@
use std::num::FpCategory; use formatteriteminfo::*;
use half::f16; use half::f16;
use std::f32; use std::f32;
use std::f64; use std::f64;
use formatteriteminfo::*; use std::num::FpCategory;
pub static FORMAT_ITEM_F16: FormatterItemInfo = FormatterItemInfo { pub static FORMAT_ITEM_F16: FormatterItemInfo = FormatterItemInfo {
byte_size: 2, byte_size: 2,

View file

@ -1,11 +1,23 @@
use formatteriteminfo::*; use formatteriteminfo::*;
/// format string to print octal using `int_writer_unsigned` /// 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` /// format string to print hexadecimal using `int_writer_unsigned`
macro_rules! HEX { () => { " {:0width$x}" }} macro_rules! HEX {
() => {
" {:0width$x}"
};
}
/// format string to print decimal using `int_writer_unsigned` or `int_writer_signed` /// format string to print decimal using `int_writer_unsigned` or `int_writer_signed`
macro_rules! DEC { () => { " {:width$}" }} macro_rules! DEC {
() => {
" {:width$}"
};
}
/// defines a static struct of type `FormatterItemInfo` called `$NAME` /// defines a static struct of type `FormatterItemInfo` called `$NAME`
/// ///
@ -15,9 +27,7 @@ macro_rules! DEC { () => { " {:width$}" }}
macro_rules! int_writer_unsigned { macro_rules! int_writer_unsigned {
($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => { ($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => {
fn $function(p: u64) -> String { fn $function(p: u64) -> String {
format!($format_str, format!($format_str, p, width = $print_width - 1)
p,
width = $print_width - 1)
} }
pub static $NAME: FormatterItemInfo = FormatterItemInfo { pub static $NAME: FormatterItemInfo = FormatterItemInfo {
@ -25,7 +35,7 @@ macro_rules! int_writer_unsigned {
print_width: $print_width, print_width: $print_width,
formatter: FormatWriter::IntWriter($function), formatter: FormatWriter::IntWriter($function),
}; };
} };
} }
/// defines a static struct of type `FormatterItemInfo` called `$NAME` /// defines a static struct of type `FormatterItemInfo` called `$NAME`
@ -37,9 +47,7 @@ macro_rules! int_writer_signed {
($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => { ($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => {
fn $function(p: u64) -> String { fn $function(p: u64) -> String {
let s = sign_extend(p, $byte_size); let s = sign_extend(p, $byte_size);
format!($format_str, format!($format_str, s, width = $print_width - 1)
s,
width = $print_width - 1)
} }
pub static $NAME: FormatterItemInfo = FormatterItemInfo { pub static $NAME: FormatterItemInfo = FormatterItemInfo {
@ -47,7 +55,7 @@ macro_rules! int_writer_signed {
print_width: $print_width, print_width: $print_width,
formatter: FormatWriter::IntWriter($function), formatter: FormatWriter::IntWriter($function),
}; };
} };
} }
/// Extends a signed number in `item` of `itembytes` bytes into a (signed) i64 /// Extends a signed number in `item` of `itembytes` bytes into a (signed) i64

View file

@ -14,9 +14,9 @@ extern crate getopts;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use std::fs::File;
use std::io::{stdin, BufRead, BufReader, Read}; use std::io::{stdin, BufRead, BufReader, Read};
use std::iter::repeat; use std::iter::repeat;
use std::fs::File;
use std::path::Path; use std::path::Path;
static NAME: &str = "paste"; static NAME: &str = "paste";
@ -60,7 +60,9 @@ FILE, separated by TABs, to standard output.",
println!("{} {}", NAME, VERSION); println!("{} {}", NAME, VERSION);
} else { } else {
let serial = matches.opt_present("serial"); let serial = matches.opt_present("serial");
let delimiters = matches.opt_str("delimiters").unwrap_or_else(|| "\t".to_owned()); let delimiters = matches
.opt_str("delimiters")
.unwrap_or_else(|| "\t".to_owned());
paste(matches.free, serial, delimiters); paste(matches.free, serial, delimiters);
} }

View file

@ -89,7 +89,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
let mut res = if matches.free.is_empty() { let mut res = if matches.free.is_empty() {
show_error!("missing operand\nTry {} --help for more information", NAME); show_error!("missing operand\nTry {} --help for more information", NAME);
false false
} else { true }; } else {
true
};
// free strings are path operands // free strings are path operands
// FIXME: TCS, seems inefficient and overly verbose (?) // FIXME: TCS, seems inefficient and overly verbose (?)
for p in matches.free { for p in matches.free {
@ -233,12 +235,14 @@ fn check_searchable(path: &str) -> bool {
// we use lstat, just like the original implementation // we use lstat, just like the original implementation
match fs::symlink_metadata(path) { match fs::symlink_metadata(path) {
Ok(_) => true, Ok(_) => true,
Err(e) => if e.kind() == ErrorKind::NotFound { Err(e) => {
true if e.kind() == ErrorKind::NotFound {
} else { true
writeln!(&mut std::io::stderr(), "{}", e); } else {
false writeln!(&mut std::io::stderr(), "{}", e);
}, false
}
}
} }
} }

View file

@ -11,9 +11,9 @@
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use uucore::utmpx::{self, time, Utmpx};
use uucore::libc::S_IWGRP;
use uucore::entries::{Locate, Passwd}; use uucore::entries::{Locate, Passwd};
use uucore::libc::S_IWGRP;
use uucore::utmpx::{self, time, Utmpx};
use std::io::prelude::*; use std::io::prelude::*;
use std::io::BufReader; use std::io::BufReader;
@ -291,7 +291,7 @@ impl Pinky {
if self.names.is_empty() { if self.names.is_empty() {
self.print_entry(&ut) self.print_entry(&ut)
} else if self.names.iter().any(|n| n.as_str() == ut.user()) { } else if self.names.iter().any(|n| n.as_str() == ut.user()) {
self.print_entry(&ut); self.print_entry(&ut);
} }
} }
} }

View file

@ -1,7 +1,7 @@
//! stdio convenience fns //! stdio convenience fns
use std::io::{stderr, stdout, Write};
use std::env; use std::env;
use std::io::{stderr, stdout, Write};
pub const EXIT_OK: i32 = 0; pub const EXIT_OK: i32 = 0;
pub const EXIT_ERR: i32 = 1; pub const EXIT_ERR: i32 = 1;

View file

@ -5,13 +5,13 @@
//! 2. feeds remaining arguments into function //! 2. feeds remaining arguments into function
//! that prints tokens. //! that prints tokens.
use cli;
use itertools::put_back_n;
use std::iter::Peekable; use std::iter::Peekable;
use std::slice::Iter; use std::slice::Iter;
use itertools::put_back_n; use tokenize::sub::Sub;
use cli;
use tokenize::token::{Token, Tokenizer}; use tokenize::token::{Token, Tokenizer};
use tokenize::unescaped_text::UnescapedText; use tokenize::unescaped_text::UnescapedText;
use tokenize::sub::Sub;
pub struct Memo { pub struct Memo {
tokens: Vec<Box<dyn Token>>, tokens: Vec<Box<dyn Token>>,

View file

@ -1,5 +1,5 @@
pub mod token;
pub mod sub;
pub mod unescaped_text;
#[allow(clippy::module_inception)] #[allow(clippy::module_inception)]
mod num_format; mod num_format;
pub mod sub;
pub mod token;
pub mod unescaped_text;

View file

@ -1,10 +1,10 @@
//! Primitives used by num_format and sub_modules. //! Primitives used by num_format and sub_modules.
//! never dealt with above (e.g. Sub Tokenizer never uses these) //! 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 super::format_field::FormatField;
use cli;
use itertools::{put_back_n, PutBackN};
use std::str::Chars;
// contains the rough ingredients to final // contains the rough ingredients to final
// output for a number, organized together // output for a number, organized together

View file

@ -1,5 +1,4 @@
#[cfg(test)] #[cfg(test)]
use super::*; use super::*;
#[test] #[test]

View file

@ -1,9 +1,9 @@
//! formatter for %a %F C99 Hex-floating-point subs //! formatter for %a %F C99 Hex-floating-point subs
use super::super::format_field::FormatField; use super::super::format_field::FormatField;
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
use super::float_common::{primitive_to_str_common, FloatAnalysis};
use super::base_conv; use super::base_conv;
use super::base_conv::RadixDef; use super::base_conv::RadixDef;
use super::float_common::{primitive_to_str_common, FloatAnalysis};
pub struct CninetyNineHexFloatf { pub struct CninetyNineHexFloatf {
as_num: f64, as_num: f64,

View file

@ -28,9 +28,9 @@ fn has_enough_digits(
false //undecidable without converting false //undecidable without converting
} }
} else if hex_input { } else if hex_input {
((((string_position - 1) - starting_position) * 9) / 8 >= limit) ((((string_position - 1) - starting_position) * 9) / 8 >= limit)
} else { } else {
((string_position - 1) - starting_position >= limit) ((string_position - 1) - starting_position >= limit)
} }
} }
@ -72,7 +72,8 @@ impl FloatAnalysis {
} }
} }
} }
if ret.decimal_pos.is_some() && pos_before_first_nonzero_after_decimal.is_none() if ret.decimal_pos.is_some()
&& pos_before_first_nonzero_after_decimal.is_none()
&& e != '0' && e != '0'
{ {
pos_before_first_nonzero_after_decimal = Some(i - 1); pos_before_first_nonzero_after_decimal = Some(i - 1);
@ -180,10 +181,7 @@ fn round_terminal_digit(
if position < after_dec.len() { if position < after_dec.len() {
let digit_at_pos: char; let digit_at_pos: char;
{ {
digit_at_pos = (&after_dec[position..=position]) digit_at_pos = (&after_dec[position..=position]).chars().next().expect("");
.chars()
.next()
.expect("");
} }
if let '5'..='9' = digit_at_pos { if let '5'..='9' = digit_at_pos {
let (new_after_dec, finished_in_dec) = _round_str_from(&after_dec, position); let (new_after_dec, finished_in_dec) = _round_str_from(&after_dec, position);

View file

@ -1,11 +1,12 @@
//! formatter for unsigned and signed int subs //! formatter for unsigned and signed int subs
//! unsigned ints: %X %x (hex u64) %o (octal u64) %u (base ten u64) //! unsigned ints: %X %x (hex u64) %o (octal u64) %u (base ten u64)
//! signed ints: %i %d (both base ten i64) //! signed ints: %i %d (both base ten i64)
use std::u64;
use std::i64;
use super::super::format_field::FormatField; use super::super::format_field::FormatField;
use super::super::formatter::{get_it_at, warn_incomplete_conv, Base, FormatPrimitive, Formatter, use super::super::formatter::{
InPrefix}; get_it_at, warn_incomplete_conv, Base, FormatPrimitive, Formatter, InPrefix,
};
use std::i64;
use std::u64;
pub struct Intf { pub struct Intf {
a: u32, a: u32,

View file

@ -1,7 +1,7 @@
pub mod intf; mod base_conv;
pub mod floatf;
pub mod cninetyninehexfloatf; pub mod cninetyninehexfloatf;
pub mod scif;
pub mod decf; pub mod decf;
mod float_common; mod float_common;
mod base_conv; pub mod floatf;
pub mod intf;
pub mod scif;

View file

@ -1,15 +1,15 @@
//! handles creating printed output for numeric substitutions //! handles creating printed output for numeric substitutions
use std::env;
use std::vec::Vec;
use cli;
use super::format_field::{FieldType, FormatField}; use super::format_field::{FieldType, FormatField};
use super::formatter::{Base, FormatPrimitive, Formatter, InPrefix}; 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::cninetyninehexfloatf::CninetyNineHexFloatf;
use super::formatters::scif::Scif;
use super::formatters::decf::Decf; use super::formatters::decf::Decf;
use super::formatters::floatf::Floatf;
use super::formatters::intf::Intf;
use super::formatters::scif::Scif;
use cli;
use std::env;
use std::vec::Vec;
pub fn warn_expected_numeric(pf_arg: &str) { pub fn warn_expected_numeric(pf_arg: &str) {
// important: keep println here not print // important: keep println here not print
@ -21,13 +21,15 @@ pub fn warn_expected_numeric(pf_arg: &str) {
fn warn_char_constant_ign(remaining_bytes: Vec<u8>) { fn warn_char_constant_ign(remaining_bytes: Vec<u8>) {
match env::var("POSIXLY_CORRECT") { match env::var("POSIXLY_CORRECT") {
Ok(_) => {} Ok(_) => {}
Err(e) => if let env::VarError::NotPresent = e { Err(e) => {
cli::err_msg(&format!( if let env::VarError::NotPresent = e {
"warning: {:?}: character(s) following character \ cli::err_msg(&format!(
constant have been ignored", "warning: {:?}: character(s) following character \
&*remaining_bytes constant have been ignored",
)); &*remaining_bytes
}, ));
}
}
} }
} }
@ -63,9 +65,7 @@ fn get_provided(str_in_opt: Option<&String>) -> Option<u8> {
}) })
} }
// first byte is not quote // first byte is not quote
_ => { _ => None, // no first byte
None
} // no first byte
} }
} else { } else {
Some(0 as u8) Some(0 as u8)

View file

@ -3,16 +3,16 @@
//! it is created by Sub's implementation of the Tokenizer trait //! it is created by Sub's implementation of the Tokenizer trait
//! Subs which have numeric field chars make use of the num_format //! Subs which have numeric field chars make use of the num_format
//! submodule //! 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::format_field::{FieldType, FormatField};
use super::num_format::num_format; 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; // use std::collections::HashSet;
fn err_conv(sofar: &str) { fn err_conv(sofar: &str) {
@ -155,22 +155,10 @@ impl SubParser {
// though, as we want to mimic the original behavior of printing // though, as we want to mimic the original behavior of printing
// the field as interpreted up until the error in the field. // 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 let mut legal_fields = vec![
'b', // 'a', 'A', //c99 hex float implementation not yet complete
'c', 'b', 'c', 'd', 'e', 'E', 'f', 'F', 'g', 'G', 'i', 'o', 's', 'u', 'x', 'X',
'd', ];
'e',
'E',
'f',
'F',
'g',
'G',
'i',
'o',
's',
'u',
'x',
'X'];
let mut specifiers = vec!['h', 'j', 'l', 'L', 't', 'z']; let mut specifiers = vec!['h', 'j', 'l', 'L', 't', 'z'];
legal_fields.sort(); legal_fields.sort();
specifiers.sort(); specifiers.sort();
@ -289,8 +277,12 @@ impl SubParser {
} }
} }
} else { } else {
if let Some(x) = n_ch { it.put_back(x) }; if let Some(x) = n_ch {
if let Some(x) = preface { it.put_back(x) }; it.put_back(x)
};
if let Some(x) = preface {
it.put_back(x)
};
false false
} }
} }
@ -302,7 +294,8 @@ impl SubParser {
|| (field_char == 'c' || (field_char == 'c'
&& (self.min_width_tmp == Some(String::from("0")) || self.past_decimal)) && (self.min_width_tmp == Some(String::from("0")) || self.past_decimal))
|| (field_char == 'b' || (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())) || self.second_field_tmp.is_some()))
{ {
err_conv(&self.text_so_far); err_conv(&self.text_so_far);
@ -393,8 +386,7 @@ impl token::Token for Sub {
"{}", "{}",
match field.min_width { match field.min_width {
Some(min_width) => { Some(min_width) => {
let diff: isize = let diff: isize = min_width.abs() as isize - pre_min_width.len() as isize;
min_width.abs() as isize - pre_min_width.len() as isize;
if diff > 0 { if diff > 0 {
let mut final_str = String::new(); let mut final_str = String::new();
// definitely more efficient ways // definitely more efficient ways

View file

@ -63,7 +63,9 @@ impl UnescapedText {
let leading_zeros = if eight_word { let leading_zeros = if eight_word {
preface = 'U'; preface = 'U';
8 8
} else { 4 }; } else {
4
};
let err_msg = format!( let err_msg = format!(
"invalid universal character name {0}{1:02$x}", "invalid universal character name {0}{1:02$x}",
preface, val, leading_zeros preface, val, leading_zeros

View file

@ -15,8 +15,8 @@ extern crate getopts;
extern crate uucore; extern crate uucore;
use std::env; use std::env;
use std::path::{Path, PathBuf};
use std::io; use std::io;
use std::path::{Path, PathBuf};
static NAME: &str = "pwd"; static NAME: &str = "pwd";
static VERSION: &str = env!("CARGO_PKG_VERSION"); static VERSION: &str = env!("CARGO_PKG_VERSION");
@ -30,7 +30,8 @@ pub fn absolute_path(path: &Path) -> io::Result<PathBuf> {
.as_path() .as_path()
.to_string_lossy() .to_string_lossy()
.trim_start_matches(r"\\?\"), .trim_start_matches(r"\\?\"),
).to_path_buf(); )
.to_path_buf();
Ok(path_buf) Ok(path_buf)
} }

View file

@ -76,7 +76,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
CanonicalizeMode::Existing CanonicalizeMode::Existing
} else if matches.opt_present("canonicalize-missing") { } else if matches.opt_present("canonicalize-missing") {
CanonicalizeMode::Missing CanonicalizeMode::Missing
} else { CanonicalizeMode::None }; } else {
CanonicalizeMode::None
};
let files = matches.free; let files = matches.free;
if files.is_empty() { if files.is_empty() {

View file

@ -16,12 +16,12 @@ extern crate walkdir;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use remove_dir_all::remove_dir_all;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fs; use std::fs;
use std::io::{stderr, stdin, BufRead, Write}; use std::io::{stderr, stdin, BufRead, Write};
use std::ops::BitOr; use std::ops::BitOr;
use std::path::Path; use std::path::Path;
use remove_dir_all::remove_dir_all;
use walkdir::{DirEntry, WalkDir}; use walkdir::{DirEntry, WalkDir};
#[derive(Eq, PartialEq, Clone, Copy)] #[derive(Eq, PartialEq, Clone, Copy)]
@ -181,7 +181,8 @@ fn remove(files: Vec<String>, options: Options) -> bool {
false false
} }
} }
}.bitor(had_err); }
.bitor(had_err);
} }
had_err had_err
@ -247,9 +248,11 @@ fn remove_dir(path: &Path, options: &Options) -> bool {
}; };
if response { if response {
match fs::remove_dir(path) { match fs::remove_dir(path) {
Ok(_) => if options.verbose { Ok(_) => {
println!("removed '{}'", path.display()); if options.verbose {
}, println!("removed '{}'", path.display());
}
}
Err(e) => { Err(e) => {
show_error!("removing '{}': {}", path.display(), e); show_error!("removing '{}': {}", path.display(), e);
return true; return true;
@ -268,9 +271,11 @@ fn remove_file(path: &Path, options: &Options) -> bool {
}; };
if response { if response {
match fs::remove_file(path) { match fs::remove_file(path) {
Ok(_) => if options.verbose { Ok(_) => {
println!("removed '{}'", path.display()); if options.verbose {
}, println!("removed '{}'", path.display());
}
}
Err(e) => { Err(e) => {
show_error!("removing '{}': {}", path.display(), e); show_error!("removing '{}': {}", path.display(), e);
return true; return true;
@ -320,5 +325,6 @@ fn is_symlink_dir(metadata: &fs::Metadata) -> bool {
pub type DWORD = c_ulong; pub type DWORD = c_ulong;
pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10; 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)
} }

View file

@ -96,10 +96,7 @@ fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<Stri
options.separator = sep; options.separator = sep;
let next = chiter.next(); let next = chiter.next();
if let Some(n) = next { if let Some(n) = next {
show_error!( show_error!("unexpected character ('{}')", n);
"unexpected character ('{}')",
n
);
return Err(1); return Err(1);
} }
} }
@ -113,10 +110,7 @@ fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<Stri
options.terminator = Some(term); options.terminator = Some(term);
let next = chiter.next(); let next = chiter.next();
if let Some(n) = next { if let Some(n) = next {
show_error!( show_error!("unexpected character ('{}')", n);
"unexpected character ('{}')",
n
);
return Err(1); return Err(1);
} }
} }
@ -137,7 +131,7 @@ fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<Stri
} }
} }
}; };
}; }
Ok(seq_args) Ok(seq_args)
} }

View file

@ -18,8 +18,8 @@ use std::cell::{Cell, RefCell};
use std::fs; use std::fs;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io; use std::io;
use std::io::SeekFrom;
use std::io::prelude::*; use std::io::prelude::*;
use std::io::SeekFrom;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[macro_use] #[macro_use]
@ -473,7 +473,8 @@ fn wipe_file(
} }
} }
// size is an optional argument for exactly how many bytes we want to shred // 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 do_pass(&mut file, path, *pass_type, size, exact).expect("File write pass failed");
// Ignore failed writes; just keep trying
} }
} }

View file

@ -130,7 +130,10 @@ With no FILE, or when FILE is -, read standard input.",
} }
Mode::InputRange((b, e)) => { Mode::InputRange((b, e)) => {
let rvec = (b..e).map(|x| format!("{}", x)).collect::<Vec<String>>(); let rvec = (b..e).map(|x| format!("{}", x)).collect::<Vec<String>>();
let mut rvec = rvec.iter().map(std::string::String::as_bytes).collect::<Vec<&[u8]>>(); let mut rvec = rvec
.iter()
.map(std::string::String::as_bytes)
.collect::<Vec<&[u8]>>();
shuf_bytes(&mut rvec, repeat, count, sep, output, random); shuf_bytes(&mut rvec, repeat, count, sep, output, random);
} }
Mode::Default => { Mode::Default => {

View file

@ -63,12 +63,14 @@ specified by the sum of their values.",
} }
fn sleep(args: Vec<String>) { fn sleep(args: Vec<String>) {
let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg| { let sleep_dur =
match uucore::parse_time::from_str(&arg[..]) { args.iter().fold(
Ok(m) => m + result, Duration::new(0, 0),
Err(f) => crash!(1, "{}", f), |result, arg| match uucore::parse_time::from_str(&arg[..]) {
} Ok(m) => m + result,
}); Err(f) => crash!(1, "{}", f),
},
);
thread::sleep(sleep_dur); thread::sleep(sleep_dur);
} }

View file

@ -16,15 +16,15 @@ extern crate itertools;
#[macro_use] #[macro_use]
extern crate uucore; extern crate uucore;
use itertools::Itertools;
use semver::Version;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::BinaryHeap; use std::collections::BinaryHeap;
use std::fs::File; use std::fs::File;
use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Lines, Read, Write}; use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Lines, Read, Write};
use std::mem::replace; use std::mem::replace;
use std::path::Path; use std::path::Path;
use uucore::fs::is_stdin_interactive; use uucore::fs::is_stdin_interactive; // for Iterator::dedup()
use semver::Version;
use itertools::Itertools; // for Iterator::dedup()
static NAME: &str = "sort"; static NAME: &str = "sort";
static VERSION: &str = env!("CARGO_PKG_VERSION"); static VERSION: &str = env!("CARGO_PKG_VERSION");
@ -380,13 +380,11 @@ fn permissive_f64_parse(a: &str) -> f64 {
// GNU sort treats "NaN" as non-number in numeric, so it needs special care. // GNU sort treats "NaN" as non-number in numeric, so it needs special care.
match a.split_whitespace().next() { match a.split_whitespace().next() {
None => std::f64::NEG_INFINITY, None => std::f64::NEG_INFINITY,
Some(sa) => { Some(sa) => match sa.parse::<f64>() {
match sa.parse::<f64>() { Ok(a) if a.is_nan() => std::f64::NEG_INFINITY,
Ok(a) if a.is_nan() => std::f64::NEG_INFINITY, Ok(a) => a,
Ok(a) => a, Err(_) => std::f64::NEG_INFINITY,
Err(_) => std::f64::NEG_INFINITY, },
}
}
} }
} }
@ -467,7 +465,8 @@ enum Month {
/// Parse the beginning string into a Month, returning Month::Unknown on errors. /// Parse the beginning string into a Month, returning Month::Unknown on errors.
fn month_parse(line: &str) -> Month { fn month_parse(line: &str) -> Month {
match line.split_whitespace() match line
.split_whitespace()
.next() .next()
.unwrap() .unwrap()
.to_uppercase() .to_uppercase()

View file

@ -319,7 +319,8 @@ fn split(settings: &Settings) -> i32 {
num_prefix(fileno, settings.suffix_length) num_prefix(fileno, settings.suffix_length)
} else { } else {
str_prefix(fileno, settings.suffix_length) str_prefix(fileno, settings.suffix_length)
}.as_ref(), }
.as_ref(),
); );
if fileno != 0 { if fileno != 0 {

View file

@ -10,9 +10,11 @@ pub use super::uucore::libc;
extern crate time; extern crate time;
use self::time::Timespec; use self::time::Timespec;
pub use libc::{c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, pub use libc::{
S_IFREG, S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG,
S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR}; 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 { pub trait BirthTime {
fn pretty_birth(&self) -> String; fn pretty_birth(&self) -> String;
@ -40,9 +42,9 @@ impl BirthTime for Metadata {
#[macro_export] #[macro_export]
macro_rules! has { macro_rules! has {
($mode:expr, $perm:expr) => ( ($mode:expr, $perm:expr) => {
$mode & $perm != 0 $mode & $perm != 0
) };
} }
pub fn pretty_time(sec: i64, nsec: i64) -> String { pub fn pretty_time(sec: i64, nsec: i64) -> String {
@ -137,22 +139,44 @@ pub fn pretty_access(mode: mode_t) -> String {
result result
} }
use std::mem;
use std::path::Path;
use std::borrow::Cow; use std::borrow::Cow;
use std::ffi::CString;
use std::convert::{AsRef, From}; use std::convert::{AsRef, From};
use std::error::Error; use std::error::Error;
use std::ffi::CString;
use std::io::Error as IOError; use std::io::Error as IOError;
use std::mem;
use std::path::Path;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android", target_os = "freebsd"))] #[cfg(any(
target_os = "linux",
target_os = "macos",
target_os = "android",
target_os = "freebsd"
))]
use libc::statfs as Sstatfs; 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; 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; 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; use libc::statvfs as statfs_fn;
pub trait FsMeta { pub trait FsMeta {
@ -219,7 +243,8 @@ impl FsMeta for Sstatfs {
// struct statvfs, containing an unsigned long f_fsid // struct statvfs, containing an unsigned long f_fsid
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "linux"))] #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "linux"))]
fn fsid(&self) -> u64 { fn fsid(&self) -> u64 {
let f_fsid: &[u32; 2] = unsafe { &*(&self.f_fsid as *const uucore::libc::fsid_t as *const [u32; 2]) }; let f_fsid: &[u32; 2] =
unsafe { &*(&self.f_fsid as *const uucore::libc::fsid_t as *const [u32; 2]) };
(u64::from(f_fsid[0])) << 32 | u64::from(f_fsid[1]) (u64::from(f_fsid[0])) << 32 | u64::from(f_fsid[1])
} }
#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "linux")))] #[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "linux")))]
@ -261,10 +286,10 @@ where
Err(CString::from_raw(strerror(errno)) Err(CString::from_raw(strerror(errno))
.into_string() .into_string()
.unwrap_or_else(|_| "Unknown Error".to_owned())) .unwrap_or_else(|_| "Unknown Error".to_owned()))
}
} }
} }
} }
}
Err(e) => Err(e.description().to_owned()), Err(e) => Err(e.description().to_owned()),
} }
} }

View file

@ -19,29 +19,31 @@ pub use fsext::*;
extern crate uucore; extern crate uucore;
use uucore::entries; use uucore::entries;
use std::{cmp, fs, iter}; use std::borrow::Cow;
use std::convert::AsRef;
use std::fs::File; use std::fs::File;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::borrow::Cow;
use std::os::unix::fs::{FileTypeExt, MetadataExt}; use std::os::unix::fs::{FileTypeExt, MetadataExt};
use std::path::Path; use std::path::Path;
use std::convert::AsRef; use std::{cmp, fs, iter};
macro_rules! check_bound { macro_rules! check_bound {
($str: ident, $bound:expr, $beg: expr, $end: expr) => ( ($str: ident, $bound:expr, $beg: expr, $end: expr) => {
if $end >= $bound { if $end >= $bound {
return Err(format!("{}: invalid directive", &$str[$beg..$end])); return Err(format!("{}: invalid directive", &$str[$beg..$end]));
} }
};
)
} }
macro_rules! fill_string { macro_rules! fill_string {
($str: ident, $c: expr, $cnt: expr) => ( ($str: ident, $c: expr, $cnt: expr) => {
iter::repeat($c).take($cnt).map(|c| $str.push(c)).all(|_| true) iter::repeat($c)
) .take($cnt)
.map(|c| $str.push(c))
.all(|_| true)
};
} }
macro_rules! extend_digits { macro_rules! extend_digits {
($str: expr, $min: expr) => ( ($str: expr, $min: expr) => {
if $min > $str.len() { if $min > $str.len() {
let mut pad = String::with_capacity($min); let mut pad = String::with_capacity($min);
fill_string!(pad, '0', $min - $str.len()); fill_string!(pad, '0', $min - $str.len());
@ -50,10 +52,10 @@ macro_rules! extend_digits {
} else { } else {
$str.into() $str.into()
} }
) };
} }
macro_rules! pad_and_print { 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 $str.len() < $width {
if $left { if $left {
$result.push_str($str.as_ref()); $result.push_str($str.as_ref());
@ -66,7 +68,7 @@ macro_rules! pad_and_print {
$result.push_str($str.as_ref()); $result.push_str($str.as_ref());
} }
print!("{}", $result); print!("{}", $result);
) };
} }
macro_rules! print_adjusted { macro_rules! print_adjusted {
($str: ident, $left: expr, $width: expr, $padding: expr) => { ($str: ident, $left: expr, $width: expr, $padding: expr) => {
@ -82,7 +84,7 @@ macro_rules! print_adjusted {
field_width -= $prefix.len(); field_width -= $prefix.len();
} }
pad_and_print!(result, $str, $left, field_width, $padding); pad_and_print!(result, $str, $left, field_width, $padding);
} };
} }
static NAME: &str = "stat"; static NAME: &str = "stat";
@ -481,7 +483,11 @@ impl Stater {
let mut mount_list = reader let mut mount_list = reader
.lines() .lines()
.filter_map(std::result::Result::ok) .filter_map(std::result::Result::ok)
.filter_map(|line| line.split_whitespace().nth(1).map(std::borrow::ToOwned::to_owned)) .filter_map(|line| {
line.split_whitespace()
.nth(1)
.map(std::borrow::ToOwned::to_owned)
})
.collect::<Vec<String>>(); .collect::<Vec<String>>();
// Reverse sort. The longer comes first. // Reverse sort. The longer comes first.
mount_list.sort_by(|a, b| b.cmp(a)); mount_list.sort_by(|a, b| b.cmp(a));

View file

@ -9,7 +9,7 @@ use libc::{c_char, c_int, size_t, FILE, _IOFBF, _IOLBF, _IONBF};
use std::env; use std::env;
use std::ptr; use std::ptr;
cpp!{{ cpp! {{
#include <cstdio> #include <cstdio>
extern "C" { extern "C" {

View file

@ -16,12 +16,12 @@ extern crate tempdir;
extern crate uucore; extern crate uucore;
use getopts::{Matches, Options}; use getopts::{Matches, Options};
use tempdir::TempDir;
use std::fs::File; use std::fs::File;
use std::io::{self, Write}; use std::io::{self, Write};
use std::os::unix::process::ExitStatusExt; use std::os::unix::process::ExitStatusExt;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use tempdir::TempDir;
static NAME: &str = "stdbuf"; static NAME: &str = "stdbuf";
static VERSION: &str = env!("CARGO_PKG_VERSION"); static VERSION: &str = env!("CARGO_PKG_VERSION");
@ -51,7 +51,12 @@ enum OkMsg {
Version, 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) { fn preload_strings() -> (&'static str, &'static str) {
("LD_PRELOAD", "so") ("LD_PRELOAD", "so")
} }
@ -61,7 +66,13 @@ fn preload_strings() -> (&'static str, &'static str) {
("DYLD_LIBRARY_PATH", "dylib") ("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) { fn preload_strings() -> (&'static str, &'static str) {
crash!(1, "Command not supported for this operating system!") crash!(1, "Command not supported for this operating system!")
} }

View file

@ -42,27 +42,29 @@ mod platform {
mod platform { mod platform {
extern crate kernel32; extern crate kernel32;
extern crate winapi; extern crate winapi;
use std::mem; use self::winapi::shared::minwindef;
use std::fs::OpenOptions; use self::winapi::shared::winerror;
use std::os::windows::prelude::*; use self::winapi::um::handleapi;
use uucore::wide::{FromWide, ToWide};
use self::winapi::um::winbase; use self::winapi::um::winbase;
use self::winapi::um::winnt; use self::winapi::um::winnt;
use self::winapi::shared::minwindef; use std::fs::OpenOptions;
use self::winapi::um::handleapi; use std::mem;
use self::winapi::shared::winerror; use std::os::windows::prelude::*;
use uucore::wide::{FromWide, ToWide};
unsafe fn flush_volume(name: &str) { unsafe fn flush_volume(name: &str) {
let name_wide = name.to_wide_null(); let name_wide = name.to_wide_null();
if kernel32::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED { if kernel32::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED {
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
match OpenOptions::new().write(true).open(sliced_name) { match OpenOptions::new().write(true).open(sliced_name) {
Ok(file) => if kernel32::FlushFileBuffers(file.as_raw_handle()) == 0 { Ok(file) => {
crash!( if kernel32::FlushFileBuffers(file.as_raw_handle()) == 0 {
kernel32::GetLastError() as i32, crash!(
"failed to flush file buffer" kernel32::GetLastError() as i32,
); "failed to flush file buffer"
}, );
}
}
Err(e) => crash!( Err(e) => crash!(
e.raw_os_error().unwrap_or(1), e.raw_os_error().unwrap_or(1),
"failed to create volume handle" "failed to create volume handle"

View file

@ -1,6 +1,6 @@
extern crate syscall; extern crate syscall;
use self::syscall::{Error, EPERM, ENOSYS}; use self::syscall::{Error, ENOSYS, EPERM};
pub type Pid = usize; pub type Pid = usize;

View file

@ -12,7 +12,7 @@ extern crate winapi;
use self::kernel32::{CloseHandle, OpenProcess, WaitForSingleObject}; use self::kernel32::{CloseHandle, OpenProcess, WaitForSingleObject};
use self::winapi::shared::minwindef::DWORD; 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}; use self::winapi::um::winnt::{HANDLE, SYNCHRONIZE};
pub type Pid = DWORD; pub type Pid = DWORD;

Some files were not shown because too many files have changed in this diff Show more