mirror of
https://github.com/uutils/coreutils
synced 2024-10-01 13:35:03 +00:00
cargo fmt
This commit is contained in:
parent
15722e3ace
commit
5af8503a5e
25
build.rs
25
build.rs
|
@ -16,8 +16,8 @@ pub fn main() {
|
|||
if val == "1" && key.starts_with(feature_prefix) {
|
||||
let krate = key[feature_prefix.len()..].to_lowercase();
|
||||
match krate.as_ref() {
|
||||
"default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic" | "windows" | "windows_legacy"
|
||||
| "nightly" | "test_unimplemented" => continue,
|
||||
"default" | "unix" | "redox" | "redox_generic" | "fuchsia" | "generic"
|
||||
| "windows" | "windows_legacy" | "nightly" | "test_unimplemented" => continue,
|
||||
_ => {}
|
||||
}
|
||||
crates.push(krate.to_string());
|
||||
|
@ -35,7 +35,8 @@ pub fn main() {
|
|||
fn util_map() -> UtilityMap {
|
||||
let mut map: UtilityMap = HashMap::new();\n"
|
||||
.as_bytes(),
|
||||
).unwrap();
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for krate in crates {
|
||||
cf.write_all(format!("extern crate uu_{krate};\n", krate = krate).as_bytes())
|
||||
|
@ -59,14 +60,18 @@ pub fn main() {
|
|||
map.insert(\"shake128sum\", uu_hashsum::uumain);
|
||||
map.insert(\"shake256sum\", uu_hashsum::uumain);\n"
|
||||
.as_bytes(),
|
||||
).unwrap();
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
_ => mf.write_all(
|
||||
format!(
|
||||
"map.insert(\"{krate}\", uu_{krate}::uumain);\n",
|
||||
krate = krate
|
||||
).as_bytes(),
|
||||
).unwrap(),
|
||||
_ => mf
|
||||
.write_all(
|
||||
format!(
|
||||
"map.insert(\"{krate}\", uu_{krate}::uumain);\n",
|
||||
krate = krate
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
use std::env;
|
||||
use std::io::Write;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
static TEMPLATE: &'static str = "\
|
||||
|
|
|
@ -16,8 +16,7 @@ use uucore::encoding::Format;
|
|||
mod base_common;
|
||||
|
||||
static SYNTAX: &str = "[OPTION]... [FILE]";
|
||||
static SUMMARY: &str =
|
||||
"Base32 encode or decode FILE, or standard input, to standard output.";
|
||||
static SUMMARY: &str = "Base32 encode or decode FILE, or standard input, to standard output.";
|
||||
static LONG_HELP: &str = "
|
||||
With no FILE, or when FILE is -, read standard input.
|
||||
|
||||
|
|
|
@ -16,8 +16,7 @@ use uucore::encoding::Format;
|
|||
mod base_common;
|
||||
|
||||
static SYNTAX: &str = "[OPTION]... [FILE]";
|
||||
static SUMMARY: &str =
|
||||
"Base64 encode or decode FILE, or standard input, to standard output.";
|
||||
static SUMMARY: &str = "Base64 encode or decode FILE, or standard input, to standard output.";
|
||||
static LONG_HELP: &str = "
|
||||
With no FILE, or when FILE is -, read standard input.
|
||||
|
||||
|
|
|
@ -36,13 +36,11 @@ pub fn execute(
|
|||
"COLS",
|
||||
)
|
||||
.parse(args);
|
||||
|
||||
let line_wrap = matches.opt_str("wrap").map(|s| {
|
||||
match s.parse() {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
crash!(1, "invalid wrap size: ‘{}’: {}", s, e);
|
||||
}
|
||||
|
||||
let line_wrap = matches.opt_str("wrap").map(|s| match s.parse() {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
crash!(1, "invalid wrap size: ‘{}’: {}", s, e);
|
||||
}
|
||||
});
|
||||
let ignore_garbage = matches.opt_present("ignore-garbage");
|
||||
|
@ -55,7 +53,13 @@ pub fn execute(
|
|||
|
||||
if matches.free.is_empty() || &matches.free[0][..] == "-" {
|
||||
let stdin_raw = stdin();
|
||||
handle_input(&mut stdin_raw.lock(), format, line_wrap, ignore_garbage, decode);
|
||||
handle_input(
|
||||
&mut stdin_raw.lock(),
|
||||
format,
|
||||
line_wrap,
|
||||
ignore_garbage,
|
||||
decode,
|
||||
);
|
||||
} else {
|
||||
let path = Path::new(matches.free[0].as_str());
|
||||
let file_buf = safe_unwrap!(File::open(&path));
|
||||
|
@ -73,8 +77,7 @@ fn handle_input<R: Read>(
|
|||
ignore_garbage: bool,
|
||||
decode: bool,
|
||||
) {
|
||||
let mut data = Data::new(input, format)
|
||||
.ignore_garbage(ignore_garbage);
|
||||
let mut data = Data::new(input, format).ignore_garbage(ignore_garbage);
|
||||
if let Some(wrap) = line_wrap {
|
||||
data = data.line_wrap(wrap);
|
||||
}
|
||||
|
@ -88,4 +91,4 @@ fn handle_input<R: Read>(
|
|||
Err(_) => crash!(1, "invalid input"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -168,7 +168,10 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
files.push("-".to_owned());
|
||||
}
|
||||
|
||||
let can_write_fast = !(show_tabs || show_nonprint || show_ends || squeeze_blank
|
||||
let can_write_fast = !(show_tabs
|
||||
|| show_nonprint
|
||||
|| show_ends
|
||||
|| squeeze_blank
|
||||
|| number_mode != NumberingMode::None);
|
||||
|
||||
let success = if can_write_fast {
|
||||
|
@ -190,7 +193,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
write_lines(files, &options).is_ok()
|
||||
};
|
||||
|
||||
if success { 0 } else { 1 }
|
||||
if success {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies the `InputType` of file at `path` if possible
|
||||
|
@ -205,25 +212,13 @@ fn get_input_type(path: &str) -> CatResult<InputType> {
|
|||
|
||||
match metadata(path).context(path)?.file_type() {
|
||||
#[cfg(unix)]
|
||||
ft if ft.is_block_device() =>
|
||||
{
|
||||
Ok(InputType::BlockDevice)
|
||||
}
|
||||
ft if ft.is_block_device() => Ok(InputType::BlockDevice),
|
||||
#[cfg(unix)]
|
||||
ft if ft.is_char_device() =>
|
||||
{
|
||||
Ok(InputType::CharacterDevice)
|
||||
}
|
||||
ft if ft.is_char_device() => Ok(InputType::CharacterDevice),
|
||||
#[cfg(unix)]
|
||||
ft if ft.is_fifo() =>
|
||||
{
|
||||
Ok(InputType::Fifo)
|
||||
}
|
||||
ft if ft.is_fifo() => Ok(InputType::Fifo),
|
||||
#[cfg(unix)]
|
||||
ft if ft.is_socket() =>
|
||||
{
|
||||
Ok(InputType::Socket)
|
||||
}
|
||||
ft if ft.is_socket() => Ok(InputType::Socket),
|
||||
ft if ft.is_dir() => Ok(InputType::Directory),
|
||||
ft if ft.is_file() => Ok(InputType::File),
|
||||
ft if ft.is_symlink() => Ok(InputType::SymLink),
|
||||
|
@ -282,12 +277,14 @@ fn write_fast(files: Vec<String>) -> CatResult<()> {
|
|||
|
||||
for file in files {
|
||||
match open(&file[..]) {
|
||||
Ok(mut handle) => while let Ok(n) = handle.reader.read(&mut in_buf) {
|
||||
if n == 0 {
|
||||
break;
|
||||
Ok(mut handle) => {
|
||||
while let Ok(n) = handle.reader.read(&mut in_buf) {
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
writer.write_all(&in_buf[..n]).context(&file[..])?;
|
||||
}
|
||||
writer.write_all(&in_buf[..n]).context(&file[..])?;
|
||||
},
|
||||
}
|
||||
Err(error) => {
|
||||
writeln!(&mut stderr(), "{}", error)?;
|
||||
error_count += 1;
|
||||
|
@ -421,10 +418,7 @@ fn write_to_end<W: Write>(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;
|
||||
loop {
|
||||
match in_buf
|
||||
.iter()
|
||||
.position(|c| *c == b'\n' || *c == b'\t')
|
||||
{
|
||||
match in_buf.iter().position(|c| *c == b'\n' || *c == b'\t') {
|
||||
Some(p) => {
|
||||
writer.write_all(&in_buf[..p]).unwrap();
|
||||
if in_buf[p] == b'\n' {
|
||||
|
@ -458,7 +452,8 @@ fn write_nonprint_to_end<W: Write>(in_buf: &[u8], writer: &mut W, tab: &[u8]) ->
|
|||
128..=159 => writer.write_all(&[b'M', b'-', b'^', byte - 64]),
|
||||
160..=254 => writer.write_all(&[b'M', b'-', byte - 128]),
|
||||
_ => writer.write_all(&[b'M', b'-', b'^', 63]),
|
||||
}.unwrap();
|
||||
}
|
||||
.unwrap();
|
||||
count += 1;
|
||||
}
|
||||
if count != in_buf.len() {
|
||||
|
|
|
@ -10,15 +10,15 @@
|
|||
|
||||
#[macro_use]
|
||||
extern crate uucore;
|
||||
use uucore::libc::{self, gid_t, lchown};
|
||||
pub use uucore::entries;
|
||||
use uucore::fs::resolve_relative_path;
|
||||
use uucore::libc::{self, gid_t, lchown};
|
||||
|
||||
extern crate walkdir;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use std::io::Result as IOResult;
|
||||
use std::io::Error as IOError;
|
||||
use std::io::Result as IOResult;
|
||||
|
||||
use std::fs;
|
||||
use std::fs::Metadata;
|
||||
|
@ -183,12 +183,12 @@ struct Chgrper {
|
|||
}
|
||||
|
||||
macro_rules! unwrap {
|
||||
($m:expr, $e:ident, $err:block) => (
|
||||
($m:expr, $e:ident, $err:block) => {
|
||||
match $m {
|
||||
Ok(meta) => meta,
|
||||
Err($e) => $err,
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
impl Chgrper {
|
||||
|
|
|
@ -19,10 +19,10 @@ extern crate uucore;
|
|||
use std::fs;
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
use std::path::Path;
|
||||
use walker::Walker;
|
||||
use uucore::fs::display_permissions_unix;
|
||||
#[cfg(not(windows))]
|
||||
use uucore::mode;
|
||||
use uucore::fs::display_permissions_unix;
|
||||
use walker::Walker;
|
||||
|
||||
const NAME: &str = "chmod";
|
||||
static SUMMARY: &str = "Change the mode of each FILE to MODE.
|
||||
|
@ -39,14 +39,31 @@ pub fn uumain(mut args: Vec<String>) -> i32 {
|
|||
NAME
|
||||
);
|
||||
let mut opts = new_coreopts!(&syntax, SUMMARY, LONG_HELP);
|
||||
opts.optflag("c", "changes", "like verbose but report only when a change is made")
|
||||
// TODO: support --silent (can be done using clap)
|
||||
.optflag("f", "quiet", "suppress most error messages")
|
||||
.optflag("v", "verbose", "output a diagnostic for every file processed")
|
||||
.optflag("", "no-preserve-root", "do not treat '/' specially (the default)")
|
||||
.optflag("", "preserve-root", "fail to operate recursively on '/'")
|
||||
.optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE")
|
||||
.optflag("R", "recursive", "change files and directories recursively");
|
||||
opts.optflag(
|
||||
"c",
|
||||
"changes",
|
||||
"like verbose but report only when a change is made",
|
||||
)
|
||||
// TODO: support --silent (can be done using clap)
|
||||
.optflag("f", "quiet", "suppress most error messages")
|
||||
.optflag(
|
||||
"v",
|
||||
"verbose",
|
||||
"output a diagnostic for every file processed",
|
||||
)
|
||||
.optflag(
|
||||
"",
|
||||
"no-preserve-root",
|
||||
"do not treat '/' specially (the default)",
|
||||
)
|
||||
.optflag("", "preserve-root", "fail to operate recursively on '/'")
|
||||
.optopt(
|
||||
"",
|
||||
"reference",
|
||||
"use RFILE's mode instead of MODE values",
|
||||
"RFILE",
|
||||
)
|
||||
.optflag("R", "recursive", "change files and directories recursively");
|
||||
|
||||
// sanitize input for - at beginning (e.g. chmod -x testfile). Remove
|
||||
// the option and save it for later, after parsing is finished.
|
||||
|
@ -148,17 +165,19 @@ impl Chmoder {
|
|||
// on Windows OsStrings cannot be built out of non-UTF-8 chars. One
|
||||
// possible fix is to use CStrings rather than Strings in the args
|
||||
// to chmod() and chmod_file().
|
||||
r = self.chmod(
|
||||
walk_dir
|
||||
.filter_map(|x| match x {
|
||||
Ok(o) => match o.path().into_os_string().to_str() {
|
||||
Some(s) => Some(s.to_owned()),
|
||||
None => None,
|
||||
},
|
||||
Err(_) => None,
|
||||
})
|
||||
.collect(),
|
||||
).and(r);
|
||||
r = self
|
||||
.chmod(
|
||||
walk_dir
|
||||
.filter_map(|x| match x {
|
||||
Ok(o) => match o.path().into_os_string().to_str() {
|
||||
Some(s) => Some(s.to_owned()),
|
||||
None => None,
|
||||
},
|
||||
Err(_) => None,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.and(r);
|
||||
r = self.chmod_file(&file, filename).and(r);
|
||||
}
|
||||
} else {
|
||||
|
@ -230,7 +249,12 @@ impl Chmoder {
|
|||
fn change_file(&self, fperm: u32, mode: u32, file: &Path, path: &str) -> Result<(), i32> {
|
||||
if fperm == mode {
|
||||
if self.verbose && !self.changes {
|
||||
show_info!("mode of '{}' retained as {:o} ({})", file.display(), fperm, display_permissions_unix(fperm));
|
||||
show_info!(
|
||||
"mode of '{}' retained as {:o} ({})",
|
||||
file.display(),
|
||||
fperm,
|
||||
display_permissions_unix(fperm)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
} else if let Err(err) =
|
||||
|
|
|
@ -11,9 +11,9 @@
|
|||
|
||||
#[macro_use]
|
||||
extern crate uucore;
|
||||
use uucore::libc::{self, gid_t, lchown, uid_t};
|
||||
pub use uucore::entries::{self, Group, Locate, Passwd};
|
||||
use uucore::fs::resolve_relative_path;
|
||||
use uucore::libc::{self, gid_t, lchown, uid_t};
|
||||
|
||||
extern crate walkdir;
|
||||
use walkdir::WalkDir;
|
||||
|
@ -24,8 +24,8 @@ use std::os::unix::fs::MetadataExt;
|
|||
use std::io;
|
||||
use std::io::Result as IOResult;
|
||||
|
||||
use std::path::Path;
|
||||
use std::convert::AsRef;
|
||||
use std::path::Path;
|
||||
|
||||
use std::ffi::CString;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
@ -253,12 +253,12 @@ struct Chowner {
|
|||
}
|
||||
|
||||
macro_rules! unwrap {
|
||||
($m:expr, $e:ident, $err:block) => (
|
||||
($m:expr, $e:ident, $err:block) => {
|
||||
match $m {
|
||||
Ok(meta) => meta,
|
||||
Err($e) => $err,
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
impl Chowner {
|
||||
|
|
|
@ -14,8 +14,8 @@ extern crate getopts;
|
|||
|
||||
#[macro_use]
|
||||
extern crate uucore;
|
||||
use uucore::libc::{self, chroot, setgid, setgroups, setuid};
|
||||
use uucore::entries;
|
||||
use uucore::libc::{self, chroot, setgid, setgroups, setuid};
|
||||
|
||||
use std::ffi::CString;
|
||||
use std::io::Error;
|
||||
|
@ -140,10 +140,7 @@ fn enter_chroot(root: &Path) {
|
|||
let root_str = root.display();
|
||||
std::env::set_current_dir(root).unwrap();
|
||||
let err = unsafe {
|
||||
chroot(CString::new(".")
|
||||
.unwrap()
|
||||
.as_bytes_with_nul()
|
||||
.as_ptr() as *const libc::c_char)
|
||||
chroot(CString::new(".").unwrap().as_bytes_with_nul().as_ptr() as *const libc::c_char)
|
||||
};
|
||||
if err != 0 {
|
||||
crash!(
|
||||
|
|
|
@ -32,7 +32,8 @@ fn main() {
|
|||
&file,
|
||||
"#[allow(clippy::unreadable_literal)]\nconst CRC_TABLE: [u32; {}] = {:?};",
|
||||
CRC_TABLE_LEN, table
|
||||
).unwrap();
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
49
src/cp/cp.rs
49
src/cp/cp.rs
|
@ -1,5 +1,4 @@
|
|||
#![crate_name = "uu_cp"]
|
||||
|
||||
#![allow(clippy::missing_safety_doc)]
|
||||
|
||||
/*
|
||||
|
@ -29,35 +28,35 @@ extern crate xattr;
|
|||
#[cfg(windows)]
|
||||
extern crate kernel32;
|
||||
#[cfg(windows)]
|
||||
use kernel32::GetFileInformationByHandle;
|
||||
#[cfg(windows)]
|
||||
use kernel32::CreateFileW;
|
||||
#[cfg(windows)]
|
||||
use kernel32::GetFileInformationByHandle;
|
||||
#[cfg(windows)]
|
||||
extern crate winapi;
|
||||
|
||||
use std::mem;
|
||||
use clap::{App, Arg, ArgMatches};
|
||||
use filetime::FileTime;
|
||||
use quick_error::ResultExt;
|
||||
use std::collections::HashSet;
|
||||
#[cfg(not(windows))]
|
||||
use std::ffi::CString;
|
||||
#[cfg(windows)]
|
||||
use std::ffi::OsStr;
|
||||
use clap::{App, Arg, ArgMatches};
|
||||
use quick_error::ResultExt;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io::{stdin, stdout, Write};
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::fs::File;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io;
|
||||
use std::io::{stdin, stdout, Write};
|
||||
use std::mem;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::os::unix::io::IntoRawFd;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Path, PathBuf, StripPrefixError};
|
||||
use std::str::FromStr;
|
||||
use uucore::fs::{canonicalize, CanonicalizeMode};
|
||||
use walkdir::WalkDir;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::os::unix::io::IntoRawFd;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::fs::File;
|
||||
use std::fs::OpenOptions;
|
||||
use filetime::FileTime;
|
||||
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
@ -584,7 +583,8 @@ impl Options {
|
|||
}
|
||||
}
|
||||
|
||||
let recursive = matches.is_present(OPT_RECURSIVE) || matches.is_present(OPT_RECURSIVE_ALIAS)
|
||||
let recursive = matches.is_present(OPT_RECURSIVE)
|
||||
|| matches.is_present(OPT_RECURSIVE_ALIAS)
|
||||
|| matches.is_present(OPT_ARCHIVE);
|
||||
|
||||
let backup = matches.is_present(OPT_BACKUP) || (matches.occurrences_of(OPT_SUFFIX) > 0);
|
||||
|
@ -731,7 +731,8 @@ fn preserve_hardlinks(
|
|||
"cannot stat {:?}: {}",
|
||||
src_path,
|
||||
std::io::Error::last_os_error()
|
||||
).into());
|
||||
)
|
||||
.into());
|
||||
}
|
||||
inode = stat.st_ino as u64;
|
||||
nlinks = stat.st_nlink as u64;
|
||||
|
@ -755,7 +756,8 @@ fn preserve_hardlinks(
|
|||
"cannot get file information {:?}: {}",
|
||||
source,
|
||||
std::io::Error::last_os_error()
|
||||
).into());
|
||||
)
|
||||
.into());
|
||||
}
|
||||
inode = ((*stat).nFileIndexHigh as u64) << 32 | (*stat).nFileIndexLow as u64;
|
||||
nlinks = (*stat).nNumberOfLinks as u64;
|
||||
|
@ -836,7 +838,8 @@ fn construct_dest_path(
|
|||
return Err(format!(
|
||||
"cannot overwrite directory '{}' with non-directory",
|
||||
target.display()
|
||||
).into());
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
Ok(match *target_type {
|
||||
|
@ -1140,7 +1143,8 @@ fn copy_helper(source: &Path, dest: &Path, options: &Options) -> CopyResult<()>
|
|||
source,
|
||||
dest,
|
||||
std::io::Error::last_os_error()
|
||||
).into());
|
||||
)
|
||||
.into());
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
|
@ -1169,7 +1173,8 @@ pub fn verify_target_type(target: &Path, target_type: &TargetType) -> CopyResult
|
|||
(&TargetType::File, true) => Err(format!(
|
||||
"cannot overwrite directory '{}' with non-directory",
|
||||
target.display()
|
||||
).into()),
|
||||
)
|
||||
.into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
@ -1205,6 +1210,8 @@ fn test_cp_localize_to_target() {
|
|||
&Path::new("a/source/"),
|
||||
&Path::new("a/source/c.txt"),
|
||||
&Path::new("target/")
|
||||
).unwrap() == Path::new("target/c.txt")
|
||||
)
|
||||
.unwrap()
|
||||
== Path::new("target/c.txt")
|
||||
)
|
||||
}
|
||||
|
|
|
@ -10,8 +10,8 @@
|
|||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::io::Result as IoResult;
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub mod Bytes {
|
||||
|
|
|
@ -466,8 +466,8 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
)
|
||||
})
|
||||
}
|
||||
(None, None, Some(field_ranges)) => list_to_ranges(&field_ranges[..], complement)
|
||||
.and_then(|ranges| {
|
||||
(None, None, Some(field_ranges)) => {
|
||||
list_to_ranges(&field_ranges[..], complement).and_then(|ranges| {
|
||||
let out_delim = match matches.opt_str("output-delimiter") {
|
||||
Some(s) => {
|
||||
if s.is_empty() {
|
||||
|
@ -519,11 +519,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
},
|
||||
)),
|
||||
}
|
||||
}),
|
||||
})
|
||||
}
|
||||
(ref b, ref c, ref f) if b.is_some() || c.is_some() || f.is_some() => Err(
|
||||
msg_expects_no_more_than_one_of!("--fields (-f)", "--chars (-c)", "--bytes (-b)"),
|
||||
),
|
||||
_ => Err(msg_expects_one_of!("--fields (-f)", "--chars (-c)", "--bytes (-b)")),
|
||||
_ => Err(msg_expects_one_of!(
|
||||
"--fields (-f)",
|
||||
"--chars (-c)",
|
||||
"--bytes (-b)"
|
||||
)),
|
||||
};
|
||||
|
||||
let mode_parse = match mode_parse {
|
||||
|
|
|
@ -42,10 +42,7 @@ impl FromStr for Range {
|
|||
(Some(n), Some(m)) if m.is_empty() => {
|
||||
if let Ok(low) = n.parse::<usize>() {
|
||||
if low > 0 {
|
||||
Ok(Range {
|
||||
low,
|
||||
high: MAX - 1,
|
||||
})
|
||||
Ok(Range { low, high: MAX - 1 })
|
||||
} else {
|
||||
Err(field)
|
||||
}
|
||||
|
@ -67,10 +64,7 @@ impl FromStr for Range {
|
|||
(Some(n), Some(m)) => match (n.parse::<usize>(), m.parse::<usize>()) {
|
||||
(Ok(low), Ok(high)) => {
|
||||
if low > 0 && low <= high {
|
||||
Ok(Range {
|
||||
low,
|
||||
high,
|
||||
})
|
||||
Ok(Range { low, high })
|
||||
} else if low == 0 {
|
||||
Err(field)
|
||||
} else {
|
||||
|
|
|
@ -14,8 +14,8 @@ extern crate chrono;
|
|||
extern crate clap;
|
||||
extern crate uucore;
|
||||
|
||||
use chrono::{DateTime, FixedOffset, Local, Offset};
|
||||
use chrono::offset::Utc;
|
||||
use chrono::{DateTime, FixedOffset, Local, Offset};
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::PathBuf;
|
||||
|
@ -210,12 +210,11 @@ fn parse_cli(args: Vec<String>) -> Settings {
|
|||
"set time described by STRING")
|
||||
(@arg utc: -u --utc --universal
|
||||
"print or set Coordinated Universal Time (UTC)"))
|
||||
|
||||
// TODO: Decide whether this is appropriate.
|
||||
// The GNU date command has an explanation of all formatting options,
|
||||
// but the `chrono` crate has a few differences (most notably, the %Z option)
|
||||
// (after_help: include_str!("usage.txt")))
|
||||
.get_matches_from(args);
|
||||
.get_matches_from(args);
|
||||
|
||||
let format = if let Some(form) = matches.value_of("custom_format") {
|
||||
let form = form[1..].into();
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
pub const INTERNAL_DB: &str =
|
||||
r#"# Configuration file for dircolors, a utility to help you set the
|
||||
pub const INTERNAL_DB: &str = r#"# Configuration file for dircolors, a utility to help you set the
|
||||
# LS_COLORS environment variable used by GNU ls with the --color option.
|
||||
# Copyright (C) 1996-2016 Free Software Foundation, Inc.
|
||||
# Copying and distribution of this file, with or without modification,
|
||||
|
|
|
@ -13,10 +13,10 @@ extern crate glob;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::borrow::Borrow;
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
|
||||
static SYNTAX: &str = "[OPTION]... [FILE]";
|
||||
static SUMMARY: &str = "Output commands to set the LS_COLORS environment variable.";
|
||||
|
@ -68,8 +68,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
.optflag("p", "print-database", "print the byte counts")
|
||||
.parse(args);
|
||||
|
||||
if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh")
|
||||
|| matches.opt_present("bourne-shell")) && matches.opt_present("print-database")
|
||||
if (matches.opt_present("csh")
|
||||
|| matches.opt_present("c-shell")
|
||||
|| matches.opt_present("sh")
|
||||
|| matches.opt_present("bourne-shell"))
|
||||
&& matches.opt_present("print-database")
|
||||
{
|
||||
disp_err!(
|
||||
"the options to output dircolors' internal database and\nto select a shell \
|
||||
|
@ -291,7 +294,7 @@ where
|
|||
} else if key.starts_with('*') {
|
||||
result.push_str(format!("{}={}:", key, val).as_str());
|
||||
} else if lower == "options" || lower == "color" || lower == "eightbit" {
|
||||
// Slackware only. Ignore
|
||||
// Slackware only. Ignore
|
||||
} else if let Some(s) = table.get(lower.as_str()) {
|
||||
result.push_str(format!("{}={}:", s, val).as_str());
|
||||
} else {
|
||||
|
|
246
src/du/du.rs
246
src/du/du.rs
|
@ -163,40 +163,36 @@ fn du(
|
|||
|
||||
for f in read {
|
||||
match f {
|
||||
Ok(entry) => {
|
||||
match Stat::new(entry.path()) {
|
||||
Ok(this_stat) => {
|
||||
if this_stat.is_dir {
|
||||
futures.push(du(this_stat, options, depth + 1, inodes));
|
||||
} else {
|
||||
if inodes.contains(&this_stat.inode) {
|
||||
continue;
|
||||
}
|
||||
inodes.insert(this_stat.inode);
|
||||
my_stat.size += this_stat.size;
|
||||
my_stat.blocks += this_stat.blocks;
|
||||
if options.all {
|
||||
stats.push(this_stat);
|
||||
}
|
||||
Ok(entry) => match Stat::new(entry.path()) {
|
||||
Ok(this_stat) => {
|
||||
if this_stat.is_dir {
|
||||
futures.push(du(this_stat, options, depth + 1, inodes));
|
||||
} else {
|
||||
if inodes.contains(&this_stat.inode) {
|
||||
continue;
|
||||
}
|
||||
inodes.insert(this_stat.inode);
|
||||
my_stat.size += this_stat.size;
|
||||
my_stat.blocks += this_stat.blocks;
|
||||
if options.all {
|
||||
stats.push(this_stat);
|
||||
}
|
||||
}
|
||||
Err(error) => show_error!("{}", error),
|
||||
}
|
||||
}
|
||||
Err(error) => show_error!("{}", error),
|
||||
},
|
||||
Err(error) => show_error!("{}", error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats.extend(futures.into_iter().flatten().rev().filter(
|
||||
|stat| {
|
||||
if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path {
|
||||
my_stat.size += stat.size;
|
||||
my_stat.blocks += stat.blocks;
|
||||
}
|
||||
options.max_depth == None || depth < options.max_depth.unwrap()
|
||||
},
|
||||
));
|
||||
stats.extend(futures.into_iter().flatten().rev().filter(|stat| {
|
||||
if !options.separate_dirs && stat.path.parent().unwrap() == my_stat.path {
|
||||
my_stat.size += stat.size;
|
||||
my_stat.blocks += stat.blocks;
|
||||
}
|
||||
options.max_depth == None || depth < options.max_depth.unwrap()
|
||||
}));
|
||||
stats.push(my_stat);
|
||||
Box::new(stats.into_iter())
|
||||
}
|
||||
|
@ -220,7 +216,10 @@ fn convert_size_k(size: u64, multiplier: u64, _block_size: u64) -> String {
|
|||
}
|
||||
|
||||
fn convert_size_m(size: u64, multiplier: u64, _block_size: u64) -> String {
|
||||
format!("{}", ((size as f64) / ((multiplier * multiplier) as f64)).ceil())
|
||||
format!(
|
||||
"{}",
|
||||
((size as f64) / ((multiplier * multiplier) as f64)).ceil()
|
||||
)
|
||||
}
|
||||
|
||||
fn convert_size_other(size: u64, _multiplier: u64, block_size: u64) -> String {
|
||||
|
@ -235,66 +234,109 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
NAME
|
||||
);
|
||||
let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP)
|
||||
// In task
|
||||
.optflag("a", "all", " write counts for all files, not just directories")
|
||||
// In main
|
||||
.optflag("", "apparent-size", "print apparent sizes, rather than disk usage
|
||||
// In task
|
||||
.optflag(
|
||||
"a",
|
||||
"all",
|
||||
" write counts for all files, not just directories",
|
||||
)
|
||||
// In main
|
||||
.optflag(
|
||||
"",
|
||||
"apparent-size",
|
||||
"print apparent sizes, rather than disk usage
|
||||
although the apparent size is usually smaller, it may be larger due to holes
|
||||
in ('sparse') files, internal fragmentation, indirect blocks, and the like")
|
||||
// In main
|
||||
.optopt("B", "block-size", "scale sizes by SIZE before printing them.
|
||||
in ('sparse') files, internal fragmentation, indirect blocks, and the like",
|
||||
)
|
||||
// In main
|
||||
.optopt(
|
||||
"B",
|
||||
"block-size",
|
||||
"scale sizes by SIZE before printing them.
|
||||
E.g., '-BM' prints sizes in units of 1,048,576 bytes. See SIZE format below.",
|
||||
"SIZE")
|
||||
// In main
|
||||
.optflag("b", "bytes", "equivalent to '--apparent-size --block-size=1'")
|
||||
// In main
|
||||
"SIZE",
|
||||
)
|
||||
// In main
|
||||
.optflag(
|
||||
"b",
|
||||
"bytes",
|
||||
"equivalent to '--apparent-size --block-size=1'",
|
||||
)
|
||||
// In main
|
||||
.optflag("c", "total", "produce a grand total")
|
||||
// In task
|
||||
// opts.optflag("D", "dereference-args", "dereference only symlinks that are listed
|
||||
// on the command line"),
|
||||
// In main
|
||||
// opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file
|
||||
// names specified in file F;
|
||||
// If F is - then read names from standard input", "F"),
|
||||
// // In task
|
||||
// opts.optflag("H", "", "equivalent to --dereference-args (-D)"),
|
||||
// In main
|
||||
.optflag("h", "human-readable", "print sizes in human readable format (e.g., 1K 234M 2G)")
|
||||
// In main
|
||||
// In task
|
||||
// opts.optflag("D", "dereference-args", "dereference only symlinks that are listed
|
||||
// on the command line"),
|
||||
// In main
|
||||
// opts.optopt("", "files0-from", "summarize disk usage of the NUL-terminated file
|
||||
// names specified in file F;
|
||||
// If F is - then read names from standard input", "F"),
|
||||
// // In task
|
||||
// opts.optflag("H", "", "equivalent to --dereference-args (-D)"),
|
||||
// In main
|
||||
.optflag(
|
||||
"h",
|
||||
"human-readable",
|
||||
"print sizes in human readable format (e.g., 1K 234M 2G)",
|
||||
)
|
||||
// In main
|
||||
.optflag("", "si", "like -h, but use powers of 1000 not 1024")
|
||||
// In main
|
||||
// In main
|
||||
.optflag("k", "", "like --block-size=1K")
|
||||
// In task
|
||||
// In task
|
||||
.optflag("l", "count-links", "count sizes many times if hard linked")
|
||||
// // In main
|
||||
// // In main
|
||||
.optflag("m", "", "like --block-size=1M")
|
||||
// // In task
|
||||
// opts.optflag("L", "dereference", "dereference all symbolic links"),
|
||||
// // In task
|
||||
// opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"),
|
||||
// // In main
|
||||
.optflag("0", "null", "end each output line with 0 byte rather than newline")
|
||||
// In main
|
||||
.optflag("S", "separate-dirs", "do not include size of subdirectories")
|
||||
// In main
|
||||
// // In task
|
||||
// opts.optflag("L", "dereference", "dereference all symbolic links"),
|
||||
// // In task
|
||||
// opts.optflag("P", "no-dereference", "don't follow any symbolic links (this is the default)"),
|
||||
// // In main
|
||||
.optflag(
|
||||
"0",
|
||||
"null",
|
||||
"end each output line with 0 byte rather than newline",
|
||||
)
|
||||
// In main
|
||||
.optflag(
|
||||
"S",
|
||||
"separate-dirs",
|
||||
"do not include size of subdirectories",
|
||||
)
|
||||
// In main
|
||||
.optflag("s", "summarize", "display only a total for each argument")
|
||||
// // In task
|
||||
// opts.optflag("x", "one-file-system", "skip directories on different file systems"),
|
||||
// // In task
|
||||
// opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"),
|
||||
// // In task
|
||||
// opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"),
|
||||
// In main
|
||||
.optopt("d", "max-depth", "print the total for a directory (or file, with --all)
|
||||
// // In task
|
||||
// opts.optflag("x", "one-file-system", "skip directories on different file systems"),
|
||||
// // In task
|
||||
// opts.optopt("X", "exclude-from", "exclude files that match any pattern in FILE", "FILE"),
|
||||
// // In task
|
||||
// opts.optopt("", "exclude", "exclude files that match PATTERN", "PATTERN"),
|
||||
// In main
|
||||
.optopt(
|
||||
"d",
|
||||
"max-depth",
|
||||
"print the total for a directory (or file, with --all)
|
||||
only if it is N or fewer levels below the command
|
||||
line argument; --max-depth=0 is the same as --summarize", "N")
|
||||
// In main
|
||||
.optflagopt("", "time", "show time of the last modification of any file in the
|
||||
line argument; --max-depth=0 is the same as --summarize",
|
||||
"N",
|
||||
)
|
||||
// In main
|
||||
.optflagopt(
|
||||
"",
|
||||
"time",
|
||||
"show time of the last modification of any file in the
|
||||
directory, or any of its subdirectories. If WORD is given, show time as WORD instead
|
||||
of modification time: atime, access, use, ctime or status", "WORD")
|
||||
// In main
|
||||
.optopt("", "time-style", "show times using style STYLE:
|
||||
full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'", "STYLE")
|
||||
of modification time: atime, access, use, ctime or status",
|
||||
"WORD",
|
||||
)
|
||||
// In main
|
||||
.optopt(
|
||||
"",
|
||||
"time-style",
|
||||
"show times using style STYLE:
|
||||
full-iso, long-iso, iso, +FORMAT FORMAT is interpreted like 'date'",
|
||||
"STYLE",
|
||||
)
|
||||
.parse(args);
|
||||
|
||||
let summarize = matches.opt_present("summarize");
|
||||
|
@ -350,26 +392,24 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
let convert_size = |size| convert_size_fn(size, multiplier, block_size);
|
||||
|
||||
let time_format_str = match matches.opt_str("time-style") {
|
||||
Some(s) => {
|
||||
match &s[..] {
|
||||
"full-iso" => "%Y-%m-%d %H:%M:%S.%f %z",
|
||||
"long-iso" => "%Y-%m-%d %H:%M",
|
||||
"iso" => "%Y-%m-%d",
|
||||
_ => {
|
||||
show_error!(
|
||||
"invalid argument '{}' for 'time style'
|
||||
Some(s) => match &s[..] {
|
||||
"full-iso" => "%Y-%m-%d %H:%M:%S.%f %z",
|
||||
"long-iso" => "%Y-%m-%d %H:%M",
|
||||
"iso" => "%Y-%m-%d",
|
||||
_ => {
|
||||
show_error!(
|
||||
"invalid argument '{}' for 'time style'
|
||||
Valid arguments are:
|
||||
- 'full-iso'
|
||||
- 'long-iso'
|
||||
- 'iso'
|
||||
Try '{} --help' for more information.",
|
||||
s,
|
||||
NAME
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
s,
|
||||
NAME
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
},
|
||||
None => "%Y-%m-%d %H:%M",
|
||||
};
|
||||
|
||||
|
@ -397,23 +437,21 @@ Try '{} --help' for more information.",
|
|||
let tm = {
|
||||
let (secs, nsecs) = {
|
||||
let time = match matches.opt_str("time") {
|
||||
Some(s) => {
|
||||
match &s[..] {
|
||||
"accessed" => stat.accessed,
|
||||
"created" => stat.created,
|
||||
"modified" => stat.modified,
|
||||
_ => {
|
||||
show_error!(
|
||||
"invalid argument 'modified' for '--time'
|
||||
Some(s) => match &s[..] {
|
||||
"accessed" => stat.accessed,
|
||||
"created" => stat.created,
|
||||
"modified" => stat.modified,
|
||||
_ => {
|
||||
show_error!(
|
||||
"invalid argument 'modified' for '--time'
|
||||
Valid arguments are:
|
||||
- 'accessed', 'created', 'modified'
|
||||
Try '{} --help' for more information.",
|
||||
NAME
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
NAME
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
},
|
||||
None => stat.modified,
|
||||
};
|
||||
((time / 1000) as i64, (time % 1000 * 1_000_000) as i32)
|
||||
|
|
|
@ -71,8 +71,8 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
|
|||
'b' => '\x08',
|
||||
'c' => {
|
||||
should_stop = true;
|
||||
break
|
||||
},
|
||||
break;
|
||||
}
|
||||
'e' => '\x1b',
|
||||
'f' => '\x0c',
|
||||
'n' => '\n',
|
||||
|
@ -90,7 +90,7 @@ fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
|
|||
_ => {
|
||||
start = 0;
|
||||
next
|
||||
},
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -110,7 +110,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
let matches = new_coreopts!(SYNTAX, SUMMARY, HELP)
|
||||
.optflag("n", "", "do not output the trailing newline")
|
||||
.optflag("e", "", "enable interpretation of backslash escapes")
|
||||
.optflag("E", "", "disable interpretation of backslash escapes (default)")
|
||||
.optflag(
|
||||
"E",
|
||||
"",
|
||||
"disable interpretation of backslash escapes (default)",
|
||||
)
|
||||
.parse(args);
|
||||
|
||||
let no_newline = matches.opt_present("n");
|
||||
|
|
3
src/env/env.rs
vendored
3
src/env/env.rs
vendored
|
@ -89,7 +89,8 @@ fn load_config_file(opts: &mut Options) -> Result<(), i32> {
|
|||
}
|
||||
};
|
||||
|
||||
for (_, prop) in &conf { // ignore all INI section lines (treat them as comments)
|
||||
for (_, prop) in &conf {
|
||||
// ignore all INI section lines (treat them as comments)
|
||||
for (key, value) in prop {
|
||||
env::set_var(key, value);
|
||||
}
|
||||
|
|
|
@ -45,7 +45,8 @@ fn tabstops_parse(s: String) -> Vec<usize> {
|
|||
crash!(1, "{}\n", "tab size cannot be 0");
|
||||
}
|
||||
|
||||
if let (false, _) = nums.iter()
|
||||
if let (false, _) = nums
|
||||
.iter()
|
||||
.fold((true, 0), |(acc, last), &n| (acc && last <= n, n))
|
||||
{
|
||||
crash!(1, "{}\n", "tab sizes must be ascending");
|
||||
|
|
|
@ -13,8 +13,8 @@ extern crate onig;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
mod tokens;
|
||||
mod syntax_tree;
|
||||
mod tokens;
|
||||
|
||||
static NAME: &str = "expr";
|
||||
static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
|
|
@ -12,8 +12,8 @@
|
|||
//! * https://en.wikipedia.org/wiki/Shunting-yard_algorithm
|
||||
//!
|
||||
|
||||
use tokens::Token;
|
||||
use onig::{Regex, RegexOptions, Syntax};
|
||||
use tokens::Token;
|
||||
|
||||
type TokenStack = Vec<(usize, Token)>;
|
||||
pub type OperandsList = Vec<Box<ASTNode>>;
|
||||
|
@ -85,25 +85,27 @@ impl ASTNode {
|
|||
ASTNode::Node { ref op_type, .. } => match self.operand_values() {
|
||||
Err(reason) => Err(reason),
|
||||
Ok(operand_values) => match op_type.as_ref() {
|
||||
"+" => infix_operator_two_ints(|a: i64, b: i64| {
|
||||
checked_binop(|| a.checked_add(b), "+")
|
||||
}, &operand_values
|
||||
"+" => infix_operator_two_ints(
|
||||
|a: i64, b: i64| checked_binop(|| a.checked_add(b), "+"),
|
||||
&operand_values,
|
||||
),
|
||||
"-" => infix_operator_two_ints(|a: i64, b: i64| {
|
||||
checked_binop(|| a.checked_sub(b), "-")
|
||||
}, &operand_values
|
||||
"-" => infix_operator_two_ints(
|
||||
|a: i64, b: i64| checked_binop(|| a.checked_sub(b), "-"),
|
||||
&operand_values,
|
||||
),
|
||||
"*" => infix_operator_two_ints(|a: i64, b: i64| {
|
||||
checked_binop(|| a.checked_mul(b), "*")
|
||||
}, &operand_values
|
||||
"*" => infix_operator_two_ints(
|
||||
|a: i64, b: i64| checked_binop(|| a.checked_mul(b), "*"),
|
||||
&operand_values,
|
||||
),
|
||||
"/" => infix_operator_two_ints(|a: i64, b: i64| {
|
||||
"/" => infix_operator_two_ints(
|
||||
|a: i64, b: i64| {
|
||||
if b == 0 {
|
||||
Err("division by zero".to_owned())
|
||||
} else {
|
||||
checked_binop(|| a.checked_div(b), "/")
|
||||
}
|
||||
}, &operand_values
|
||||
},
|
||||
&operand_values,
|
||||
),
|
||||
"%" => infix_operator_two_ints(
|
||||
|a: i64, b: i64| {
|
||||
|
@ -299,18 +301,29 @@ fn push_token_to_either_stack(
|
|||
op_stack: &mut TokenStack,
|
||||
) -> Result<(), String> {
|
||||
let result = match *token {
|
||||
Token::Value { .. } => { out_stack.push((token_idx, token.clone())); Ok(()) },
|
||||
Token::Value { .. } => {
|
||||
out_stack.push((token_idx, token.clone()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Token::InfixOp { .. } => if op_stack.is_empty() {
|
||||
Token::InfixOp { .. } => {
|
||||
if op_stack.is_empty() {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
Ok(())
|
||||
} else {
|
||||
push_op_to_stack(token_idx, token, out_stack, op_stack)
|
||||
}
|
||||
}
|
||||
|
||||
Token::PrefixOp { .. } => {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
Ok(())
|
||||
} else {
|
||||
push_op_to_stack(token_idx, token, out_stack, op_stack)
|
||||
},
|
||||
}
|
||||
|
||||
Token::PrefixOp { .. } => { op_stack.push((token_idx, token.clone())); Ok(()) },
|
||||
|
||||
Token::ParOpen => { op_stack.push((token_idx, token.clone())); Ok(()) },
|
||||
Token::ParOpen => {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Token::ParClose => move_till_match_paren(out_stack, op_stack),
|
||||
};
|
||||
|
@ -352,7 +365,10 @@ fn push_op_to_stack(
|
|||
{
|
||||
loop {
|
||||
match op_stack.last() {
|
||||
None => { op_stack.push((token_idx, token.clone())); return Ok(()) },
|
||||
None => {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Some(&(_, Token::ParOpen)) => {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
|
@ -365,12 +381,14 @@ fn push_op_to_stack(
|
|||
precedence: prev_prec,
|
||||
..
|
||||
},
|
||||
)) => if la && prev_prec >= prec || !la && prev_prec > prec {
|
||||
out_stack.push(op_stack.pop().unwrap())
|
||||
} else {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
return Ok(());
|
||||
},
|
||||
)) => {
|
||||
if la && prev_prec >= prec || !la && prev_prec > prec {
|
||||
out_stack.push(op_stack.pop().unwrap())
|
||||
} else {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Some(&(_, Token::PrefixOp { .. })) => {
|
||||
op_stack.push((token_idx, token.clone()));
|
||||
|
|
|
@ -141,12 +141,7 @@ fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) {
|
|||
}
|
||||
}
|
||||
|
||||
fn push_token_if_not_escaped(
|
||||
acc: &mut Vec<(usize, Token)>,
|
||||
tok_idx: usize,
|
||||
token: Token,
|
||||
s: &str,
|
||||
) {
|
||||
fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
|
||||
// Smells heuristics... :(
|
||||
let prev_is_plus = match acc.last() {
|
||||
None => false,
|
||||
|
|
|
@ -115,7 +115,8 @@ fn main() {
|
|||
file,
|
||||
"\n];\n\n#[allow(dead_code)]\npub const NEXT_PRIME: u64 = {};\n",
|
||||
x
|
||||
).unwrap();
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -20,12 +20,12 @@ extern crate uucore;
|
|||
|
||||
use numeric::*;
|
||||
use rand::distributions::{Distribution, Uniform};
|
||||
use rand::{SeedableRng, thread_rng};
|
||||
use rand::rngs::SmallRng;
|
||||
use rand::{thread_rng, SeedableRng};
|
||||
use std::cmp::{max, min};
|
||||
use std::io::{stdin, BufRead};
|
||||
use std::num::Wrapping;
|
||||
use std::mem::swap;
|
||||
use std::num::Wrapping;
|
||||
|
||||
mod numeric;
|
||||
|
||||
|
@ -155,7 +155,10 @@ fn print_factors(num: u64) {
|
|||
}
|
||||
|
||||
fn print_factors_str(num_str: &str) {
|
||||
if let Err(e) = num_str.parse::<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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
* that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use std::u64::MAX as MAX_U64;
|
||||
use std::num::Wrapping;
|
||||
use std::u64::MAX as MAX_U64;
|
||||
|
||||
pub fn big_add(a: u64, b: u64, m: u64) -> u64 {
|
||||
let Wrapping(msb_mod_m) = Wrapping(MAX_U64) - Wrapping(m) + Wrapping(1);
|
||||
|
|
|
@ -14,12 +14,12 @@ extern crate unicode_width;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use std::cmp;
|
||||
use std::io::{BufReader, BufWriter, Read};
|
||||
use std::fs::File;
|
||||
use std::io::{stdin, stdout, Write};
|
||||
use linebreak::break_lines;
|
||||
use parasplit::ParagraphStream;
|
||||
use std::cmp;
|
||||
use std::fs::File;
|
||||
use std::io::{stdin, stdout, Write};
|
||||
use std::io::{BufReader, BufWriter, Read};
|
||||
|
||||
macro_rules! silent_unwrap(
|
||||
($exp:expr) => (
|
||||
|
|
|
@ -7,12 +7,12 @@
|
|||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use FmtOptions;
|
||||
use parasplit::{ParaWords, Paragraph, WordInfo};
|
||||
use std::io::{BufWriter, Stdout, Write};
|
||||
use std::i64;
|
||||
use std::cmp;
|
||||
use std::i64;
|
||||
use std::io::{BufWriter, Stdout, Write};
|
||||
use std::mem;
|
||||
use FmtOptions;
|
||||
|
||||
struct BreakArgs<'a> {
|
||||
opts: &'a FmtOptions,
|
||||
|
@ -58,18 +58,19 @@ pub fn break_lines(para: &Paragraph, opts: &FmtOptions, ostream: &mut BufWriter<
|
|||
}
|
||||
};
|
||||
// print the init, if it exists, and get its length
|
||||
let p_init_len = w_len + if opts.crown || opts.tagged {
|
||||
// handle "init" portion
|
||||
silent_unwrap!(ostream.write_all(para.init_str.as_bytes()));
|
||||
para.init_len
|
||||
} else if !para.mail_header {
|
||||
// for non-(crown, tagged) that's the same as a normal indent
|
||||
silent_unwrap!(ostream.write_all(p_indent.as_bytes()));
|
||||
p_indent_len
|
||||
} else {
|
||||
// except that mail headers get no indent at all
|
||||
0
|
||||
};
|
||||
let p_init_len = w_len
|
||||
+ if opts.crown || opts.tagged {
|
||||
// handle "init" portion
|
||||
silent_unwrap!(ostream.write_all(para.init_str.as_bytes()));
|
||||
para.init_len
|
||||
} else if !para.mail_header {
|
||||
// for non-(crown, tagged) that's the same as a normal indent
|
||||
silent_unwrap!(ostream.write_all(p_indent.as_bytes()));
|
||||
p_indent_len
|
||||
} else {
|
||||
// except that mail headers get no indent at all
|
||||
0
|
||||
};
|
||||
// write first word after writing init
|
||||
silent_unwrap!(ostream.write_all(w.as_bytes()));
|
||||
|
||||
|
@ -218,17 +219,15 @@ fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
|
|||
) -> Vec<(&'a WordInfo<'a>, bool)> {
|
||||
let mut iter = iter.peekable();
|
||||
// set up the initial null linebreak
|
||||
let mut linebreaks = vec![
|
||||
LineBreak {
|
||||
prev: 0,
|
||||
linebreak: None,
|
||||
break_before: false,
|
||||
demerits: 0,
|
||||
prev_rat: 0.0f32,
|
||||
length: args.init_len,
|
||||
fresh: false,
|
||||
},
|
||||
];
|
||||
let mut linebreaks = vec![LineBreak {
|
||||
prev: 0,
|
||||
linebreak: None,
|
||||
break_before: false,
|
||||
demerits: 0,
|
||||
prev_rat: 0.0f32,
|
||||
length: args.init_len,
|
||||
fresh: false,
|
||||
}];
|
||||
// this vec holds the current active linebreaks; next_ holds the breaks that will be active for
|
||||
// the next word
|
||||
let active_breaks = &mut vec![0];
|
||||
|
@ -275,7 +274,9 @@ fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
|
|||
}
|
||||
|
||||
// get the new length
|
||||
let tlen = w.word_nchars + args.compute_width(w, active.length, active.fresh) + slen
|
||||
let tlen = w.word_nchars
|
||||
+ args.compute_width(w, active.length, active.fresh)
|
||||
+ slen
|
||||
+ active.length;
|
||||
|
||||
// if tlen is longer than args.opts.width, we drop this break from the active list
|
||||
|
@ -304,7 +305,8 @@ fn find_kp_breakpoints<'a, T: Iterator<Item = &'a WordInfo<'a>>>(
|
|||
// do not even consider adding a line that has too many demerits
|
||||
// also, try to detect overflow by checking signum
|
||||
let total_demerits = new_demerits + active.demerits;
|
||||
if new_demerits < BAD_INFTY_SQ && total_demerits < ld_new
|
||||
if new_demerits < BAD_INFTY_SQ
|
||||
&& total_demerits < ld_new
|
||||
&& active.demerits.signum() <= new_demerits.signum()
|
||||
{
|
||||
ld_new = total_demerits;
|
||||
|
|
|
@ -7,8 +7,8 @@
|
|||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use std::iter::Peekable;
|
||||
use std::io::{BufRead, Lines};
|
||||
use std::iter::Peekable;
|
||||
use std::slice::Iter;
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
use FileOrStdReader;
|
||||
|
@ -72,10 +72,7 @@ pub struct FileLines<'a> {
|
|||
|
||||
impl<'a> FileLines<'a> {
|
||||
fn new<'b>(opts: &'b FmtOptions, lines: Lines<&'b mut FileOrStdReader>) -> FileLines<'b> {
|
||||
FileLines {
|
||||
opts,
|
||||
lines,
|
||||
}
|
||||
FileLines { opts, lines }
|
||||
}
|
||||
|
||||
// returns true if this line should be formatted
|
||||
|
@ -363,8 +360,9 @@ impl<'a> Iterator for ParagraphStream<'a> {
|
|||
}
|
||||
} else if !second_done {
|
||||
// now we have enough info to handle crown margin and tagged mode
|
||||
if // in both crown and tagged modes we require that prefix_len is the same
|
||||
prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end
|
||||
if
|
||||
// in both crown and tagged modes we require that prefix_len is the same
|
||||
prefix_len != fl.prefix_len || pfxind_end != fl.pfxind_end
|
||||
||
|
||||
// in tagged mode, indent has to be *different* on following lines
|
||||
self.opts.tagged && indent_len - 4 == fl.indent_len && indent_end == fl.indent_end
|
||||
|
@ -380,7 +378,8 @@ impl<'a> Iterator for ParagraphStream<'a> {
|
|||
second_done = true;
|
||||
} else {
|
||||
// detect mismatch
|
||||
if indent_end != fl.indent_end || pfxind_end != fl.pfxind_end
|
||||
if indent_end != fl.indent_end
|
||||
|| pfxind_end != fl.pfxind_end
|
||||
|| indent_len != fl.indent_len
|
||||
|| prefix_len != fl.prefix_len
|
||||
{
|
||||
|
|
|
@ -70,9 +70,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
|
||||
for (i, arg) in args.iter().enumerate() {
|
||||
let slice = &arg;
|
||||
if slice.starts_with('-') && slice.len() > 1
|
||||
&& slice.chars().nth(1).unwrap().is_digit(10)
|
||||
{
|
||||
if slice.starts_with('-') && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
|
||||
let mut v = args.to_vec();
|
||||
v.remove(i);
|
||||
return (v, Some(slice[1..].to_owned()));
|
||||
|
@ -145,11 +143,13 @@ fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width:
|
|||
let ncount = routput.chars().fold(0, |out, ch: char| {
|
||||
out + match ch {
|
||||
'\t' => 8,
|
||||
'\x08' => if out > 0 {
|
||||
!0
|
||||
} else {
|
||||
0
|
||||
},
|
||||
'\x08' => {
|
||||
if out > 0 {
|
||||
!0
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
'\r' => return 0,
|
||||
_ => 1,
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
|
||||
#[macro_use]
|
||||
extern crate uucore;
|
||||
use uucore::entries::{get_groups, Locate, Passwd, gid2grp};
|
||||
use uucore::entries::{get_groups, gid2grp, Locate, Passwd};
|
||||
|
||||
static SYNTAX: &str = "[user]";
|
||||
static SUMMARY: &str = "display current group names";
|
||||
|
|
|
@ -71,7 +71,7 @@ impl Digest for sha1::Sha1 {
|
|||
|
||||
// Implements the Digest trait for sha2 / sha3 algorithms with fixed ouput
|
||||
macro_rules! impl_digest_sha {
|
||||
($type: ty, $size: expr) => (
|
||||
($type: ty, $size: expr) => {
|
||||
impl Digest for $type {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
|
@ -89,14 +89,16 @@ macro_rules! impl_digest_sha {
|
|||
*self = Self::new();
|
||||
}
|
||||
|
||||
fn output_bits(&self) -> usize { $size }
|
||||
fn output_bits(&self) -> usize {
|
||||
$size
|
||||
}
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
// Implements the Digest trait for sha2 / sha3 algorithms with variable ouput
|
||||
macro_rules! impl_digest_shake {
|
||||
($type: ty) => (
|
||||
($type: ty) => {
|
||||
impl Digest for $type {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
|
@ -114,9 +116,11 @@ macro_rules! impl_digest_shake {
|
|||
*self = Self::new();
|
||||
}
|
||||
|
||||
fn output_bits(&self) -> usize { 0 }
|
||||
fn output_bits(&self) -> usize {
|
||||
0
|
||||
}
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
impl_digest_sha!(sha2::Sha224, 224);
|
||||
|
|
|
@ -65,10 +65,26 @@ fn detect_algo(
|
|||
"sha512sum" => ("SHA512", Box::new(Sha512::new()) as Box<dyn Digest>, 512),
|
||||
"sha3sum" => match matches.opt_str("bits") {
|
||||
Some(bits_str) => match usize::from_str_radix(&bits_str, 10) {
|
||||
Ok(224) => ("SHA3-224", Box::new(Sha3_224::new()) as Box<dyn Digest>, 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(224) => (
|
||||
"SHA3-224",
|
||||
Box::new(Sha3_224::new()) as Box<dyn Digest>,
|
||||
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!(
|
||||
1,
|
||||
"Invalid output size for SHA3 (expected 224, 256, 384, or 512)"
|
||||
|
@ -77,20 +93,44 @@ fn detect_algo(
|
|||
},
|
||||
None => crash!(1, "--bits required for SHA3"),
|
||||
},
|
||||
"sha3-224sum" => ("SHA3-224", Box::new(Sha3_224::new()) as Box<dyn Digest>, 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),
|
||||
"sha3-224sum" => (
|
||||
"SHA3-224",
|
||||
Box::new(Sha3_224::new()) as Box<dyn Digest>,
|
||||
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") {
|
||||
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),
|
||||
},
|
||||
None => crash!(1, "--bits required for SHAKE-128"),
|
||||
},
|
||||
"shake256sum" => match matches.opt_str("bits") {
|
||||
Some(bits_str) => match usize::from_str_radix(&bits_str, 10) {
|
||||
Ok(bits) => ("SHAKE256", Box::new(Shake256::new()) as Box<dyn Digest>, bits),
|
||||
Ok(bits) => (
|
||||
"SHAKE256",
|
||||
Box::new(Shake256::new()) as Box<dyn Digest>,
|
||||
bits,
|
||||
),
|
||||
Err(err) => crash!(1, "{}", err),
|
||||
},
|
||||
None => crash!(1, "--bits required for SHAKE-256"),
|
||||
|
@ -319,17 +359,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
matches.free
|
||||
};
|
||||
match hashsum(
|
||||
name,
|
||||
algo,
|
||||
files,
|
||||
binary,
|
||||
check,
|
||||
tag,
|
||||
status,
|
||||
quiet,
|
||||
strict,
|
||||
warn,
|
||||
bits,
|
||||
name, algo, files, binary, check, tag, status, quiet, strict, warn, bits,
|
||||
) {
|
||||
Ok(()) => return 0,
|
||||
Err(e) => return e,
|
||||
|
@ -449,7 +479,8 @@ fn hashsum(
|
|||
&mut ckf,
|
||||
binary_check,
|
||||
output_bits
|
||||
)).to_ascii_lowercase();
|
||||
))
|
||||
.to_ascii_lowercase();
|
||||
if sum == real_sum {
|
||||
if !quiet {
|
||||
println!("{}: OK", ck_filename);
|
||||
|
@ -472,8 +503,12 @@ fn hashsum(
|
|||
}
|
||||
if !status {
|
||||
match bad_format.cmp(&1) {
|
||||
std::cmp::Ordering::Equal => show_warning!("{} line is improperly formatted", bad_format),
|
||||
std::cmp::Ordering::Greater => show_warning!("{} lines are improperly formatted", bad_format),
|
||||
std::cmp::Ordering::Equal => {
|
||||
show_warning!("{} line is improperly formatted", bad_format)
|
||||
}
|
||||
std::cmp::Ordering::Greater => {
|
||||
show_warning!("{} lines are improperly formatted", bad_format)
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
if failed > 0 {
|
||||
|
|
|
@ -14,8 +14,8 @@
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use std::io::{stdin, BufRead, BufReader, Read};
|
||||
use std::fs::File;
|
||||
use std::io::{stdin, BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::str::from_utf8;
|
||||
|
||||
|
@ -90,12 +90,14 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
}
|
||||
}
|
||||
}
|
||||
None => if let Some(count) = matches.opt_str("c") {
|
||||
match count.parse::<usize>() {
|
||||
Ok(m) => settings.mode = FilterMode::Bytes(m),
|
||||
Err(e) => {
|
||||
show_error!("invalid byte count '{}': {}", count, e);
|
||||
return 1;
|
||||
None => {
|
||||
if let Some(count) = matches.opt_str("c") {
|
||||
match count.parse::<usize>() {
|
||||
Ok(m) => settings.mode = FilterMode::Bytes(m),
|
||||
Err(e) => {
|
||||
show_error!("invalid byte count '{}': {}", count, e);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -186,12 +188,16 @@ fn obsolete(options: &[String]) -> (Vec<String>, Option<usize>) {
|
|||
// TODO: handle errors on read
|
||||
fn head<T: Read>(reader: &mut BufReader<T>, settings: &Settings) -> bool {
|
||||
match settings.mode {
|
||||
FilterMode::Bytes(count) => for byte in reader.bytes().take(count) {
|
||||
print!("{}", byte.unwrap() as char);
|
||||
},
|
||||
FilterMode::Lines(count) => for line in reader.lines().take(count) {
|
||||
println!("{}", line.unwrap());
|
||||
},
|
||||
FilterMode::Bytes(count) => {
|
||||
for byte in reader.bytes().take(count) {
|
||||
print!("{}", byte.unwrap() as char);
|
||||
}
|
||||
}
|
||||
FilterMode::Lines(count) => {
|
||||
for line in reader.lines().take(count) {
|
||||
println!("{}", line.unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
|
|
@ -17,21 +17,21 @@ extern crate winapi;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use std::collections::hash_set::HashSet;
|
||||
use std::iter::repeat;
|
||||
use std::io;
|
||||
use std::str;
|
||||
use std::net::ToSocketAddrs;
|
||||
use getopts::Matches;
|
||||
use std::collections::hash_set::HashSet;
|
||||
use std::io;
|
||||
use std::iter::repeat;
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::str;
|
||||
|
||||
#[cfg(windows)]
|
||||
use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup};
|
||||
#[cfg(windows)]
|
||||
use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW};
|
||||
use uucore::wide::*;
|
||||
#[cfg(windows)]
|
||||
use winapi::shared::minwindef::MAKEWORD;
|
||||
#[cfg(windows)]
|
||||
use uucore::wide::*;
|
||||
use winapi::um::sysinfoapi::{ComputerNamePhysicalDnsHostname, SetComputerNameExW};
|
||||
#[cfg(windows)]
|
||||
use winapi::um::winsock2::{GetHostNameW, WSACleanup, WSAStartup};
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use libc::gethostname;
|
||||
|
@ -63,12 +63,28 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
|
||||
fn execute(args: Vec<String>) -> i32 {
|
||||
let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
|
||||
.optflag("d", "domain", "Display the name of the DNS domain if possible")
|
||||
.optflag("i", "ip-address", "Display the network address(es) of the host")
|
||||
.optflag(
|
||||
"d",
|
||||
"domain",
|
||||
"Display the name of the DNS domain if possible",
|
||||
)
|
||||
.optflag(
|
||||
"i",
|
||||
"ip-address",
|
||||
"Display the network address(es) of the host",
|
||||
)
|
||||
// TODO: support --long
|
||||
.optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)")
|
||||
.optflag("s", "short", "Display the short hostname (the portion before the first dot) if \
|
||||
possible")
|
||||
.optflag(
|
||||
"f",
|
||||
"fqdn",
|
||||
"Display the FQDN (Fully Qualified Domain Name) (default)",
|
||||
)
|
||||
.optflag(
|
||||
"s",
|
||||
"short",
|
||||
"Display the short hostname (the portion before the first dot) if \
|
||||
possible",
|
||||
)
|
||||
.parse(args);
|
||||
|
||||
match matches.free.len() {
|
||||
|
|
|
@ -16,16 +16,16 @@
|
|||
|
||||
#[macro_use]
|
||||
extern crate uucore;
|
||||
use std::ffi::CStr;
|
||||
use uucore::entries::{self, Group, Locate, Passwd};
|
||||
pub use uucore::libc;
|
||||
use uucore::libc::{getlogin, uid_t};
|
||||
use uucore::entries::{self, Group, Locate, Passwd};
|
||||
use uucore::process::{getegid, geteuid, getgid, getuid};
|
||||
use std::ffi::CStr;
|
||||
|
||||
macro_rules! cstr2cow {
|
||||
($v:expr) => (
|
||||
($v:expr) => {
|
||||
unsafe { CStr::from_ptr($v).to_string_lossy() }
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
|
|
|
@ -101,49 +101,115 @@ fn parse_opts(args: Vec<String>) -> getopts::Matches {
|
|||
NAME
|
||||
);
|
||||
new_coreopts!(&syntax, SUMMARY, LONG_HELP)
|
||||
// TODO implement flag
|
||||
.optflagopt("", "backup", "(unimplemented) make a backup of each existing destination\n \
|
||||
file", "CONTROL")
|
||||
// TODO implement flag
|
||||
.optflag("b", "", "(unimplemented) like --backup but does not accept an argument")
|
||||
// TODO implement flag
|
||||
.optflagopt(
|
||||
"",
|
||||
"backup",
|
||||
"(unimplemented) make a backup of each existing destination\n \
|
||||
file",
|
||||
"CONTROL",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflag(
|
||||
"b",
|
||||
"",
|
||||
"(unimplemented) like --backup but does not accept an argument",
|
||||
)
|
||||
.optflag("c", "", "ignored")
|
||||
// TODO implement flag
|
||||
.optflag("C", "compare", "(unimplemented) compare each pair of source and destination\n \
|
||||
files, and in some cases, do not modify the destination at all")
|
||||
.optflag("d", "directory", "treat all arguments as directory names.\n \
|
||||
create all components of the specified directories")
|
||||
// TODO implement flag
|
||||
.optflag("D", "", "(unimplemented) create all leading components of DEST except the\n \
|
||||
last, then copy SOURCE to DEST")
|
||||
// TODO implement flag
|
||||
.optflagopt("g", "group", "(unimplemented) set group ownership, instead of process'\n \
|
||||
current group", "GROUP")
|
||||
.optflagopt("m", "mode", "set permission mode (as in chmod), instead\n \
|
||||
of rwxr-xr-x", "MODE")
|
||||
// TODO implement flag
|
||||
.optflagopt("o", "owner", "(unimplemented) set ownership (super-user only)",
|
||||
"OWNER")
|
||||
// TODO implement flag
|
||||
.optflag("p", "preserve-timestamps", "(unimplemented) apply access/modification times\n \
|
||||
of SOURCE files to corresponding destination files")
|
||||
// TODO implement flag
|
||||
// TODO implement flag
|
||||
.optflag(
|
||||
"C",
|
||||
"compare",
|
||||
"(unimplemented) compare each pair of source and destination\n \
|
||||
files, and in some cases, do not modify the destination at all",
|
||||
)
|
||||
.optflag(
|
||||
"d",
|
||||
"directory",
|
||||
"treat all arguments as directory names.\n \
|
||||
create all components of the specified directories",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflag(
|
||||
"D",
|
||||
"",
|
||||
"(unimplemented) create all leading components of DEST except the\n \
|
||||
last, then copy SOURCE to DEST",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflagopt(
|
||||
"g",
|
||||
"group",
|
||||
"(unimplemented) set group ownership, instead of process'\n \
|
||||
current group",
|
||||
"GROUP",
|
||||
)
|
||||
.optflagopt(
|
||||
"m",
|
||||
"mode",
|
||||
"set permission mode (as in chmod), instead\n \
|
||||
of rwxr-xr-x",
|
||||
"MODE",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflagopt(
|
||||
"o",
|
||||
"owner",
|
||||
"(unimplemented) set ownership (super-user only)",
|
||||
"OWNER",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflag(
|
||||
"p",
|
||||
"preserve-timestamps",
|
||||
"(unimplemented) apply access/modification times\n \
|
||||
of SOURCE files to corresponding destination files",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflag("s", "strip", "(unimplemented) strip symbol tables")
|
||||
// TODO implement flag
|
||||
.optflagopt("", "strip-program", "(unimplemented) program used to strip binaries",
|
||||
"PROGRAM")
|
||||
// TODO implement flag
|
||||
.optopt("S", "suffix", "(unimplemented) override the usual backup suffix", "SUFFIX")
|
||||
// TODO implement flag
|
||||
.optopt("t", "target-directory", "(unimplemented) move all SOURCE arguments into\n \
|
||||
DIRECTORY", "DIRECTORY")
|
||||
// TODO implement flag
|
||||
.optflag("T", "no-target-directory", "(unimplemented) treat DEST as a normal file")
|
||||
// TODO implement flag
|
||||
.optflagopt(
|
||||
"",
|
||||
"strip-program",
|
||||
"(unimplemented) program used to strip binaries",
|
||||
"PROGRAM",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optopt(
|
||||
"S",
|
||||
"suffix",
|
||||
"(unimplemented) override the usual backup suffix",
|
||||
"SUFFIX",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optopt(
|
||||
"t",
|
||||
"target-directory",
|
||||
"(unimplemented) move all SOURCE arguments into\n \
|
||||
DIRECTORY",
|
||||
"DIRECTORY",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflag(
|
||||
"T",
|
||||
"no-target-directory",
|
||||
"(unimplemented) treat DEST as a normal file",
|
||||
)
|
||||
.optflag("v", "verbose", "explain what is being done")
|
||||
// TODO implement flag
|
||||
.optflag("P", "preserve-context", "(unimplemented) preserve security context")
|
||||
// TODO implement flag
|
||||
.optflagopt("Z", "context", "(unimplemented) set security context of files and\n \
|
||||
directories", "CONTEXT")
|
||||
// TODO implement flag
|
||||
.optflag(
|
||||
"P",
|
||||
"preserve-context",
|
||||
"(unimplemented) preserve security context",
|
||||
)
|
||||
// TODO implement flag
|
||||
.optflagopt(
|
||||
"Z",
|
||||
"context",
|
||||
"(unimplemented) set security context of files and\n \
|
||||
directories",
|
||||
"CONTEXT",
|
||||
)
|
||||
.parse(args)
|
||||
}
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
extern crate libc;
|
||||
|
||||
use std::path::Path;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
#[cfg(not(windows))]
|
||||
use uucore::mode;
|
||||
|
||||
|
|
|
@ -14,10 +14,10 @@ extern crate clap;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use clap::{App, Arg};
|
||||
use std::cmp::{min, Ordering};
|
||||
use std::fs::File;
|
||||
use std::io::{stdin, BufRead, BufReader, Lines, Stdin};
|
||||
use std::cmp::{min, Ordering};
|
||||
use clap::{App, Arg};
|
||||
|
||||
static NAME: &str = "join";
|
||||
static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
@ -425,11 +425,13 @@ impl<'a> State<'a> {
|
|||
if repr.uses_format() {
|
||||
repr.print_format(|spec| match *spec {
|
||||
Spec::Key => line.get_field(self.key),
|
||||
Spec::Field(file_num, field_num) => if file_num == self.file_num {
|
||||
line.get_field(field_num)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
Spec::Field(file_num, field_num) => {
|
||||
if file_num == self.file_num {
|
||||
line.get_field(field_num)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
repr.print_field(line.get_field(self.key));
|
||||
|
|
|
@ -74,9 +74,7 @@ fn handle_obsolete(mut args: Vec<String>) -> (Vec<String>, Option<String>) {
|
|||
while i < args.len() {
|
||||
// this is safe because slice is valid when it is referenced
|
||||
let slice = &args[i].clone();
|
||||
if slice.starts_with('-') && slice.len() > 1
|
||||
&& slice.chars().nth(1).unwrap().is_digit(10)
|
||||
{
|
||||
if slice.starts_with('-') && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
|
||||
let val = &slice[1..];
|
||||
match val.parse() {
|
||||
Ok(num) => {
|
||||
|
|
|
@ -13,8 +13,8 @@
|
|||
extern crate uucore;
|
||||
|
||||
use std::fs::hard_link;
|
||||
use std::path::Path;
|
||||
use std::io::Error;
|
||||
use std::path::Path;
|
||||
|
||||
static SYNTAX: &str = "[OPTIONS] FILE1 FILE2";
|
||||
static SUMMARY: &str = "Create a link named FILE2 to FILE1";
|
||||
|
|
51
src/ln/ln.rs
51
src/ln/ln.rs
|
@ -67,24 +67,45 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
NAME
|
||||
);
|
||||
let matches = new_coreopts!(&syntax, SUMMARY, LONG_HELP)
|
||||
.optflag("b", "", "make a backup of each file that would otherwise be overwritten or \
|
||||
removed")
|
||||
.optflagopt("", "backup", "make a backup of each file that would otherwise be overwritten \
|
||||
or removed", "METHOD")
|
||||
// TODO: opts.optflag("d", "directory", "allow users with appropriate privileges to attempt \
|
||||
// to make hard links to directories");
|
||||
.optflag(
|
||||
"b",
|
||||
"",
|
||||
"make a backup of each file that would otherwise be overwritten or \
|
||||
removed",
|
||||
)
|
||||
.optflagopt(
|
||||
"",
|
||||
"backup",
|
||||
"make a backup of each file that would otherwise be overwritten \
|
||||
or removed",
|
||||
"METHOD",
|
||||
)
|
||||
// TODO: opts.optflag("d", "directory", "allow users with appropriate privileges to attempt \
|
||||
// to make hard links to directories");
|
||||
.optflag("f", "force", "remove existing destination files")
|
||||
.optflag("i", "interactive", "prompt whether to remove existing destination files")
|
||||
// TODO: opts.optflag("L", "logical", "dereference TARGETs that are symbolic links");
|
||||
// TODO: opts.optflag("n", "no-dereference", "treat LINK_NAME as a normal file if it is a \
|
||||
// symbolic link to a directory");
|
||||
// TODO: opts.optflag("P", "physical", "make hard links directly to symbolic links");
|
||||
// TODO: opts.optflag("r", "relative", "create symbolic links relative to link location");
|
||||
.optflag(
|
||||
"i",
|
||||
"interactive",
|
||||
"prompt whether to remove existing destination files",
|
||||
)
|
||||
// TODO: opts.optflag("L", "logical", "dereference TARGETs that are symbolic links");
|
||||
// TODO: opts.optflag("n", "no-dereference", "treat LINK_NAME as a normal file if it is a \
|
||||
// symbolic link to a directory");
|
||||
// TODO: opts.optflag("P", "physical", "make hard links directly to symbolic links");
|
||||
// TODO: opts.optflag("r", "relative", "create symbolic links relative to link location");
|
||||
.optflag("s", "symbolic", "make symbolic links instead of hard links")
|
||||
.optopt("S", "suffix", "override the usual backup suffix", "SUFFIX")
|
||||
.optopt("t", "target-directory", "specify the DIRECTORY in which to create the links",
|
||||
"DIRECTORY")
|
||||
.optflag("T", "no-target-directory", "treat LINK_NAME as a normal file always")
|
||||
.optopt(
|
||||
"t",
|
||||
"target-directory",
|
||||
"specify the DIRECTORY in which to create the links",
|
||||
"DIRECTORY",
|
||||
)
|
||||
.optflag(
|
||||
"T",
|
||||
"no-target-directory",
|
||||
"treat LINK_NAME as a normal file always",
|
||||
)
|
||||
.optflag("v", "verbose", "print name of each linked file")
|
||||
.parse(args);
|
||||
|
||||
|
|
55
src/ls/ls.rs
55
src/ls/ls.rs
|
@ -9,12 +9,12 @@
|
|||
//
|
||||
|
||||
extern crate getopts;
|
||||
extern crate number_prefix;
|
||||
extern crate term_grid;
|
||||
extern crate termsize;
|
||||
extern crate time;
|
||||
extern crate unicode_width;
|
||||
extern crate number_prefix;
|
||||
use number_prefix::{Standalone, Prefixed, decimal_prefix};
|
||||
use number_prefix::{decimal_prefix, Prefixed, Standalone};
|
||||
use term_grid::{Cell, Direction, Filling, Grid, GridOptions};
|
||||
use time::{strftime, Timespec};
|
||||
|
||||
|
@ -30,20 +30,19 @@ extern crate lazy_static;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
#[cfg(unix)]
|
||||
use uucore::libc::{mode_t, S_ISGID, S_ISUID, S_ISVTX, S_IWOTH,
|
||||
S_IXGRP, S_IXOTH, S_IXUSR};
|
||||
use uucore::libc::{mode_t, S_ISGID, S_ISUID, S_ISVTX, S_IWOTH, S_IXGRP, S_IXOTH, S_IXUSR};
|
||||
|
||||
use std::fs;
|
||||
use std::fs::{DirEntry, FileType, Metadata};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::cmp::Reverse;
|
||||
#[cfg(unix)]
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::fs::{DirEntry, FileType, Metadata};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::FileTypeExt;
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
#[cfg(unix)]
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
|
@ -63,7 +62,8 @@ static DEFAULT_COLORS: &str = "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do
|
|||
|
||||
#[cfg(unix)]
|
||||
lazy_static! {
|
||||
static ref LS_COLORS: String = std::env::var("LS_COLORS").unwrap_or_else(|_| DEFAULT_COLORS.to_string());
|
||||
static ref LS_COLORS: String =
|
||||
std::env::var("LS_COLORS").unwrap_or_else(|_| DEFAULT_COLORS.to_string());
|
||||
static ref COLOR_MAP: HashMap<&'static str, &'static str> = {
|
||||
let codes = LS_COLORS.split(':');
|
||||
let mut map = HashMap::new();
|
||||
|
@ -163,7 +163,12 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
directory. This is especially useful when listing very large directories, \
|
||||
since not doing any sorting can be noticeably faster.",
|
||||
)
|
||||
.optflagopt("", "color", "Color output based on file type.", "always|auto|never")
|
||||
.optflagopt(
|
||||
"",
|
||||
"color",
|
||||
"Color output based on file type.",
|
||||
"always|auto|never",
|
||||
)
|
||||
.parse(args);
|
||||
|
||||
list(matches);
|
||||
|
@ -357,19 +362,17 @@ fn display_items(items: &[PathBuf], strip: Option<&Path>, options: &getopts::Mat
|
|||
}
|
||||
} else {
|
||||
if !options.opt_present("1") {
|
||||
let names = items
|
||||
.iter()
|
||||
.filter_map(|i| {
|
||||
let md = get_metadata(i, options);
|
||||
match md {
|
||||
Err(e) => {
|
||||
let filename = get_file_name(i, strip);
|
||||
show_error!("{}: {}", filename, e);
|
||||
None
|
||||
}
|
||||
Ok(md) => Some(display_file_name(&i, strip, &md, options)),
|
||||
let names = items.iter().filter_map(|i| {
|
||||
let md = get_metadata(i, options);
|
||||
match md {
|
||||
Err(e) => {
|
||||
let filename = get_file_name(i, strip);
|
||||
show_error!("{}: {}", filename, e);
|
||||
None
|
||||
}
|
||||
});
|
||||
Ok(md) => Some(display_file_name(&i, strip, &md, options)),
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(size) = termsize::get() {
|
||||
let mut grid = Grid::new(GridOptions {
|
||||
|
@ -512,7 +515,7 @@ fn display_file_size(metadata: &Metadata, options: &getopts::Matches) -> String
|
|||
if options.opt_present("human-readable") {
|
||||
match decimal_prefix(metadata.len() as f64) {
|
||||
Standalone(bytes) => bytes.to_string(),
|
||||
Prefixed(prefix, bytes) => format!("{:.2}{}", bytes, prefix).to_uppercase()
|
||||
Prefixed(prefix, bytes) => format!("{:.2}{}", bytes, prefix).to_uppercase(),
|
||||
}
|
||||
} else {
|
||||
metadata.len().to_string()
|
||||
|
@ -596,9 +599,9 @@ fn color_name(name: String, typ: &str) -> String {
|
|||
|
||||
#[cfg(unix)]
|
||||
macro_rules! has {
|
||||
($mode:expr, $perm:expr) => (
|
||||
($mode:expr, $perm:expr) => {
|
||||
$mode & ($perm as mode_t) != 0
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
|
|
@ -60,10 +60,10 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
let res: Option<u16> = u16::from_str_radix(&m, 8).ok();
|
||||
match res {
|
||||
Some(r) => r,
|
||||
_ => crash!(1, "no mode given")
|
||||
_ => crash!(1, "no mode given"),
|
||||
}
|
||||
},
|
||||
_ => 0o755 as u16
|
||||
}
|
||||
_ => 0o755 as u16,
|
||||
};
|
||||
|
||||
let dirs = matches.free;
|
||||
|
@ -112,7 +112,11 @@ fn exec(dirs: Vec<String>, recursive: bool, mode: u16, verbose: bool) -> i32 {
|
|||
* Wrapper to catch errors, return 1 if failed
|
||||
*/
|
||||
fn mkdir(path: &Path, recursive: bool, mode: u16, verbose: bool) -> i32 {
|
||||
let create_dir = if recursive { fs::create_dir_all } else { fs::create_dir };
|
||||
let create_dir = if recursive {
|
||||
fs::create_dir_all
|
||||
} else {
|
||||
fs::create_dir
|
||||
};
|
||||
if let Err(e) = create_dir(path) {
|
||||
show_info!("{}: {}", path.display(), e.to_string());
|
||||
return 1;
|
||||
|
@ -124,17 +128,13 @@ fn mkdir(path: &Path, recursive: bool, mode: u16, verbose: bool) -> i32 {
|
|||
|
||||
#[cfg(any(unix, target_os = "redox"))]
|
||||
fn chmod(path: &Path, mode: u16) -> i32 {
|
||||
use fs::{Permissions, set_permissions};
|
||||
use std::os::unix::fs::{PermissionsExt};
|
||||
use fs::{set_permissions, Permissions};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let mode = Permissions::from_mode(u32::from(mode));
|
||||
|
||||
if let Err(err) = set_permissions(path, mode) {
|
||||
show_error!(
|
||||
"{}: {}",
|
||||
path.display(),
|
||||
err
|
||||
);
|
||||
show_error!("{}: {}", path.display(), err);
|
||||
return 1;
|
||||
}
|
||||
0
|
||||
|
|
|
@ -77,10 +77,7 @@ Create a FIFO with the given name.",
|
|||
for f in &matches.free {
|
||||
let err = unsafe {
|
||||
let name = CString::new(f.as_bytes()).unwrap();
|
||||
mkfifo(
|
||||
name.as_ptr(),
|
||||
mode as libc::mode_t,
|
||||
)
|
||||
mkfifo(name.as_ptr(), mode as libc::mode_t)
|
||||
};
|
||||
if err == -1 {
|
||||
show_error!(
|
||||
|
|
|
@ -31,8 +31,7 @@ const MODE_RW_UGO: mode_t = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_
|
|||
#[inline(always)]
|
||||
fn makedev(maj: u64, min: u64) -> dev_t {
|
||||
// pick up from <sys/sysmacros.h>
|
||||
((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32))
|
||||
as dev_t
|
||||
((min & 0xff) | ((maj & 0xfff) << 8) | ((min & !0xff) << 12) | ((maj & !0xfff) << 32)) as dev_t
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
|
|
|
@ -17,9 +17,9 @@ extern crate tempfile;
|
|||
extern crate uucore;
|
||||
|
||||
use std::env;
|
||||
use std::path::{is_separator, PathBuf};
|
||||
use std::mem::forget;
|
||||
use std::iter;
|
||||
use std::mem::forget;
|
||||
use std::path::{is_separator, PathBuf};
|
||||
|
||||
use rand::Rng;
|
||||
use tempfile::NamedTempFileOptions;
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
// Mainly taken from crate `tempdir`
|
||||
|
||||
extern crate rand;
|
||||
use rand::{thread_rng, Rng};
|
||||
use rand::distributions::Alphanumeric;
|
||||
use rand::{thread_rng, Rng};
|
||||
|
||||
use std::io::Result as IOResult;
|
||||
use std::io::{Error, ErrorKind};
|
||||
|
|
|
@ -15,8 +15,8 @@ extern crate getopts;
|
|||
extern crate uucore;
|
||||
|
||||
use getopts::Options;
|
||||
use std::io::{stdout, Read, Write};
|
||||
use std::fs::File;
|
||||
use std::io::{stdout, Read, Write};
|
||||
|
||||
#[cfg(all(unix, not(target_os = "fuchsia")))]
|
||||
extern crate nix;
|
||||
|
|
27
src/mv/mv.rs
27
src/mv/mv.rs
|
@ -14,8 +14,8 @@ extern crate getopts;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use std::fs;
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::io::{stdin, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
@ -202,7 +202,9 @@ fn determine_backup_suffix(backup_mode: BackupMode, matches: &getopts::Matches)
|
|||
);
|
||||
}
|
||||
}
|
||||
} else if let (Ok(s), BackupMode::SimpleBackup) = (env::var("SIMPLE_BACKUP_SUFFIX"), backup_mode) {
|
||||
} else if let (Ok(s), BackupMode::SimpleBackup) =
|
||||
(env::var("SIMPLE_BACKUP_SUFFIX"), backup_mode)
|
||||
{
|
||||
s
|
||||
} else {
|
||||
"~".to_owned()
|
||||
|
@ -257,7 +259,9 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 {
|
|||
Err(e) => {
|
||||
show_error!(
|
||||
"cannot move ‘{}’ to ‘{}’: {}",
|
||||
source.display(), target.display(), e
|
||||
source.display(),
|
||||
target.display(),
|
||||
e
|
||||
);
|
||||
1
|
||||
}
|
||||
|
@ -269,7 +273,8 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 {
|
|||
} else if target.exists() && source.is_dir() {
|
||||
show_error!(
|
||||
"cannot overwrite non-directory ‘{}’ with directory ‘{}’",
|
||||
target.display(), source.display()
|
||||
target.display(),
|
||||
source.display()
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
@ -359,8 +364,7 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> {
|
|||
fs::rename(to, p)?;
|
||||
}
|
||||
|
||||
if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()?
|
||||
{
|
||||
if b.update && fs::metadata(from)?.modified()? <= fs::metadata(to)?.modified()? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
@ -372,7 +376,10 @@ fn rename(from: &PathBuf, to: &PathBuf, b: &Behaviour) -> Result<()> {
|
|||
if is_empty_dir(to) {
|
||||
fs::remove_dir(to)?
|
||||
} else {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::Other, "Directory not empty"));
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Directory not empty",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -425,9 +432,7 @@ fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf {
|
|||
|
||||
fn is_empty_dir(path: &PathBuf) -> bool {
|
||||
match fs::read_dir(path) {
|
||||
Ok(contents) => {
|
||||
contents.peekable().peek().is_none()
|
||||
},
|
||||
Err(_e) => { false }
|
||||
Ok(contents) => contents.peekable().peek().is_none(),
|
||||
Err(_e) => false,
|
||||
}
|
||||
}
|
||||
|
|
|
@ -336,7 +336,9 @@ fn nl<T: Read>(reader: &mut BufReader<T>, settings: &Settings) {
|
|||
// A line number is to be printed.
|
||||
let w = if settings.number_width > line_no_width {
|
||||
settings.number_width - line_no_width
|
||||
} else { 0 };
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let fill: String = repeat(fill_char).take(w).collect();
|
||||
match settings.number_format {
|
||||
NumberFormat::Left => println!(
|
||||
|
|
|
@ -15,14 +15,14 @@ extern crate libc;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use libc::{c_char, execvp, signal, dup2};
|
||||
use libc::{c_char, dup2, execvp, signal};
|
||||
use libc::{SIGHUP, SIG_IGN};
|
||||
use std::env;
|
||||
use std::ffi::CString;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::Error;
|
||||
use std::os::unix::prelude::*;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::env;
|
||||
use uucore::fs::{is_stderr_interactive, is_stdin_interactive, is_stdout_interactive};
|
||||
|
||||
static NAME: &str = "nohup";
|
||||
|
|
|
@ -108,7 +108,12 @@ Print the number of cores available to the current process.",
|
|||
0
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd"))]
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "macos",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd"
|
||||
))]
|
||||
fn num_cpus_all() -> usize {
|
||||
let nprocs = unsafe { libc::sysconf(_SC_NPROCESSORS_CONF) };
|
||||
if nprocs == 1 {
|
||||
|
@ -123,8 +128,12 @@ fn num_cpus_all() -> usize {
|
|||
}
|
||||
|
||||
// Other platform(e.g., windows), num_cpus::get() directly.
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd",
|
||||
target_os = "netbsd")))]
|
||||
#[cfg(not(any(
|
||||
target_os = "linux",
|
||||
target_os = "macos",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd"
|
||||
)))]
|
||||
fn num_cpus_all() -> usize {
|
||||
num_cpus::get()
|
||||
}
|
||||
|
|
|
@ -70,7 +70,8 @@ impl fmt::Display for DisplayableSuffix {
|
|||
RawSuffix::E => write!(f, "E"),
|
||||
RawSuffix::Z => write!(f, "Z"),
|
||||
RawSuffix::Y => write!(f, "Y"),
|
||||
}.and_then(|()| match with_i {
|
||||
}
|
||||
.and_then(|()| match with_i {
|
||||
true => write!(f, "i"),
|
||||
false => Ok(()),
|
||||
})
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
// workaround until https://github.com/BurntSushi/byteorder/issues/41 has been fixed
|
||||
// based on: https://github.com/netvl/immeta/blob/4460ee/src/utils.rs#L76
|
||||
|
||||
use byteorder::{BigEndian, LittleEndian, NativeEndian};
|
||||
use byteorder::ByteOrder as ByteOrderTrait;
|
||||
use byteorder::{BigEndian, LittleEndian, NativeEndian};
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub enum ByteOrder {
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
use std::io;
|
||||
use byteorder_io::ByteOrder;
|
||||
use half::f16;
|
||||
use multifilereader::HasError;
|
||||
use peekreader::PeekRead;
|
||||
use half::f16;
|
||||
use std::io;
|
||||
|
||||
/// Processes an input and provides access to the data read in various formats
|
||||
///
|
||||
|
@ -60,7 +60,8 @@ where
|
|||
/// calls `peek_read` on the internal stream to (re)fill the buffer. Returns a
|
||||
/// MemoryDecoder providing access to the result or returns an i/o error.
|
||||
pub fn peek_read(&mut self) -> io::Result<MemoryDecoder> {
|
||||
match self.input
|
||||
match self
|
||||
.input
|
||||
.peek_read(self.data.as_mut_slice(), self.reserved_peek_length)
|
||||
{
|
||||
Ok((n, p)) => {
|
||||
|
@ -157,9 +158,9 @@ impl<'a> MemoryDecoder<'a> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Cursor;
|
||||
use peekreader::PeekReader;
|
||||
use byteorder_io::ByteOrder;
|
||||
use peekreader::PeekReader;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
fn smoke_test() {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
// https://github.com/lazy-bitfield/rust-mockstream/pull/2
|
||||
|
||||
use std::io::{Cursor, Error, ErrorKind, Read, Result};
|
||||
use std::error::Error as errorError;
|
||||
use std::io::{Cursor, Error, ErrorKind, Read, Result};
|
||||
|
||||
/// `FailingMockStream` mocks a stream which will fail upon read or write
|
||||
///
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::BufReader;
|
||||
use std::fs::File;
|
||||
use std::vec::Vec;
|
||||
|
||||
pub enum InputSource<'a> {
|
||||
|
@ -125,8 +125,8 @@ impl<'b> HasError for MultifileReader<'b> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Cursor, ErrorKind, Read};
|
||||
use mockstream::*;
|
||||
use std::io::{Cursor, ErrorKind, Read};
|
||||
|
||||
#[test]
|
||||
fn test_multi_file_reader_one_read() {
|
||||
|
|
41
src/od/od.rs
41
src/od/od.rs
|
@ -16,36 +16,36 @@ extern crate half;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
mod multifilereader;
|
||||
mod partialreader;
|
||||
mod peekreader;
|
||||
mod byteorder_io;
|
||||
mod formatteriteminfo;
|
||||
mod prn_int;
|
||||
mod prn_char;
|
||||
mod prn_float;
|
||||
mod parse_nrofbytes;
|
||||
mod parse_formats;
|
||||
mod parse_inputs;
|
||||
mod inputoffset;
|
||||
mod inputdecoder;
|
||||
mod output_info;
|
||||
mod inputoffset;
|
||||
#[cfg(test)]
|
||||
mod mockstream;
|
||||
mod multifilereader;
|
||||
mod output_info;
|
||||
mod parse_formats;
|
||||
mod parse_inputs;
|
||||
mod parse_nrofbytes;
|
||||
mod partialreader;
|
||||
mod peekreader;
|
||||
mod prn_char;
|
||||
mod prn_float;
|
||||
mod prn_int;
|
||||
|
||||
use std::cmp;
|
||||
use byteorder_io::*;
|
||||
use formatteriteminfo::*;
|
||||
use inputdecoder::{InputDecoder, MemoryDecoder};
|
||||
use inputoffset::{InputOffset, Radix};
|
||||
use multifilereader::*;
|
||||
use output_info::OutputInfo;
|
||||
use parse_formats::{parse_format_flags, ParsedFormatterItemInfo};
|
||||
use parse_inputs::{parse_inputs, CommandLineInputs};
|
||||
use parse_nrofbytes::parse_number_of_bytes;
|
||||
use partialreader::*;
|
||||
use peekreader::*;
|
||||
use formatteriteminfo::*;
|
||||
use parse_nrofbytes::parse_number_of_bytes;
|
||||
use parse_formats::{parse_format_flags, ParsedFormatterItemInfo};
|
||||
use prn_char::format_ascii_dump;
|
||||
use parse_inputs::{parse_inputs, CommandLineInputs};
|
||||
use inputoffset::{InputOffset, Radix};
|
||||
use inputdecoder::{InputDecoder, MemoryDecoder};
|
||||
use output_info::OutputInfo;
|
||||
use std::cmp;
|
||||
|
||||
static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const PEEK_BUFFER_SIZE: usize = 4; // utf-8 can be 4 bytes
|
||||
|
@ -379,7 +379,8 @@ where
|
|||
memory_decoder.zero_out_buffer(length, max_used);
|
||||
}
|
||||
|
||||
if !output_info.output_duplicates && length == line_bytes
|
||||
if !output_info.output_duplicates
|
||||
&& length == line_bytes
|
||||
&& memory_decoder.get_buffer(0) == &previous_bytes[..]
|
||||
{
|
||||
if !duplicate_line {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use formatteriteminfo::FormatterItemInfo;
|
||||
use parse_formats::ParsedFormatterItemInfo;
|
||||
use std::cmp;
|
||||
use std::slice::Iter;
|
||||
use parse_formats::ParsedFormatterItemInfo;
|
||||
use formatteriteminfo::FormatterItemInfo;
|
||||
|
||||
/// Size in bytes of the max datatype. ie set to 16 for 128-bit numbers.
|
||||
const MAX_BYTES_PER_UNIT: usize = 8;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use formatteriteminfo::FormatterItemInfo;
|
||||
use prn_int::*;
|
||||
use prn_char::*;
|
||||
use prn_float::*;
|
||||
use prn_int::*;
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct ParsedFormatterItemInfo {
|
||||
|
@ -539,7 +539,8 @@ fn test_mixed_formats() {
|
|||
"--".to_string(),
|
||||
"-h".to_string(),
|
||||
"--format=f8".to_string(),
|
||||
]).unwrap(),
|
||||
])
|
||||
.unwrap(),
|
||||
vec![
|
||||
ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC64S, false), // I
|
||||
ParsedFormatterItemInfo::new(FORMAT_ITEM_DEC8U, true), // tu1z
|
||||
|
|
|
@ -323,23 +323,27 @@ mod tests {
|
|||
parse_inputs(&MockOptions::new(
|
||||
vec!["file1", "10", "10"],
|
||||
vec!["traditional"]
|
||||
)).unwrap()
|
||||
))
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
parse_inputs(&MockOptions::new(
|
||||
vec!["10", "file1", "10"],
|
||||
vec!["traditional"],
|
||||
)).unwrap_err();
|
||||
))
|
||||
.unwrap_err();
|
||||
|
||||
parse_inputs(&MockOptions::new(
|
||||
vec!["10", "10", "file1"],
|
||||
vec!["traditional"],
|
||||
)).unwrap_err();
|
||||
))
|
||||
.unwrap_err();
|
||||
|
||||
parse_inputs(&MockOptions::new(
|
||||
vec!["10", "10", "10", "10"],
|
||||
vec!["traditional"],
|
||||
)).unwrap_err();
|
||||
))
|
||||
.unwrap_err();
|
||||
}
|
||||
|
||||
fn parse_offset_operand_str(s: &str) -> Result<usize, &'static str> {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use multifilereader::HasError;
|
||||
use std::cmp;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use multifilereader::HasError;
|
||||
|
||||
/// When a large number of bytes must be skipped, it will be read into a
|
||||
/// dynamically allocated buffer. The buffer will be limited to this size.
|
||||
|
@ -21,11 +21,7 @@ impl<R> PartialReader<R> {
|
|||
/// `skip` bytes, and limits the output to `limit` bytes. Set `limit`
|
||||
/// to `None` if there should be no limit.
|
||||
pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self {
|
||||
PartialReader {
|
||||
inner,
|
||||
skip,
|
||||
limit,
|
||||
}
|
||||
PartialReader { inner, skip, limit }
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -77,9 +73,9 @@ impl<R: HasError> HasError for PartialReader<R> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Cursor, ErrorKind, Read};
|
||||
use std::error::Error;
|
||||
use mockstream::*;
|
||||
use std::error::Error;
|
||||
use std::io::{Cursor, ErrorKind, Read};
|
||||
|
||||
#[test]
|
||||
fn test_read_without_limits() {
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
//! Contains the trait `PeekRead` and type `PeekReader` implementing it.
|
||||
|
||||
use multifilereader::HasError;
|
||||
use std::io;
|
||||
use std::io::{Read, Write};
|
||||
use multifilereader::HasError;
|
||||
|
||||
/// A trait which supplies a function to peek into a stream without
|
||||
/// actually reading it.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use std::str::from_utf8;
|
||||
use formatteriteminfo::*;
|
||||
use std::str::from_utf8;
|
||||
|
||||
pub static FORMAT_ITEM_A: FormatterItemInfo = FormatterItemInfo {
|
||||
byte_size: 1,
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
use std::num::FpCategory;
|
||||
use formatteriteminfo::*;
|
||||
use half::f16;
|
||||
use std::f32;
|
||||
use std::f64;
|
||||
use formatteriteminfo::*;
|
||||
use std::num::FpCategory;
|
||||
|
||||
pub static FORMAT_ITEM_F16: FormatterItemInfo = FormatterItemInfo {
|
||||
byte_size: 2,
|
||||
|
|
|
@ -1,11 +1,23 @@
|
|||
use formatteriteminfo::*;
|
||||
|
||||
/// format string to print octal using `int_writer_unsigned`
|
||||
macro_rules! OCT { () => { " {:0width$o}" }}
|
||||
macro_rules! OCT {
|
||||
() => {
|
||||
" {:0width$o}"
|
||||
};
|
||||
}
|
||||
/// format string to print hexadecimal using `int_writer_unsigned`
|
||||
macro_rules! HEX { () => { " {:0width$x}" }}
|
||||
macro_rules! HEX {
|
||||
() => {
|
||||
" {:0width$x}"
|
||||
};
|
||||
}
|
||||
/// format string to print decimal using `int_writer_unsigned` or `int_writer_signed`
|
||||
macro_rules! DEC { () => { " {:width$}" }}
|
||||
macro_rules! DEC {
|
||||
() => {
|
||||
" {:width$}"
|
||||
};
|
||||
}
|
||||
|
||||
/// defines a static struct of type `FormatterItemInfo` called `$NAME`
|
||||
///
|
||||
|
@ -15,9 +27,7 @@ macro_rules! DEC { () => { " {:width$}" }}
|
|||
macro_rules! int_writer_unsigned {
|
||||
($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => {
|
||||
fn $function(p: u64) -> String {
|
||||
format!($format_str,
|
||||
p,
|
||||
width = $print_width - 1)
|
||||
format!($format_str, p, width = $print_width - 1)
|
||||
}
|
||||
|
||||
pub static $NAME: FormatterItemInfo = FormatterItemInfo {
|
||||
|
@ -25,7 +35,7 @@ macro_rules! int_writer_unsigned {
|
|||
print_width: $print_width,
|
||||
formatter: FormatWriter::IntWriter($function),
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// defines a static struct of type `FormatterItemInfo` called `$NAME`
|
||||
|
@ -37,9 +47,7 @@ macro_rules! int_writer_signed {
|
|||
($NAME:ident, $byte_size:expr, $print_width:expr, $function:ident, $format_str:expr) => {
|
||||
fn $function(p: u64) -> String {
|
||||
let s = sign_extend(p, $byte_size);
|
||||
format!($format_str,
|
||||
s,
|
||||
width = $print_width - 1)
|
||||
format!($format_str, s, width = $print_width - 1)
|
||||
}
|
||||
|
||||
pub static $NAME: FormatterItemInfo = FormatterItemInfo {
|
||||
|
@ -47,7 +55,7 @@ macro_rules! int_writer_signed {
|
|||
print_width: $print_width,
|
||||
formatter: FormatWriter::IntWriter($function),
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Extends a signed number in `item` of `itembytes` bytes into a (signed) i64
|
||||
|
|
|
@ -14,9 +14,9 @@ extern crate getopts;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{stdin, BufRead, BufReader, Read};
|
||||
use std::iter::repeat;
|
||||
use std::fs::File;
|
||||
use std::path::Path;
|
||||
|
||||
static NAME: &str = "paste";
|
||||
|
@ -60,7 +60,9 @@ FILE, separated by TABs, to standard output.",
|
|||
println!("{} {}", NAME, VERSION);
|
||||
} else {
|
||||
let serial = matches.opt_present("serial");
|
||||
let delimiters = matches.opt_str("delimiters").unwrap_or_else(|| "\t".to_owned());
|
||||
let delimiters = matches
|
||||
.opt_str("delimiters")
|
||||
.unwrap_or_else(|| "\t".to_owned());
|
||||
paste(matches.free, serial, delimiters);
|
||||
}
|
||||
|
||||
|
|
|
@ -89,7 +89,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
let mut res = if matches.free.is_empty() {
|
||||
show_error!("missing operand\nTry {} --help for more information", NAME);
|
||||
false
|
||||
} else { true };
|
||||
} else {
|
||||
true
|
||||
};
|
||||
// free strings are path operands
|
||||
// FIXME: TCS, seems inefficient and overly verbose (?)
|
||||
for p in matches.free {
|
||||
|
@ -233,12 +235,14 @@ fn check_searchable(path: &str) -> bool {
|
|||
// we use lstat, just like the original implementation
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(_) => true,
|
||||
Err(e) => if e.kind() == ErrorKind::NotFound {
|
||||
true
|
||||
} else {
|
||||
writeln!(&mut std::io::stderr(), "{}", e);
|
||||
false
|
||||
},
|
||||
Err(e) => {
|
||||
if e.kind() == ErrorKind::NotFound {
|
||||
true
|
||||
} else {
|
||||
writeln!(&mut std::io::stderr(), "{}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -11,9 +11,9 @@
|
|||
|
||||
#[macro_use]
|
||||
extern crate uucore;
|
||||
use uucore::utmpx::{self, time, Utmpx};
|
||||
use uucore::libc::S_IWGRP;
|
||||
use uucore::entries::{Locate, Passwd};
|
||||
use uucore::libc::S_IWGRP;
|
||||
use uucore::utmpx::{self, time, Utmpx};
|
||||
|
||||
use std::io::prelude::*;
|
||||
use std::io::BufReader;
|
||||
|
@ -291,7 +291,7 @@ impl Pinky {
|
|||
if self.names.is_empty() {
|
||||
self.print_entry(&ut)
|
||||
} else if self.names.iter().any(|n| n.as_str() == ut.user()) {
|
||||
self.print_entry(&ut);
|
||||
self.print_entry(&ut);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
//! stdio convenience fns
|
||||
|
||||
use std::io::{stderr, stdout, Write};
|
||||
use std::env;
|
||||
use std::io::{stderr, stdout, Write};
|
||||
|
||||
pub const EXIT_OK: i32 = 0;
|
||||
pub const EXIT_ERR: i32 = 1;
|
||||
|
|
|
@ -5,13 +5,13 @@
|
|||
//! 2. feeds remaining arguments into function
|
||||
//! that prints tokens.
|
||||
|
||||
use cli;
|
||||
use itertools::put_back_n;
|
||||
use std::iter::Peekable;
|
||||
use std::slice::Iter;
|
||||
use itertools::put_back_n;
|
||||
use cli;
|
||||
use tokenize::sub::Sub;
|
||||
use tokenize::token::{Token, Tokenizer};
|
||||
use tokenize::unescaped_text::UnescapedText;
|
||||
use tokenize::sub::Sub;
|
||||
|
||||
pub struct Memo {
|
||||
tokens: Vec<Box<dyn Token>>,
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
pub mod token;
|
||||
pub mod sub;
|
||||
pub mod unescaped_text;
|
||||
#[allow(clippy::module_inception)]
|
||||
mod num_format;
|
||||
pub mod sub;
|
||||
pub mod token;
|
||||
pub mod unescaped_text;
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
//! Primitives used by num_format and sub_modules.
|
||||
//! never dealt with above (e.g. Sub Tokenizer never uses these)
|
||||
|
||||
use std::str::Chars;
|
||||
use itertools::{put_back_n, PutBackN};
|
||||
use cli;
|
||||
use super::format_field::FormatField;
|
||||
use cli;
|
||||
use itertools::{put_back_n, PutBackN};
|
||||
use std::str::Chars;
|
||||
|
||||
// contains the rough ingredients to final
|
||||
// output for a number, organized together
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
#[cfg(test)]
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
//! formatter for %a %F C99 Hex-floating-point subs
|
||||
use super::super::format_field::FormatField;
|
||||
use super::super::formatter::{FormatPrimitive, Formatter, InPrefix};
|
||||
use super::float_common::{primitive_to_str_common, FloatAnalysis};
|
||||
use super::base_conv;
|
||||
use super::base_conv::RadixDef;
|
||||
use super::float_common::{primitive_to_str_common, FloatAnalysis};
|
||||
|
||||
pub struct CninetyNineHexFloatf {
|
||||
as_num: f64,
|
||||
|
|
|
@ -28,9 +28,9 @@ fn has_enough_digits(
|
|||
false //undecidable without converting
|
||||
}
|
||||
} else if hex_input {
|
||||
((((string_position - 1) - starting_position) * 9) / 8 >= limit)
|
||||
((((string_position - 1) - starting_position) * 9) / 8 >= limit)
|
||||
} else {
|
||||
((string_position - 1) - starting_position >= limit)
|
||||
((string_position - 1) - starting_position >= limit)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -72,7 +72,8 @@ impl FloatAnalysis {
|
|||
}
|
||||
}
|
||||
}
|
||||
if ret.decimal_pos.is_some() && pos_before_first_nonzero_after_decimal.is_none()
|
||||
if ret.decimal_pos.is_some()
|
||||
&& pos_before_first_nonzero_after_decimal.is_none()
|
||||
&& e != '0'
|
||||
{
|
||||
pos_before_first_nonzero_after_decimal = Some(i - 1);
|
||||
|
@ -180,10 +181,7 @@ fn round_terminal_digit(
|
|||
if position < after_dec.len() {
|
||||
let digit_at_pos: char;
|
||||
{
|
||||
digit_at_pos = (&after_dec[position..=position])
|
||||
.chars()
|
||||
.next()
|
||||
.expect("");
|
||||
digit_at_pos = (&after_dec[position..=position]).chars().next().expect("");
|
||||
}
|
||||
if let '5'..='9' = digit_at_pos {
|
||||
let (new_after_dec, finished_in_dec) = _round_str_from(&after_dec, position);
|
||||
|
|
|
@ -1,11 +1,12 @@
|
|||
//! formatter for unsigned and signed int subs
|
||||
//! unsigned ints: %X %x (hex u64) %o (octal u64) %u (base ten u64)
|
||||
//! signed ints: %i %d (both base ten i64)
|
||||
use std::u64;
|
||||
use std::i64;
|
||||
use super::super::format_field::FormatField;
|
||||
use super::super::formatter::{get_it_at, warn_incomplete_conv, Base, FormatPrimitive, Formatter,
|
||||
InPrefix};
|
||||
use super::super::formatter::{
|
||||
get_it_at, warn_incomplete_conv, Base, FormatPrimitive, Formatter, InPrefix,
|
||||
};
|
||||
use std::i64;
|
||||
use std::u64;
|
||||
|
||||
pub struct Intf {
|
||||
a: u32,
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
pub mod intf;
|
||||
pub mod floatf;
|
||||
mod base_conv;
|
||||
pub mod cninetyninehexfloatf;
|
||||
pub mod scif;
|
||||
pub mod decf;
|
||||
mod float_common;
|
||||
mod base_conv;
|
||||
pub mod floatf;
|
||||
pub mod intf;
|
||||
pub mod scif;
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
//! handles creating printed output for numeric substitutions
|
||||
|
||||
use std::env;
|
||||
use std::vec::Vec;
|
||||
use cli;
|
||||
use super::format_field::{FieldType, FormatField};
|
||||
use super::formatter::{Base, FormatPrimitive, Formatter, InPrefix};
|
||||
use super::formatters::intf::Intf;
|
||||
use super::formatters::floatf::Floatf;
|
||||
use super::formatters::cninetyninehexfloatf::CninetyNineHexFloatf;
|
||||
use super::formatters::scif::Scif;
|
||||
use super::formatters::decf::Decf;
|
||||
use super::formatters::floatf::Floatf;
|
||||
use super::formatters::intf::Intf;
|
||||
use super::formatters::scif::Scif;
|
||||
use cli;
|
||||
use std::env;
|
||||
use std::vec::Vec;
|
||||
|
||||
pub fn warn_expected_numeric(pf_arg: &str) {
|
||||
// important: keep println here not print
|
||||
|
@ -21,13 +21,15 @@ pub fn warn_expected_numeric(pf_arg: &str) {
|
|||
fn warn_char_constant_ign(remaining_bytes: Vec<u8>) {
|
||||
match env::var("POSIXLY_CORRECT") {
|
||||
Ok(_) => {}
|
||||
Err(e) => if let env::VarError::NotPresent = e {
|
||||
cli::err_msg(&format!(
|
||||
"warning: {:?}: character(s) following character \
|
||||
constant have been ignored",
|
||||
&*remaining_bytes
|
||||
));
|
||||
},
|
||||
Err(e) => {
|
||||
if let env::VarError::NotPresent = e {
|
||||
cli::err_msg(&format!(
|
||||
"warning: {:?}: character(s) following character \
|
||||
constant have been ignored",
|
||||
&*remaining_bytes
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -63,9 +65,7 @@ fn get_provided(str_in_opt: Option<&String>) -> Option<u8> {
|
|||
})
|
||||
}
|
||||
// first byte is not quote
|
||||
_ => {
|
||||
None
|
||||
} // no first byte
|
||||
_ => None, // no first byte
|
||||
}
|
||||
} else {
|
||||
Some(0 as u8)
|
||||
|
|
|
@ -3,16 +3,16 @@
|
|||
//! it is created by Sub's implementation of the Tokenizer trait
|
||||
//! Subs which have numeric field chars make use of the num_format
|
||||
//! submodule
|
||||
use std::slice::Iter;
|
||||
use std::iter::Peekable;
|
||||
use std::str::Chars;
|
||||
use std::process::exit;
|
||||
use cli;
|
||||
use itertools::{put_back_n, PutBackN};
|
||||
use super::token;
|
||||
use super::unescaped_text::UnescapedText;
|
||||
use super::num_format::format_field::{FieldType, FormatField};
|
||||
use super::num_format::num_format;
|
||||
use super::token;
|
||||
use super::unescaped_text::UnescapedText;
|
||||
use cli;
|
||||
use itertools::{put_back_n, PutBackN};
|
||||
use std::iter::Peekable;
|
||||
use std::process::exit;
|
||||
use std::slice::Iter;
|
||||
use std::str::Chars;
|
||||
// use std::collections::HashSet;
|
||||
|
||||
fn err_conv(sofar: &str) {
|
||||
|
@ -155,22 +155,10 @@ impl SubParser {
|
|||
// though, as we want to mimic the original behavior of printing
|
||||
// the field as interpreted up until the error in the field.
|
||||
|
||||
let mut legal_fields = vec![// 'a', 'A', //c99 hex float implementation not yet complete
|
||||
'b',
|
||||
'c',
|
||||
'd',
|
||||
'e',
|
||||
'E',
|
||||
'f',
|
||||
'F',
|
||||
'g',
|
||||
'G',
|
||||
'i',
|
||||
'o',
|
||||
's',
|
||||
'u',
|
||||
'x',
|
||||
'X'];
|
||||
let mut legal_fields = vec![
|
||||
// 'a', 'A', //c99 hex float implementation not yet complete
|
||||
'b', 'c', 'd', 'e', 'E', 'f', 'F', 'g', 'G', 'i', 'o', 's', 'u', 'x', 'X',
|
||||
];
|
||||
let mut specifiers = vec!['h', 'j', 'l', 'L', 't', 'z'];
|
||||
legal_fields.sort();
|
||||
specifiers.sort();
|
||||
|
@ -289,8 +277,12 @@ impl SubParser {
|
|||
}
|
||||
}
|
||||
} else {
|
||||
if let Some(x) = n_ch { it.put_back(x) };
|
||||
if let Some(x) = preface { it.put_back(x) };
|
||||
if let Some(x) = n_ch {
|
||||
it.put_back(x)
|
||||
};
|
||||
if let Some(x) = preface {
|
||||
it.put_back(x)
|
||||
};
|
||||
false
|
||||
}
|
||||
}
|
||||
|
@ -302,7 +294,8 @@ impl SubParser {
|
|||
|| (field_char == 'c'
|
||||
&& (self.min_width_tmp == Some(String::from("0")) || self.past_decimal))
|
||||
|| (field_char == 'b'
|
||||
&& (self.min_width_tmp.is_some() || self.past_decimal
|
||||
&& (self.min_width_tmp.is_some()
|
||||
|| self.past_decimal
|
||||
|| self.second_field_tmp.is_some()))
|
||||
{
|
||||
err_conv(&self.text_so_far);
|
||||
|
@ -393,8 +386,7 @@ impl token::Token for Sub {
|
|||
"{}",
|
||||
match field.min_width {
|
||||
Some(min_width) => {
|
||||
let diff: isize =
|
||||
min_width.abs() as isize - pre_min_width.len() as isize;
|
||||
let diff: isize = min_width.abs() as isize - pre_min_width.len() as isize;
|
||||
if diff > 0 {
|
||||
let mut final_str = String::new();
|
||||
// definitely more efficient ways
|
||||
|
|
|
@ -63,7 +63,9 @@ impl UnescapedText {
|
|||
let leading_zeros = if eight_word {
|
||||
preface = 'U';
|
||||
8
|
||||
} else { 4 };
|
||||
} else {
|
||||
4
|
||||
};
|
||||
let err_msg = format!(
|
||||
"invalid universal character name {0}{1:02$x}",
|
||||
preface, val, leading_zeros
|
||||
|
|
|
@ -15,8 +15,8 @@ extern crate getopts;
|
|||
extern crate uucore;
|
||||
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
static NAME: &str = "pwd";
|
||||
static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
@ -30,7 +30,8 @@ pub fn absolute_path(path: &Path) -> io::Result<PathBuf> {
|
|||
.as_path()
|
||||
.to_string_lossy()
|
||||
.trim_start_matches(r"\\?\"),
|
||||
).to_path_buf();
|
||||
)
|
||||
.to_path_buf();
|
||||
|
||||
Ok(path_buf)
|
||||
}
|
||||
|
|
|
@ -76,7 +76,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
|||
CanonicalizeMode::Existing
|
||||
} else if matches.opt_present("canonicalize-missing") {
|
||||
CanonicalizeMode::Missing
|
||||
} else { CanonicalizeMode::None };
|
||||
} else {
|
||||
CanonicalizeMode::None
|
||||
};
|
||||
|
||||
let files = matches.free;
|
||||
if files.is_empty() {
|
||||
|
|
24
src/rm/rm.rs
24
src/rm/rm.rs
|
@ -16,12 +16,12 @@ extern crate walkdir;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use remove_dir_all::remove_dir_all;
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
use std::io::{stderr, stdin, BufRead, Write};
|
||||
use std::ops::BitOr;
|
||||
use std::path::Path;
|
||||
use remove_dir_all::remove_dir_all;
|
||||
use walkdir::{DirEntry, WalkDir};
|
||||
|
||||
#[derive(Eq, PartialEq, Clone, Copy)]
|
||||
|
@ -181,7 +181,8 @@ fn remove(files: Vec<String>, options: Options) -> bool {
|
|||
false
|
||||
}
|
||||
}
|
||||
}.bitor(had_err);
|
||||
}
|
||||
.bitor(had_err);
|
||||
}
|
||||
|
||||
had_err
|
||||
|
@ -247,9 +248,11 @@ fn remove_dir(path: &Path, options: &Options) -> bool {
|
|||
};
|
||||
if response {
|
||||
match fs::remove_dir(path) {
|
||||
Ok(_) => if options.verbose {
|
||||
println!("removed '{}'", path.display());
|
||||
},
|
||||
Ok(_) => {
|
||||
if options.verbose {
|
||||
println!("removed '{}'", path.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
show_error!("removing '{}': {}", path.display(), e);
|
||||
return true;
|
||||
|
@ -268,9 +271,11 @@ fn remove_file(path: &Path, options: &Options) -> bool {
|
|||
};
|
||||
if response {
|
||||
match fs::remove_file(path) {
|
||||
Ok(_) => if options.verbose {
|
||||
println!("removed '{}'", path.display());
|
||||
},
|
||||
Ok(_) => {
|
||||
if options.verbose {
|
||||
println!("removed '{}'", path.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
show_error!("removing '{}': {}", path.display(), e);
|
||||
return true;
|
||||
|
@ -320,5 +325,6 @@ fn is_symlink_dir(metadata: &fs::Metadata) -> bool {
|
|||
pub type DWORD = c_ulong;
|
||||
pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10;
|
||||
|
||||
metadata.file_type().is_symlink() && ((metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY) != 0)
|
||||
metadata.file_type().is_symlink()
|
||||
&& ((metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY) != 0)
|
||||
}
|
||||
|
|
|
@ -96,10 +96,7 @@ fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<Stri
|
|||
options.separator = sep;
|
||||
let next = chiter.next();
|
||||
if let Some(n) = next {
|
||||
show_error!(
|
||||
"unexpected character ('{}')",
|
||||
n
|
||||
);
|
||||
show_error!("unexpected character ('{}')", n);
|
||||
return Err(1);
|
||||
}
|
||||
}
|
||||
|
@ -113,10 +110,7 @@ fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<Stri
|
|||
options.terminator = Some(term);
|
||||
let next = chiter.next();
|
||||
if let Some(n) = next {
|
||||
show_error!(
|
||||
"unexpected character ('{}')",
|
||||
n
|
||||
);
|
||||
show_error!("unexpected character ('{}')", n);
|
||||
return Err(1);
|
||||
}
|
||||
}
|
||||
|
@ -137,7 +131,7 @@ fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<Stri
|
|||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
Ok(seq_args)
|
||||
}
|
||||
|
||||
|
|
|
@ -18,8 +18,8 @@ use std::cell::{Cell, RefCell};
|
|||
use std::fs;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io;
|
||||
use std::io::SeekFrom;
|
||||
use std::io::prelude::*;
|
||||
use std::io::SeekFrom;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[macro_use]
|
||||
|
@ -473,7 +473,8 @@ fn wipe_file(
|
|||
}
|
||||
}
|
||||
// size is an optional argument for exactly how many bytes we want to shred
|
||||
do_pass(&mut file, path, *pass_type, size, exact).expect("File write pass failed"); // Ignore failed writes; just keep trying
|
||||
do_pass(&mut file, path, *pass_type, size, exact).expect("File write pass failed");
|
||||
// Ignore failed writes; just keep trying
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -130,7 +130,10 @@ With no FILE, or when FILE is -, read standard input.",
|
|||
}
|
||||
Mode::InputRange((b, e)) => {
|
||||
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);
|
||||
}
|
||||
Mode::Default => {
|
||||
|
|
|
@ -63,12 +63,14 @@ specified by the sum of their values.",
|
|||
}
|
||||
|
||||
fn sleep(args: Vec<String>) {
|
||||
let sleep_dur = args.iter().fold(Duration::new(0, 0), |result, arg| {
|
||||
match uucore::parse_time::from_str(&arg[..]) {
|
||||
Ok(m) => m + result,
|
||||
Err(f) => crash!(1, "{}", f),
|
||||
}
|
||||
});
|
||||
let sleep_dur =
|
||||
args.iter().fold(
|
||||
Duration::new(0, 0),
|
||||
|result, arg| match uucore::parse_time::from_str(&arg[..]) {
|
||||
Ok(m) => m + result,
|
||||
Err(f) => crash!(1, "{}", f),
|
||||
},
|
||||
);
|
||||
|
||||
thread::sleep(sleep_dur);
|
||||
}
|
||||
|
|
|
@ -16,15 +16,15 @@ extern crate itertools;
|
|||
#[macro_use]
|
||||
extern crate uucore;
|
||||
|
||||
use itertools::Itertools;
|
||||
use semver::Version;
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BinaryHeap;
|
||||
use std::fs::File;
|
||||
use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Lines, Read, Write};
|
||||
use std::mem::replace;
|
||||
use std::path::Path;
|
||||
use uucore::fs::is_stdin_interactive;
|
||||
use semver::Version;
|
||||
use itertools::Itertools; // for Iterator::dedup()
|
||||
use uucore::fs::is_stdin_interactive; // for Iterator::dedup()
|
||||
|
||||
static NAME: &str = "sort";
|
||||
static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
@ -380,13 +380,11 @@ fn permissive_f64_parse(a: &str) -> f64 {
|
|||
// GNU sort treats "NaN" as non-number in numeric, so it needs special care.
|
||||
match a.split_whitespace().next() {
|
||||
None => std::f64::NEG_INFINITY,
|
||||
Some(sa) => {
|
||||
match sa.parse::<f64>() {
|
||||
Ok(a) if a.is_nan() => std::f64::NEG_INFINITY,
|
||||
Ok(a) => a,
|
||||
Err(_) => std::f64::NEG_INFINITY,
|
||||
}
|
||||
}
|
||||
Some(sa) => match sa.parse::<f64>() {
|
||||
Ok(a) if a.is_nan() => std::f64::NEG_INFINITY,
|
||||
Ok(a) => a,
|
||||
Err(_) => std::f64::NEG_INFINITY,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -467,7 +465,8 @@ enum Month {
|
|||
|
||||
/// Parse the beginning string into a Month, returning Month::Unknown on errors.
|
||||
fn month_parse(line: &str) -> Month {
|
||||
match line.split_whitespace()
|
||||
match line
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap()
|
||||
.to_uppercase()
|
||||
|
|
|
@ -319,7 +319,8 @@ fn split(settings: &Settings) -> i32 {
|
|||
num_prefix(fileno, settings.suffix_length)
|
||||
} else {
|
||||
str_prefix(fileno, settings.suffix_length)
|
||||
}.as_ref(),
|
||||
}
|
||||
.as_ref(),
|
||||
);
|
||||
|
||||
if fileno != 0 {
|
||||
|
|
|
@ -10,9 +10,11 @@ pub use super::uucore::libc;
|
|||
extern crate time;
|
||||
|
||||
use self::time::Timespec;
|
||||
pub use libc::{c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT,
|
||||
S_IFREG, S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP,
|
||||
S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR};
|
||||
pub use libc::{
|
||||
c_int, mode_t, strerror, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG,
|
||||
S_IFSOCK, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, S_IWOTH, S_IWUSR,
|
||||
S_IXGRP, S_IXOTH, S_IXUSR,
|
||||
};
|
||||
|
||||
pub trait BirthTime {
|
||||
fn pretty_birth(&self) -> String;
|
||||
|
@ -40,9 +42,9 @@ impl BirthTime for Metadata {
|
|||
|
||||
#[macro_export]
|
||||
macro_rules! has {
|
||||
($mode:expr, $perm:expr) => (
|
||||
($mode:expr, $perm:expr) => {
|
||||
$mode & $perm != 0
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub fn pretty_time(sec: i64, nsec: i64) -> String {
|
||||
|
@ -137,22 +139,44 @@ pub fn pretty_access(mode: mode_t) -> String {
|
|||
result
|
||||
}
|
||||
|
||||
use std::mem;
|
||||
use std::path::Path;
|
||||
use std::borrow::Cow;
|
||||
use std::ffi::CString;
|
||||
use std::convert::{AsRef, From};
|
||||
use std::error::Error;
|
||||
use std::ffi::CString;
|
||||
use std::io::Error as IOError;
|
||||
use std::mem;
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android", target_os = "freebsd"))]
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "macos",
|
||||
target_os = "android",
|
||||
target_os = "freebsd"
|
||||
))]
|
||||
use libc::statfs as Sstatfs;
|
||||
#[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "openbsd", target_os = "bitrig", target_os = "dragonfly"))]
|
||||
#[cfg(any(
|
||||
target_os = "openbsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "bitrig",
|
||||
target_os = "dragonfly"
|
||||
))]
|
||||
use libc::statvfs as Sstatfs;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android", target_os = "freebsd"))]
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "macos",
|
||||
target_os = "android",
|
||||
target_os = "freebsd"
|
||||
))]
|
||||
use libc::statfs as statfs_fn;
|
||||
#[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "openbsd", target_os = "bitrig", target_os = "dragonfly"))]
|
||||
#[cfg(any(
|
||||
target_os = "openbsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "bitrig",
|
||||
target_os = "dragonfly"
|
||||
))]
|
||||
use libc::statvfs as statfs_fn;
|
||||
|
||||
pub trait FsMeta {
|
||||
|
@ -219,7 +243,8 @@ impl FsMeta for Sstatfs {
|
|||
// struct statvfs, containing an unsigned long f_fsid
|
||||
#[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "linux"))]
|
||||
fn fsid(&self) -> u64 {
|
||||
let f_fsid: &[u32; 2] = unsafe { &*(&self.f_fsid as *const uucore::libc::fsid_t as *const [u32; 2]) };
|
||||
let f_fsid: &[u32; 2] =
|
||||
unsafe { &*(&self.f_fsid as *const uucore::libc::fsid_t as *const [u32; 2]) };
|
||||
(u64::from(f_fsid[0])) << 32 | u64::from(f_fsid[1])
|
||||
}
|
||||
#[cfg(not(any(target_os = "macos", target_os = "freebsd", target_os = "linux")))]
|
||||
|
@ -261,10 +286,10 @@ where
|
|||
Err(CString::from_raw(strerror(errno))
|
||||
.into_string()
|
||||
.unwrap_or_else(|_| "Unknown Error".to_owned()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e.description().to_owned()),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,29 +19,31 @@ pub use fsext::*;
|
|||
extern crate uucore;
|
||||
use uucore::entries;
|
||||
|
||||
use std::{cmp, fs, iter};
|
||||
use std::borrow::Cow;
|
||||
use std::convert::AsRef;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::borrow::Cow;
|
||||
use std::os::unix::fs::{FileTypeExt, MetadataExt};
|
||||
use std::path::Path;
|
||||
use std::convert::AsRef;
|
||||
use std::{cmp, fs, iter};
|
||||
|
||||
macro_rules! check_bound {
|
||||
($str: ident, $bound:expr, $beg: expr, $end: expr) => (
|
||||
($str: ident, $bound:expr, $beg: expr, $end: expr) => {
|
||||
if $end >= $bound {
|
||||
return Err(format!("‘{}’: invalid directive", &$str[$beg..$end]));
|
||||
}
|
||||
|
||||
)
|
||||
};
|
||||
}
|
||||
macro_rules! fill_string {
|
||||
($str: ident, $c: expr, $cnt: expr) => (
|
||||
iter::repeat($c).take($cnt).map(|c| $str.push(c)).all(|_| true)
|
||||
)
|
||||
($str: ident, $c: expr, $cnt: expr) => {
|
||||
iter::repeat($c)
|
||||
.take($cnt)
|
||||
.map(|c| $str.push(c))
|
||||
.all(|_| true)
|
||||
};
|
||||
}
|
||||
macro_rules! extend_digits {
|
||||
($str: expr, $min: expr) => (
|
||||
($str: expr, $min: expr) => {
|
||||
if $min > $str.len() {
|
||||
let mut pad = String::with_capacity($min);
|
||||
fill_string!(pad, '0', $min - $str.len());
|
||||
|
@ -50,10 +52,10 @@ macro_rules! extend_digits {
|
|||
} else {
|
||||
$str.into()
|
||||
}
|
||||
)
|
||||
};
|
||||
}
|
||||
macro_rules! pad_and_print {
|
||||
($result: ident, $str: ident, $left: expr, $width: expr, $padding: expr) => (
|
||||
($result: ident, $str: ident, $left: expr, $width: expr, $padding: expr) => {
|
||||
if $str.len() < $width {
|
||||
if $left {
|
||||
$result.push_str($str.as_ref());
|
||||
|
@ -66,7 +68,7 @@ macro_rules! pad_and_print {
|
|||
$result.push_str($str.as_ref());
|
||||
}
|
||||
print!("{}", $result);
|
||||
)
|
||||
};
|
||||
}
|
||||
macro_rules! print_adjusted {
|
||||
($str: ident, $left: expr, $width: expr, $padding: expr) => {
|
||||
|
@ -82,7 +84,7 @@ macro_rules! print_adjusted {
|
|||
field_width -= $prefix.len();
|
||||
}
|
||||
pad_and_print!(result, $str, $left, field_width, $padding);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static NAME: &str = "stat";
|
||||
|
@ -481,7 +483,11 @@ impl Stater {
|
|||
let mut mount_list = reader
|
||||
.lines()
|
||||
.filter_map(std::result::Result::ok)
|
||||
.filter_map(|line| line.split_whitespace().nth(1).map(std::borrow::ToOwned::to_owned))
|
||||
.filter_map(|line| {
|
||||
line.split_whitespace()
|
||||
.nth(1)
|
||||
.map(std::borrow::ToOwned::to_owned)
|
||||
})
|
||||
.collect::<Vec<String>>();
|
||||
// Reverse sort. The longer comes first.
|
||||
mount_list.sort_by(|a, b| b.cmp(a));
|
||||
|
|
|
@ -9,7 +9,7 @@ use libc::{c_char, c_int, size_t, FILE, _IOFBF, _IOLBF, _IONBF};
|
|||
use std::env;
|
||||
use std::ptr;
|
||||
|
||||
cpp!{{
|
||||
cpp! {{
|
||||
#include <cstdio>
|
||||
|
||||
extern "C" {
|
||||
|
|
|
@ -16,12 +16,12 @@ extern crate tempdir;
|
|||
extern crate uucore;
|
||||
|
||||
use getopts::{Matches, Options};
|
||||
use tempdir::TempDir;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Write};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use tempdir::TempDir;
|
||||
|
||||
static NAME: &str = "stdbuf";
|
||||
static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
@ -51,7 +51,12 @@ enum OkMsg {
|
|||
Version,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "dragonflybsd"))]
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "dragonflybsd"
|
||||
))]
|
||||
fn preload_strings() -> (&'static str, &'static str) {
|
||||
("LD_PRELOAD", "so")
|
||||
}
|
||||
|
@ -61,7 +66,13 @@ fn preload_strings() -> (&'static str, &'static str) {
|
|||
("DYLD_LIBRARY_PATH", "dylib")
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "dragonflybsd", target_os = "macos")))]
|
||||
#[cfg(not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "dragonflybsd",
|
||||
target_os = "macos"
|
||||
)))]
|
||||
fn preload_strings() -> (&'static str, &'static str) {
|
||||
crash!(1, "Command not supported for this operating system!")
|
||||
}
|
||||
|
|
|
@ -42,27 +42,29 @@ mod platform {
|
|||
mod platform {
|
||||
extern crate kernel32;
|
||||
extern crate winapi;
|
||||
use std::mem;
|
||||
use std::fs::OpenOptions;
|
||||
use std::os::windows::prelude::*;
|
||||
use uucore::wide::{FromWide, ToWide};
|
||||
use self::winapi::shared::minwindef;
|
||||
use self::winapi::shared::winerror;
|
||||
use self::winapi::um::handleapi;
|
||||
use self::winapi::um::winbase;
|
||||
use self::winapi::um::winnt;
|
||||
use self::winapi::shared::minwindef;
|
||||
use self::winapi::um::handleapi;
|
||||
use self::winapi::shared::winerror;
|
||||
use std::fs::OpenOptions;
|
||||
use std::mem;
|
||||
use std::os::windows::prelude::*;
|
||||
use uucore::wide::{FromWide, ToWide};
|
||||
|
||||
unsafe fn flush_volume(name: &str) {
|
||||
let name_wide = name.to_wide_null();
|
||||
if kernel32::GetDriveTypeW(name_wide.as_ptr()) == winbase::DRIVE_FIXED {
|
||||
let sliced_name = &name[..name.len() - 1]; // eliminate trailing backslash
|
||||
match OpenOptions::new().write(true).open(sliced_name) {
|
||||
Ok(file) => if kernel32::FlushFileBuffers(file.as_raw_handle()) == 0 {
|
||||
crash!(
|
||||
kernel32::GetLastError() as i32,
|
||||
"failed to flush file buffer"
|
||||
);
|
||||
},
|
||||
Ok(file) => {
|
||||
if kernel32::FlushFileBuffers(file.as_raw_handle()) == 0 {
|
||||
crash!(
|
||||
kernel32::GetLastError() as i32,
|
||||
"failed to flush file buffer"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => crash!(
|
||||
e.raw_os_error().unwrap_or(1),
|
||||
"failed to create volume handle"
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
extern crate syscall;
|
||||
|
||||
use self::syscall::{Error, EPERM, ENOSYS};
|
||||
use self::syscall::{Error, ENOSYS, EPERM};
|
||||
|
||||
pub type Pid = usize;
|
||||
|
||||
|
|
|
@ -12,7 +12,7 @@ extern crate winapi;
|
|||
|
||||
use self::kernel32::{CloseHandle, OpenProcess, WaitForSingleObject};
|
||||
use self::winapi::shared::minwindef::DWORD;
|
||||
use self::winapi::um::winbase::{WAIT_OBJECT_0, WAIT_FAILED};
|
||||
use self::winapi::um::winbase::{WAIT_FAILED, WAIT_OBJECT_0};
|
||||
use self::winapi::um::winnt::{HANDLE, SYNCHRONIZE};
|
||||
|
||||
pub type Pid = DWORD;
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue