#[cfg(feature = "libc")]
pub extern crate libc;
#[cfg(all(feature = "windows-sys", target_os = "windows"))]
pub extern crate windows_sys;
mod features; mod macros; mod mods;
pub use uucore_procs::*;
pub use crate::mods::display;
pub use crate::mods::error;
#[cfg(feature = "fs")]
pub use crate::mods::io;
pub use crate::mods::line_ending;
pub use crate::mods::locale;
pub use crate::mods::os;
pub use crate::mods::panic;
pub use crate::mods::posix;
#[cfg(feature = "backup-control")]
pub use crate::features::backup_control;
#[cfg(feature = "buf-copy")]
pub use crate::features::buf_copy;
#[cfg(feature = "checksum")]
pub use crate::features::checksum;
#[cfg(feature = "colors")]
pub use crate::features::colors;
#[cfg(feature = "custom-tz-fmt")]
pub use crate::features::custom_tz_fmt;
#[cfg(feature = "encoding")]
pub use crate::features::encoding;
#[cfg(feature = "extendedbigdecimal")]
pub use crate::features::extendedbigdecimal;
#[cfg(feature = "fast-inc")]
pub use crate::features::fast_inc;
#[cfg(feature = "format")]
pub use crate::features::format;
#[cfg(feature = "fs")]
pub use crate::features::fs;
#[cfg(feature = "lines")]
pub use crate::features::lines;
#[cfg(feature = "parser")]
pub use crate::features::parser;
#[cfg(feature = "quoting-style")]
pub use crate::features::quoting_style;
#[cfg(feature = "ranges")]
pub use crate::features::ranges;
#[cfg(feature = "ringbuffer")]
pub use crate::features::ringbuffer;
#[cfg(feature = "sum")]
pub use crate::features::sum;
#[cfg(feature = "update-control")]
pub use crate::features::update_control;
#[cfg(feature = "uptime")]
pub use crate::features::uptime;
#[cfg(feature = "version-cmp")]
pub use crate::features::version_cmp;
#[cfg(all(not(windows), feature = "mode"))]
pub use crate::features::mode;
#[cfg(all(unix, feature = "entries"))]
pub use crate::features::entries;
#[cfg(all(unix, feature = "perms"))]
pub use crate::features::perms;
#[cfg(all(unix, any(feature = "pipes", feature = "buf-copy")))]
pub use crate::features::pipes;
#[cfg(all(unix, feature = "process"))]
pub use crate::features::process;
#[cfg(all(unix, not(target_os = "fuchsia"), feature = "signals"))]
pub use crate::features::signals;
#[cfg(all(
unix,
not(target_os = "android"),
not(target_os = "fuchsia"),
not(target_os = "openbsd"),
not(target_os = "redox"),
feature = "utmpx"
))]
pub use crate::features::utmpx;
#[cfg(all(windows, feature = "wide"))]
pub use crate::features::wide;
#[cfg(feature = "fsext")]
pub use crate::features::fsext;
#[cfg(all(unix, feature = "fsxattr"))]
pub use crate::features::fsxattr;
#[cfg(all(target_os = "linux", feature = "selinux"))]
pub use crate::features::selinux;
#[cfg(unix)]
use nix::errno::Errno;
#[cfg(unix)]
use nix::sys::signal::{
SaFlags, SigAction, SigHandler::SigDfl, SigSet, Signal::SIGBUS, Signal::SIGSEGV, sigaction,
};
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::io::{BufRead, BufReader};
use std::iter;
#[cfg(unix)]
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::str;
use std::sync::{LazyLock, atomic::Ordering};
#[cfg(unix)]
pub fn disable_rust_signal_handlers() -> Result<(), Errno> {
unsafe {
sigaction(
SIGSEGV,
&SigAction::new(SigDfl, SaFlags::empty(), SigSet::all()),
)
}?;
unsafe {
sigaction(
SIGBUS,
&SigAction::new(SigDfl, SaFlags::empty(), SigSet::all()),
)
}?;
Ok(())
}
#[macro_export]
macro_rules! bin {
($util:ident) => {
pub fn main() {
use std::io::Write;
uucore::panic::mute_sigpipe_panic();
let code = $util::uumain(uucore::args_os());
if let Err(e) = std::io::stdout().flush() {
eprintln!("Error flushing stdout: {e}");
}
std::process::exit(code);
}
};
}
#[macro_export]
macro_rules! crate_version {
() => {
concat!(
"(",
env!("PROJECT_NAME_FOR_VERSION_STRING"),
") ",
env!("CARGO_PKG_VERSION")
)
};
}
pub fn format_usage(s: &str) -> String {
let s = s.replace('\n', &format!("\n{}", " ".repeat(7)));
s.replace("{}", crate::execution_phrase())
}
pub fn get_utility_is_second_arg() -> bool {
crate::macros::UTILITY_IS_SECOND_ARG.load(Ordering::SeqCst)
}
pub fn set_utility_is_second_arg() {
crate::macros::UTILITY_IS_SECOND_ARG.store(true, Ordering::SeqCst);
}
static ARGV: LazyLock<Vec<OsString>> = LazyLock::new(|| wild::args_os().collect());
static UTIL_NAME: LazyLock<String> = LazyLock::new(|| {
let base_index = usize::from(get_utility_is_second_arg());
let is_man = usize::from(ARGV[base_index].eq("manpage"));
let argv_index = base_index + is_man;
ARGV[argv_index].to_string_lossy().into_owned()
});
pub fn util_name() -> &'static str {
&UTIL_NAME
}
static EXECUTION_PHRASE: LazyLock<String> = LazyLock::new(|| {
if get_utility_is_second_arg() {
ARGV.iter()
.take(2)
.map(|os_str| os_str.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" ")
} else {
ARGV[0].to_string_lossy().into_owned()
}
});
pub fn execution_phrase() -> &'static str {
&EXECUTION_PHRASE
}
pub trait Args: Iterator<Item = OsString> + Sized {
fn collect_lossy(self) -> Vec<String> {
self.map(|s| s.to_string_lossy().into_owned()).collect()
}
fn collect_ignore(self) -> Vec<String> {
self.filter_map(|s| s.into_string().ok()).collect()
}
}
impl<T: Iterator<Item = OsString> + Sized> Args for T {}
pub fn args_os() -> impl Iterator<Item = OsString> {
ARGV.iter().cloned()
}
pub fn read_yes() -> bool {
let mut s = String::new();
match std::io::stdin().read_line(&mut s) {
Ok(_) => matches!(s.chars().next(), Some('y' | 'Y')),
_ => false,
}
}
pub fn os_str_as_bytes(os_string: &OsStr) -> mods::error::UResult<&[u8]> {
#[cfg(unix)]
let bytes = os_string.as_bytes();
#[cfg(not(unix))]
let bytes = os_string
.to_str()
.ok_or_else(|| {
mods::error::UUsageError::new(1, "invalid UTF-8 was detected in one or more arguments")
})?
.as_bytes();
Ok(bytes)
}
pub fn os_str_as_bytes_lossy(os_string: &OsStr) -> Cow<[u8]> {
#[cfg(unix)]
let bytes = Cow::from(os_string.as_bytes());
#[cfg(not(unix))]
let bytes = match os_string.to_string_lossy() {
Cow::Borrowed(slice) => Cow::from(slice.as_bytes()),
Cow::Owned(owned) => Cow::from(owned.into_bytes()),
};
bytes
}
pub fn os_str_from_bytes(bytes: &[u8]) -> mods::error::UResult<Cow<'_, OsStr>> {
#[cfg(unix)]
let os_str = Cow::Borrowed(OsStr::from_bytes(bytes));
#[cfg(not(unix))]
let os_str = Cow::Owned(OsString::from(str::from_utf8(bytes).map_err(|_| {
mods::error::UUsageError::new(1, "Unable to transform bytes into OsStr")
})?));
Ok(os_str)
}
pub fn os_string_from_vec(vec: Vec<u8>) -> mods::error::UResult<OsString> {
#[cfg(unix)]
let s = OsString::from_vec(vec);
#[cfg(not(unix))]
let s = OsString::from(String::from_utf8(vec).map_err(|_| {
mods::error::UUsageError::new(1, "invalid UTF-8 was detected in one or more arguments")
})?);
Ok(s)
}
pub fn read_byte_lines<R: std::io::Read>(
mut buf_reader: BufReader<R>,
) -> impl Iterator<Item = Vec<u8>> {
iter::from_fn(move || {
let mut buf = Vec::with_capacity(256);
let size = buf_reader.read_until(b'\n', &mut buf).ok()?;
if size == 0 {
return None;
}
if buf.ends_with(b"\n") {
buf.pop();
if buf.ends_with(b"\r") {
buf.pop();
}
}
Some(buf)
})
}
pub fn read_os_string_lines<R: std::io::Read>(
buf_reader: BufReader<R>,
) -> impl Iterator<Item = OsString> {
read_byte_lines(buf_reader).map(|byte_line| os_string_from_vec(byte_line).expect("UTF-8 error"))
}
#[macro_export]
macro_rules! prompt_yes(
($($args:tt)+) => ({
use std::io::Write;
eprint!("{}: ", uucore::util_name());
eprint!($($args)+);
eprint!(" ");
let res = std::io::stderr().flush().map_err(|err| {
$crate::error::USimpleError::new(1, err.to_string())
});
uucore::show_if_err!(res);
uucore::read_yes()
})
);
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsStr;
fn make_os_vec(os_str: &OsStr) -> Vec<OsString> {
vec![
OsString::from("test"),
OsString::from("สวัสดี"), os_str.to_os_string(),
]
}
#[cfg(any(unix, target_os = "redox"))]
fn test_invalid_utf8_args_lossy(os_str: &OsStr) {
assert!(os_str.to_os_string().into_string().is_err());
let test_vec = make_os_vec(os_str);
let collected_to_str = test_vec.clone().into_iter().collect_lossy();
assert_eq!(collected_to_str.len(), test_vec.len());
for index in 0..2 {
assert_eq!(collected_to_str[index], test_vec[index].to_str().unwrap());
}
assert_eq!(
*collected_to_str[2],
os_str.to_os_string().to_string_lossy()
);
}
#[cfg(any(unix, target_os = "redox"))]
fn test_invalid_utf8_args_ignore(os_str: &OsStr) {
assert!(os_str.to_os_string().into_string().is_err());
let test_vec = make_os_vec(os_str);
let collected_to_str = test_vec.clone().into_iter().collect_ignore();
assert_eq!(collected_to_str.len(), test_vec.len() - 1);
for index in 0..2 {
assert_eq!(
collected_to_str.get(index).unwrap(),
test_vec.get(index).unwrap().to_str().unwrap()
);
}
}
#[test]
fn valid_utf8_encoding_args() {
let test_vec = make_os_vec(&OsString::from("test2"));
let _ = test_vec.into_iter().collect_lossy();
}
#[cfg(any(unix, target_os = "redox"))]
#[test]
fn invalid_utf8_args_unix() {
use std::os::unix::ffi::OsStrExt;
let source = [0x66, 0x6f, 0x80, 0x6f];
let os_str = OsStr::from_bytes(&source[..]);
test_invalid_utf8_args_lossy(os_str);
test_invalid_utf8_args_ignore(os_str);
}
#[test]
fn test_format_usage() {
assert_eq!(format_usage("expr EXPRESSION"), "expr EXPRESSION");
assert_eq!(
format_usage("expr EXPRESSION\nexpr OPTION"),
"expr EXPRESSION\n expr OPTION"
);
}
}