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

refactor/polish ~ cargo fmt

This commit is contained in:
Roy Ivy III 2020-05-23 12:47:37 -05:00
parent 099b0a2074
commit 6a8a677e8b
12 changed files with 358 additions and 293 deletions

View file

@ -84,13 +84,15 @@ impl<'a> CoreOptions<'a> {
eprintln!("{}", f);
::std::process::exit(1);
}
}.unwrap();
}
.unwrap();
if matches.opt_present("help") {
let usage_str = if self.help_text.display_usage {
format!(
"\n {}\n\n Reference\n",
self.options.usage(self.help_text.summary)
).replace("Options:", " Options:")
)
.replace("Options:", " Options:")
} else {
String::new()
};
@ -118,24 +120,24 @@ impl<'a> CoreOptions<'a> {
#[macro_export]
macro_rules! new_coreopts {
($syntax: expr, $summary: expr, $long_help: expr) => (
($syntax: expr, $summary: expr, $long_help: expr) => {
uucore::coreopts::CoreOptions::new(uucore::coreopts::HelpText {
name: executable!(),
version: env!("CARGO_PKG_VERSION"),
syntax: $syntax,
summary: $summary,
long_help: $long_help,
display_usage: true
display_usage: true,
})
);
($syntax: expr, $summary: expr, $long_help: expr, $display_usage: expr) => (
};
($syntax: expr, $summary: expr, $long_help: expr, $display_usage: expr) => {
uucore::coreopts::CoreOptions::new(uucore::coreopts::HelpText {
name: executable!(),
version: env!("CARGO_PKG_VERSION"),
syntax: $syntax,
summary: $summary,
long_help: $long_help,
display_usage: $display_usage
display_usage: $display_usage,
})
);
};
}

View file

@ -37,12 +37,12 @@ use libc::time_t;
use libc::{c_char, c_int, gid_t, uid_t};
use libc::{getgrgid, getgrnam, getgroups, getpwnam, getpwuid, group, passwd};
use std::ptr;
use std::io::ErrorKind;
use std::io::Error as IOError;
use std::io::Result as IOResult;
use std::ffi::{CStr, CString};
use std::borrow::Cow;
use std::ffi::{CStr, CString};
use std::io::Error as IOError;
use std::io::ErrorKind;
use std::io::Result as IOResult;
use std::ptr;
extern "C" {
fn getgrouplist(
@ -75,9 +75,9 @@ pub struct Passwd {
}
macro_rules! cstr2cow {
($v:expr) => (
($v:expr) => {
unsafe { CStr::from_ptr($v).to_string_lossy() }
)
};
}
impl Passwd {
@ -191,17 +191,20 @@ pub trait Locate<K> {
}
macro_rules! f {
($fnam:ident, $fid:ident, $t:ident, $st:ident) => (
($fnam:ident, $fid:ident, $t:ident, $st:ident) => {
impl Locate<$t> for $st {
fn locate(k: $t) -> IOResult<Self> {
unsafe {
let data = $fid(k);
if !data.is_null() {
Ok($st {
inner: ptr::read(data as *const _)
inner: ptr::read(data as *const _),
})
} else {
Err(IOError::new(ErrorKind::NotFound, format!("No such id: {}", k)))
Err(IOError::new(
ErrorKind::NotFound,
format!("No such id: {}", k),
))
}
}
}
@ -213,26 +216,32 @@ macro_rules! f {
let data = unsafe { $fid(id) };
if !data.is_null() {
Ok($st {
inner: unsafe {ptr::read(data as *const _)}
inner: unsafe { ptr::read(data as *const _) },
})
} else {
Err(IOError::new(ErrorKind::NotFound, format!("No such id: {}", id)))
Err(IOError::new(
ErrorKind::NotFound,
format!("No such id: {}", id),
))
}
} else {
unsafe {
let data = $fnam(CString::new(k).unwrap().as_ptr());
if !data.is_null() {
Ok($st {
inner: ptr::read(data as *const _)
inner: ptr::read(data as *const _),
})
} else {
Err(IOError::new(ErrorKind::NotFound, format!("Not found: {}", k)))
Err(IOError::new(
ErrorKind::NotFound,
format!("Not found: {}", k),
))
}
}
}
}
}
)
};
}
f!(getpwnam, getpwuid, uid_t, Passwd);

View file

@ -14,24 +14,26 @@ extern crate termion;
#[cfg(unix)]
use super::libc;
#[cfg(unix)]
use super::libc::{mode_t, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, S_IWOTH,
S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR};
use super::libc::{
mode_t, S_IRGRP, S_IROTH, S_IRUSR, S_ISGID, S_ISUID, S_ISVTX, S_IWGRP, S_IWOTH, S_IWUSR,
S_IXGRP, S_IXOTH, S_IXUSR,
};
use std::borrow::Cow;
use std::env;
use std::fs;
#[cfg(any(unix, target_os = "redox"))]
use std::os::unix::fs::MetadataExt;
#[cfg(target_os = "redox")]
use std::io;
use std::io::{Error, ErrorKind};
use std::io::Result as IOResult;
use std::io::{Error, ErrorKind};
#[cfg(any(unix, target_os = "redox"))]
use std::os::unix::fs::MetadataExt;
use std::path::{Component, Path, PathBuf};
use std::borrow::Cow;
#[cfg(unix)]
macro_rules! has {
($mode:expr, $perm:expr) => (
($mode:expr, $perm:expr) => {
$mode & ($perm as u32) != 0
)
};
}
pub fn resolve_relative_path(path: &Path) -> Cow<Path> {
@ -103,7 +105,9 @@ pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) ->
let original = if original.is_absolute() {
original.to_path_buf()
} else {
dunce::canonicalize(env::current_dir().unwrap()).unwrap().join(original)
dunce::canonicalize(env::current_dir().unwrap())
.unwrap()
.join(original)
};
let mut result = PathBuf::new();

View file

@ -1,15 +1,15 @@
extern crate wild;
pub fn args() -> impl Iterator<Item=String> {
pub fn args() -> impl Iterator<Item = String> {
wild::args()
}
#[cfg(feature = "failure")]
extern crate failure;
#[cfg(feature = "libc")]
pub extern crate libc;
#[cfg(feature = "winapi")]
pub extern crate winapi;
#[cfg(feature = "failure")]
extern crate failure;
#[cfg(feature = "failure_derive")]
#[macro_use]
extern crate failure_derive;
@ -29,23 +29,28 @@ pub mod coreopts;
pub mod panic;
#[cfg(feature = "fs")]
pub mod fs;
#[cfg(feature = "encoding")]
pub mod encoding;
#[cfg(feature = "fs")]
pub mod fs;
#[cfg(feature = "parse_time")]
pub mod parse_time;
#[cfg(all(not(windows), feature = "mode"))]
pub mod mode;
#[cfg(all(unix, not(target_os = "fuchsia"), not(target_env="musl"), feature = "utmpx"))]
pub mod utmpx;
#[cfg(all(unix, feature = "entries"))]
pub mod entries;
#[cfg(all(not(windows), feature = "mode"))]
pub mod mode;
#[cfg(all(unix, feature = "process"))]
pub mod process;
#[cfg(all(unix, not(target_os = "fuchsia"), feature = "signals"))]
pub mod signals;
#[cfg(all(
unix,
not(target_os = "fuchsia"),
not(target_env = "musl"),
feature = "utmpx"
))]
pub mod utmpx;
#[cfg(feature = "zero-copy")]
pub mod zero_copy;

View file

@ -148,80 +148,108 @@ macro_rules! snippet_list_join_or {
//-- message templates : invalid input
#[macro_export]
macro_rules! msg_invalid_input { ($reason: expr) => (
format!("invalid input: {}", $reason) ); }
macro_rules! msg_invalid_input {
($reason: expr) => {
format!("invalid input: {}", $reason)
};
}
#[macro_export]
macro_rules! snippet_no_file_at_path { ($path:expr) => (
format!("nonexistent path {}", $path) ); }
macro_rules! snippet_no_file_at_path {
($path:expr) => {
format!("nonexistent path {}", $path)
};
}
// -- message templates : invalid input : flag
#[macro_export]
macro_rules! msg_invalid_opt_use {
($about:expr, $flag:expr) => (
($about:expr, $flag:expr) => {
msg_invalid_input!(format!("The '{}' option {}", $flag, $about))
);
};
($about:expr, $longflag:expr, $shortflag:expr) => {
msg_invalid_input!(format!("The '{}' ('{}') option {}", $longflag, $shortflag, $about))
msg_invalid_input!(format!(
"The '{}' ('{}') option {}",
$longflag, $shortflag, $about
))
};
}
#[macro_export]
macro_rules! msg_opt_only_usable_if {
($clause:expr, $flag:expr) => (
($clause:expr, $flag:expr) => {
msg_invalid_opt_use!(format!("only usable if {}", $clause), $flag)
);
($clause:expr, $longflag:expr, $shortflag:expr) => (
};
($clause:expr, $longflag:expr, $shortflag:expr) => {
msg_invalid_opt_use!(format!("only usable if {}", $clause), $longflag, $shortflag)
);
};
}
#[macro_export]
macro_rules! msg_opt_invalid_should_be {
($expects:expr, $received:expr, $flag:expr) => (
msg_invalid_opt_use!(format!("expects {}, but was provided {}", $expects, $received), $flag)
);
($expects:expr, $received:expr, $longflag:expr, $shortflag:expr) => (
msg_invalid_opt_use!(format!("expects {}, but was provided {}", $expects, $received), $longflag, $shortflag)
);
($expects:expr, $received:expr, $flag:expr) => {
msg_invalid_opt_use!(
format!("expects {}, but was provided {}", $expects, $received),
$flag
)
};
($expects:expr, $received:expr, $longflag:expr, $shortflag:expr) => {
msg_invalid_opt_use!(
format!("expects {}, but was provided {}", $expects, $received),
$longflag,
$shortflag
)
};
}
// -- message templates : invalid input : args
#[macro_export]
macro_rules! msg_arg_invalid_value { ($expects:expr, $received:expr) => (
msg_invalid_input!(format!("expects its argument to be {}, but was provided {}", $expects, $received)) ); }
#[macro_export]
macro_rules! msg_args_invalid_value {
($expects:expr, $received:expr) => (
msg_invalid_input!(format!("expects its arguments to be {}, but was provided {}", $expects, $received))
);
($msg:expr) => (
msg_invalid_input!($msg)
);
macro_rules! msg_arg_invalid_value {
($expects:expr, $received:expr) => {
msg_invalid_input!(format!(
"expects its argument to be {}, but was provided {}",
$expects, $received
))
};
}
#[macro_export]
macro_rules! msg_args_nonexistent_file { ($received:expr) => (
msg_args_invalid_value!("paths to files", snippet_no_file_at_path!($received)));}
macro_rules! msg_args_invalid_value {
($expects:expr, $received:expr) => {
msg_invalid_input!(format!(
"expects its arguments to be {}, but was provided {}",
$expects, $received
))
};
($msg:expr) => {
msg_invalid_input!($msg)
};
}
#[macro_export]
macro_rules! msg_args_nonexistent_file {
($received:expr) => {
msg_args_invalid_value!("paths to files", snippet_no_file_at_path!($received))
};
}
#[macro_export]
macro_rules! msg_wrong_number_of_arguments {
() => (
() => {
msg_args_invalid_value!("wrong number of arguments")
);
($min:expr, $max:expr) => (
};
($min:expr, $max:expr) => {
msg_args_invalid_value!(format!("expects {}-{} arguments", $min, $max))
);
($exact:expr) => (
};
($exact:expr) => {
if $exact == 1 {
msg_args_invalid_value!("expects 1 argument")
} else {
msg_args_invalid_value!(format!("expects {} arguments", $exact))
}
);
};
}
// -- message templates : invalid input : input combinations

View file

@ -35,19 +35,19 @@ use super::libc;
pub extern crate time;
use self::time::{Timespec, Tm};
use std::io::Result as IOResult;
use std::io::Error as IOError;
use std::ptr;
use std::ffi::CString;
use std::io::Error as IOError;
use std::io::Result as IOResult;
use std::ptr;
pub use self::ut::*;
use libc::utmpx;
// pub use libc::getutxid;
// pub use libc::getutxline;
// pub use libc::pututxline;
pub use libc::endutxent;
pub use libc::getutxent;
pub use libc::setutxent;
pub use libc::endutxent;
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub use libc::utmpxname;
#[cfg(target_os = "freebsd")]
@ -57,53 +57,56 @@ pub unsafe extern "C" fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
// In case the c_char array doesn't end with NULL
macro_rules! chars2string {
($arr:expr) => (
$arr.iter().take_while(|i| **i > 0).map(|&i| i as u8 as char).collect::<String>()
)
($arr:expr) => {
$arr.iter()
.take_while(|i| **i > 0)
.map(|&i| i as u8 as char)
.collect::<String>()
};
}
#[cfg(target_os = "linux")]
mod ut {
pub static DEFAULT_FILE: &str = "/var/run/utmp";
pub use libc::__UT_HOSTSIZE as UT_HOSTSIZE;
pub use libc::__UT_LINESIZE as UT_LINESIZE;
pub use libc::__UT_NAMESIZE as UT_NAMESIZE;
pub use libc::__UT_HOSTSIZE as UT_HOSTSIZE;
pub const UT_IDSIZE: usize = 4;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::ACCOUNTING;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::DEAD_PROCESS;
pub use libc::EMPTY;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::RUN_LVL;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
}
#[cfg(target_os = "macos")]
mod ut {
pub static DEFAULT_FILE: &str = "/var/run/utmpx";
pub use libc::_UTX_LINESIZE as UT_LINESIZE;
pub use libc::_UTX_USERSIZE as UT_NAMESIZE;
pub use libc::_UTX_HOSTSIZE as UT_HOSTSIZE;
pub use libc::_UTX_IDSIZE as UT_IDSIZE;
pub use libc::_UTX_LINESIZE as UT_LINESIZE;
pub use libc::_UTX_USERSIZE as UT_NAMESIZE;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::ACCOUNTING;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::DEAD_PROCESS;
pub use libc::EMPTY;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
pub use libc::SIGNATURE;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::RUN_LVL;
pub use libc::SHUTDOWN_TIME;
pub use libc::SIGNATURE;
pub use libc::USER_PROCESS;
}
#[cfg(target_os = "freebsd")]
@ -117,15 +120,15 @@ mod ut {
pub const UT_IDSIZE: usize = 8;
pub const UT_HOSTSIZE: usize = 128;
pub use libc::EMPTY;
pub use libc::BOOT_TIME;
pub use libc::OLD_TIME;
pub use libc::NEW_TIME;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::EMPTY;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::SHUTDOWN_TIME;
pub use libc::USER_PROCESS;
}
pub struct Utmpx {

View file

@ -8,7 +8,7 @@ pub trait AsRawObject {
fn as_raw_object(&self) -> RawObject;
}
pub trait FromRawObject : Sized {
pub trait FromRawObject: Sized {
unsafe fn from_raw_object(obj: RawObject) -> Option<Self>;
}
@ -66,7 +66,9 @@ impl<'a, A: Write + AsRawObject + Sized, B: Write + Sized> Write for TransformCo
}
}
impl<'a, A: Write + AsRawObject + Sized, B: Write + Sized> AsRawObject for TransformContainer<'a, A, B> {
impl<'a, A: Write + AsRawObject + Sized, B: Write + Sized> AsRawObject
for TransformContainer<'a, A, B>
{
fn as_raw_object(&self) -> RawObject {
panic!("Test should never be used")
}
@ -76,12 +78,10 @@ impl<T: Write + AsRawObject + Sized> ZeroCopyWriter<T> {
pub fn new(writer: T) -> Self {
let raw_obj = writer.as_raw_object();
match unsafe { PlatformZeroCopyWriter::new(raw_obj) } {
Ok(inner) => {
ZeroCopyWriter {
Ok(inner) => ZeroCopyWriter {
raw_obj_owner: Some(writer),
inner: InnerZeroCopyWriter::Platform(inner),
}
}
},
_ => {
// creating the splice writer failed for whatever reason, so just make a default
// writer
@ -93,19 +93,23 @@ impl<T: Write + AsRawObject + Sized> ZeroCopyWriter<T> {
}
}
pub fn with_default<'a: 'b, 'b, F, W>(writer: &'a mut T, func: F) -> ZeroCopyWriter<impl Write + AsRawObject + Sized + 'b>
pub fn with_default<'a: 'b, 'b, F, W>(
writer: &'a mut T,
func: F,
) -> ZeroCopyWriter<impl Write + AsRawObject + Sized + 'b>
where
F: Fn(&'a mut T) -> W,
W: Write + Sized + 'b,
{
let raw_obj = writer.as_raw_object();
match unsafe { PlatformZeroCopyWriter::new(raw_obj) } {
Ok(inner) => {
ZeroCopyWriter {
raw_obj_owner: Some(TransformContainer { original: Some(writer), transformed: None, }),
Ok(inner) => ZeroCopyWriter {
raw_obj_owner: Some(TransformContainer {
original: Some(writer),
transformed: None,
}),
inner: InnerZeroCopyWriter::Platform(inner),
}
}
},
_ => {
// XXX: should func actually consume writer and leave it up to the user to save the value?
// maybe provide a default stdin method then? in some cases it would make more sense for the
@ -113,7 +117,10 @@ impl<T: Write + AsRawObject + Sized> ZeroCopyWriter<T> {
let real_writer = func(writer);
ZeroCopyWriter {
raw_obj_owner: None,
inner: InnerZeroCopyWriter::Standard(TransformContainer { original: None, transformed: Some(real_writer) }),
inner: InnerZeroCopyWriter::Standard(TransformContainer {
original: None,
transformed: Some(real_writer),
}),
}
}
}

View file

@ -4,10 +4,10 @@ use std::os::unix::io::RawFd;
use libc::{O_APPEND, S_IFIFO, S_IFREG};
use nix::errno::Errno;
use nix::fcntl::{fcntl, splice, vmsplice, FcntlArg, SpliceFFlags};
use nix::sys::uio::IoVec;
use nix::sys::stat::{fstat, FileStat};
use nix::sys::uio::IoVec;
use nix::unistd::pipe;
use platform_info::{Uname, PlatformInfo};
use platform_info::{PlatformInfo, Uname};
use crate::zero_copy::{FromRawObject, RawObject};
@ -31,7 +31,7 @@ impl PlatformZeroCopyWriter {
// apparently WSL hasn't implemented vmsplice(), causing writes to fail
// thus, we will just say zero-copy doesn't work there rather than working
// around it
return Err(nix::Error::from(Errno::EOPNOTSUPP))
return Err(nix::Error::from(Errno::EOPNOTSUPP));
}
let stat_info: FileStat = fstat(raw_obj)?;
@ -84,22 +84,29 @@ impl Write for PlatformZeroCopyWriter {
}
}
fn write_regular(writer: &mut PlatformZeroCopyWriter, iovec: &[IoVec<&[u8]>], len: usize) -> io::Result<usize> {
fn write_regular(
writer: &mut PlatformZeroCopyWriter,
iovec: &[IoVec<&[u8]>],
len: usize,
) -> io::Result<usize> {
vmsplice(writer.write_pipe, iovec, SpliceFFlags::empty())
.and_then(|_|
.and_then(|_| {
splice(
writer.read_pipe,
None,
writer.raw_obj,
None,
len,
SpliceFFlags::empty()
)
SpliceFFlags::empty(),
)
})
.map_err(|_| io::Error::last_os_error())
}
fn write_fifo(writer: &mut PlatformZeroCopyWriter, iovec: &[IoVec<&[u8]>], _len: usize) -> io::Result<usize> {
vmsplice(writer.raw_obj, iovec, SpliceFFlags::empty())
.map_err(|_| io::Error::last_os_error())
fn write_fifo(
writer: &mut PlatformZeroCopyWriter,
iovec: &[IoVec<&[u8]>],
_len: usize,
) -> io::Result<usize> {
vmsplice(writer.raw_obj, iovec, SpliceFFlags::empty()).map_err(|_| io::Error::last_os_error())
}

View file

@ -1,7 +1,7 @@
#[cfg(unix)]
pub use self::unix::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::linux::*;
#[cfg(unix)]
pub use self::unix::*;
#[cfg(windows)]
pub use self::windows::*;
@ -9,10 +9,10 @@ pub use self::windows::*;
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub use self::default::*;
#[cfg(unix)]
mod unix;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux;
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;