Update message quoting and filename printing

This commit is contained in:
Jan Verbeek
2021-09-03 16:10:39 +02:00
parent 60df3c6b7c
commit 259f18fcab
91 changed files with 777 additions and 550 deletions
+2
View File
@@ -9,6 +9,8 @@ bytewise
canonicalization
canonicalize
canonicalizing
codepoint
codepoints
colorizable
colorize
coprime
+19 -10
View File
@@ -10,10 +10,12 @@ use clap::Arg;
use clap::Shell;
use std::cmp;
use std::collections::hash_map::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use uucore::display::Quotable;
const VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -76,13 +78,21 @@ fn main() {
// 0th argument equals util name?
if let Some(util_os) = util_name {
let util = util_os.as_os_str().to_string_lossy();
fn not_found(util: &OsStr) -> ! {
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
}
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
if util == "completion" {
gen_completions(args, utils);
}
match utils.get(&util[..]) {
match utils.get(util) {
Some(&(uumain, _)) => {
process::exit(uumain((vec![util_os].into_iter()).chain(args)));
}
@@ -90,9 +100,12 @@ fn main() {
if util == "--help" || util == "-h" {
// see if they want help on a specific util
if let Some(util_os) = args.next() {
let util = util_os.as_os_str().to_string_lossy();
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
match utils.get(&util[..]) {
match utils.get(util) {
Some(&(uumain, _)) => {
let code = uumain(
(vec![util_os, OsString::from("--help")].into_iter())
@@ -101,17 +114,13 @@ fn main() {
io::stdout().flush().expect("could not flush stdout");
process::exit(code);
}
None => {
println!("{}: function/utility not found", util);
process::exit(1);
}
None => not_found(&util_os),
}
}
usage(&utils, binary_as_util);
process::exit(0);
} else {
println!("{}: function/utility not found", util);
process::exit(1);
not_found(&util_os);
}
}
}
+6 -4
View File
@@ -9,6 +9,7 @@
use std::io::{stdout, Read, Write};
use uucore::display::Quotable;
use uucore::encoding::{wrap_print, Data, Format};
use uucore::InvalidEncodingHandling;
@@ -40,8 +41,9 @@ impl Config {
let name = values.next().unwrap();
if let Some(extra_op) = values.next() {
return Err(format!(
"extra operand '{}'\nTry '{} --help' for more information.",
extra_op, app_name
"extra operand {}\nTry '{} --help' for more information.",
extra_op.quote(),
app_name
));
}
@@ -49,7 +51,7 @@ impl Config {
None
} else {
if !Path::exists(Path::new(name)) {
return Err(format!("{}: No such file or directory", name));
return Err(format!("{}: No such file or directory", name.maybe_quote()));
}
Some(name.to_owned())
}
@@ -61,7 +63,7 @@ impl Config {
.value_of(options::WRAP)
.map(|num| {
num.parse::<usize>()
.map_err(|_| format!("invalid wrap size: '{}'", num))
.map_err(|_| format!("invalid wrap size: {}", num.quote()))
})
.transpose()?;
+2 -1
View File
@@ -20,6 +20,7 @@ use clap::{crate_version, App, Arg};
use std::fs::{metadata, File};
use std::io::{self, Read, Write};
use thiserror::Error;
use uucore::display::Quotable;
use uucore::error::UResult;
#[cfg(unix)]
@@ -386,7 +387,7 @@ fn cat_files(files: Vec<String>, options: &OutputOptions) -> UResult<()> {
for path in &files {
if let Err(err) = cat_path(path, options, &mut state, &out_info) {
error_messages.push(format!("{}: {}", path, err));
error_messages.push(format!("{}: {}", path.maybe_quote(), err));
}
}
if state.skipped_carriage_return {
+8 -8
View File
@@ -2,7 +2,7 @@
#![allow(clippy::upper_case_acronyms)]
use uucore::{show_error, show_usage_error, show_warning};
use uucore::{display::Quotable, show_error, show_usage_error, show_warning};
use clap::{App, Arg};
use selinux::{OpaqueSecurityContext, SecurityContext};
@@ -111,13 +111,13 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
Ok(context) => context,
Err(_r) => {
show_error!("Invalid security context '{}'.", context.to_string_lossy());
show_error!("Invalid security context {}.", context.quote());
return libc::EXIT_FAILURE;
}
};
if SecurityContext::from_c_str(&c_context, false).check() == Some(false) {
show_error!("Invalid security context '{}'.", context.to_string_lossy());
show_error!("Invalid security context {}.", context.quote());
return libc::EXIT_FAILURE;
}
@@ -564,7 +564,7 @@ fn process_file(
println!(
"{}: Changing security context of: {}",
uucore::util_name(),
file_full_name.to_string_lossy()
file_full_name.quote()
);
}
@@ -699,9 +699,9 @@ fn root_dev_ino_warn(dir_name: &Path) {
);
} else {
show_warning!(
"It is dangerous to operate recursively on '{}' (same as '/'). \
"It is dangerous to operate recursively on {} (same as '/'). \
Use --{} to override this failsafe.",
dir_name.to_string_lossy(),
dir_name.quote(),
options::preserve_root::NO_PRESERVE_ROOT,
);
}
@@ -726,8 +726,8 @@ fn emit_cycle_warning(file_name: &Path) {
"Circular directory structure.\n\
This almost certainly means that you have a corrupted file system.\n\
NOTIFY YOUR SYSTEM MANAGER.\n\
The following directory is part of the cycle '{}'.",
file_name.display()
The following directory is part of the cycle {}.",
file_name.quote()
)
}
+3 -1
View File
@@ -2,6 +2,8 @@ use std::ffi::OsString;
use std::fmt::Write;
use std::io;
use uucore::display::Quotable;
pub(crate) type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error, Debug)]
@@ -30,7 +32,7 @@ pub(crate) enum Error {
source: io::Error,
},
#[error("{operation} failed on '{}'", .operand1.to_string_lossy())]
#[error("{operation} failed on {}", .operand1.quote())]
Io1 {
operation: &'static str,
operand1: OsString,
+8 -2
View File
@@ -9,6 +9,7 @@
#[macro_use]
extern crate uucore;
use uucore::display::Quotable;
pub use uucore::entries;
use uucore::error::{FromIo, UResult, USimpleError};
use uucore::perms::{chown_base, options, IfFrom};
@@ -32,7 +33,7 @@ fn parse_gid_and_uid(matches: &ArgMatches) -> UResult<(Option<u32>, Option<u32>,
let dest_gid = if let Some(file) = matches.value_of(options::REFERENCE) {
fs::metadata(&file)
.map(|meta| Some(meta.gid()))
.map_err_context(|| format!("failed to get attributes of '{}'", file))?
.map_err_context(|| format!("failed to get attributes of {}", file.quote()))?
} else {
let group = matches.value_of(options::ARG_GROUP).unwrap_or_default();
if group.is_empty() {
@@ -40,7 +41,12 @@ fn parse_gid_and_uid(matches: &ArgMatches) -> UResult<(Option<u32>, Option<u32>,
} else {
match entries::grp2gid(group) {
Ok(g) => Some(g),
_ => return Err(USimpleError::new(1, format!("invalid group: '{}'", group))),
_ => {
return Err(USimpleError::new(
1,
format!("invalid group: {}", group.quote()),
))
}
}
}
};
+24 -18
View File
@@ -14,6 +14,7 @@ use clap::{crate_version, App, Arg};
use std::fs;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::Path;
use uucore::display::Quotable;
use uucore::fs::display_permissions_unix;
use uucore::libc::mode_t;
#[cfg(not(windows))]
@@ -75,7 +76,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
.value_of(options::REFERENCE)
.and_then(|fref| match fs::metadata(fref) {
Ok(meta) => Some(meta.mode()),
Err(err) => crash!(1, "cannot stat attributes of '{}': {}", fref, err),
Err(err) => crash!(1, "cannot stat attributes of {}: {}", fref.quote(), err),
});
let modes = matches.value_of(options::MODE).unwrap(); // should always be Some because required
let cmode = if mode_had_minus_prefix {
@@ -223,21 +224,24 @@ impl Chmoder {
if !file.exists() {
if is_symlink(file) {
println!(
"failed to change mode of '{}' from 0000 (---------) to 0000 (---------)",
filename
"failed to change mode of {} from 0000 (---------) to 0000 (---------)",
filename.quote()
);
if !self.quiet {
show_error!("cannot operate on dangling symlink '{}'", filename);
show_error!("cannot operate on dangling symlink {}", filename.quote());
}
} else if !self.quiet {
show_error!("cannot access '{}': No such file or directory", filename);
show_error!(
"cannot access {}: No such file or directory",
filename.quote()
);
}
return Err(1);
}
if self.recursive && self.preserve_root && filename == "/" {
show_error!(
"it is dangerous to operate recursively on '{}'\nuse --no-preserve-root to override this failsafe",
filename
"it is dangerous to operate recursively on {}\nuse --no-preserve-root to override this failsafe",
filename.quote()
);
return Err(1);
}
@@ -270,15 +274,17 @@ impl Chmoder {
if is_symlink(file) {
if self.verbose {
println!(
"neither symbolic link '{}' nor referent has been changed",
file.display()
"neither symbolic link {} nor referent has been changed",
file.quote()
);
}
return Ok(());
} else if err.kind() == std::io::ErrorKind::PermissionDenied {
show_error!("'{}': Permission denied", file.display());
// These two filenames would normally be conditionally
// quoted, but GNU's tests expect them to always be quoted
show_error!("{}: Permission denied", file.quote());
} else {
show_error!("'{}': {}", file.display(), err);
show_error!("{}: {}", file.quote(), err);
}
return Err(1);
}
@@ -325,7 +331,7 @@ impl Chmoder {
if (new_mode & !naively_expected_new_mode) != 0 {
show_error!(
"{}: new permissions are {}, not {}",
file.display(),
file.maybe_quote(),
display_permissions_unix(new_mode as mode_t, false),
display_permissions_unix(naively_expected_new_mode as mode_t, false)
);
@@ -342,8 +348,8 @@ impl Chmoder {
if fperm == mode {
if self.verbose && !self.changes {
println!(
"mode of '{}' retained as {:04o} ({})",
file.display(),
"mode of {} retained as {:04o} ({})",
file.quote(),
fperm,
display_permissions_unix(fperm as mode_t, false),
);
@@ -355,8 +361,8 @@ impl Chmoder {
}
if self.verbose {
println!(
"failed to change mode of file '{}' from {:04o} ({}) to {:04o} ({})",
file.display(),
"failed to change mode of file {} from {:04o} ({}) to {:04o} ({})",
file.quote(),
fperm,
display_permissions_unix(fperm as mode_t, false),
mode,
@@ -367,8 +373,8 @@ impl Chmoder {
} else {
if self.verbose || self.changes {
println!(
"mode of '{}' changed from {:04o} ({}) to {:04o} ({})",
file.display(),
"mode of {} changed from {:04o} ({}) to {:04o} ({})",
file.quote(),
fperm,
display_permissions_unix(fperm as mode_t, false),
mode,
+4 -3
View File
@@ -9,6 +9,7 @@
#[macro_use]
extern crate uucore;
use uucore::display::Quotable;
pub use uucore::entries::{self, Group, Locate, Passwd};
use uucore::perms::{chown_base, options, IfFrom};
@@ -44,7 +45,7 @@ fn parse_gid_uid_and_filter(matches: &ArgMatches) -> UResult<(Option<u32>, Optio
let dest_gid: Option<u32>;
if let Some(file) = matches.value_of(options::REFERENCE) {
let meta = fs::metadata(&file)
.map_err_context(|| format!("failed to get attributes of '{}'", file))?;
.map_err_context(|| format!("failed to get attributes of {}", file.quote()))?;
dest_gid = Some(meta.gid());
dest_uid = Some(meta.uid());
} else {
@@ -173,7 +174,7 @@ fn parse_spec(spec: &str) -> UResult<(Option<u32>, Option<u32>)> {
let uid = if usr_only || usr_grp {
Some(
Passwd::locate(args[0])
.map_err(|_| USimpleError::new(1, format!("invalid user: '{}'", spec)))?
.map_err(|_| USimpleError::new(1, format!("invalid user: {}", spec.quote())))?
.uid(),
)
} else {
@@ -182,7 +183,7 @@ fn parse_spec(spec: &str) -> UResult<(Option<u32>, Option<u32>)> {
let gid = if grp_only || usr_grp {
Some(
Group::locate(args[1])
.map_err(|_| USimpleError::new(1, format!("invalid group: '{}'", spec)))?
.map_err(|_| USimpleError::new(1, format!("invalid group: {}", spec.quote())))?
.gid(),
)
} else {
+11 -6
View File
@@ -15,6 +15,7 @@ use std::ffi::CString;
use std::io::Error;
use std::path::Path;
use std::process::Command;
use uucore::display::Quotable;
use uucore::libc::{self, chroot, setgid, setgroups, setuid};
use uucore::{entries, InvalidEncodingHandling};
@@ -53,8 +54,8 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
if !newroot.is_dir() {
crash!(
1,
"cannot change root directory to `{}`: no such directory",
newroot.display()
"cannot change root directory to {}: no such directory",
newroot.quote()
);
}
@@ -170,7 +171,6 @@ fn set_context(root: &Path, options: &clap::ArgMatches) {
}
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)
@@ -179,7 +179,7 @@ fn enter_chroot(root: &Path) {
crash!(
1,
"cannot chroot to {}: {}",
root_str,
root.quote(),
Error::last_os_error()
)
};
@@ -189,7 +189,7 @@ fn set_main_group(group: &str) {
if !group.is_empty() {
let group_id = match entries::grp2gid(group) {
Ok(g) => g,
_ => crash!(1, "no such group: {}", group),
_ => crash!(1, "no such group: {}", group.maybe_quote()),
};
let err = unsafe { setgid(group_id) };
if err != 0 {
@@ -234,7 +234,12 @@ fn set_user(user: &str) {
let user_id = entries::usr2uid(user).unwrap();
let err = unsafe { setuid(user_id as libc::uid_t) };
if err != 0 {
crash!(1, "cannot set user to {}: {}", user, Error::last_os_error())
crash!(
1,
"cannot set user to {}: {}",
user.maybe_quote(),
Error::last_os_error()
)
}
}
}
+3 -2
View File
@@ -14,6 +14,7 @@ use clap::{crate_version, App, Arg};
use std::fs::File;
use std::io::{self, stdin, BufReader, Read};
use std::path::Path;
use uucore::display::Quotable;
use uucore::InvalidEncodingHandling;
// NOTE: CRC_TABLE_LEN *must* be <= 256 as we cast 0..CRC_TABLE_LEN to u8
@@ -191,7 +192,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
match cksum("-") {
Ok((crc, size)) => println!("{} {}", crc, size),
Err(err) => {
show_error!("{}", err);
show_error!("-: {}", err);
return 2;
}
}
@@ -203,7 +204,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
match cksum(fname.as_ref()) {
Ok((crc, size)) => println!("{} {} {}", crc, size, fname),
Err(err) => {
show_error!("'{}' {}", fname, err);
show_error!("{}: {}", fname.maybe_quote(), err);
exit_code = 2;
}
}
+18 -17
View File
@@ -18,6 +18,7 @@ extern crate quick_error;
#[macro_use]
extern crate uucore;
use uucore::display::Quotable;
#[cfg(windows)]
use winapi::um::fileapi::CreateFileW;
#[cfg(windows)]
@@ -541,8 +542,8 @@ impl FromStr for Attribute {
"xattr" => Attribute::Xattr,
_ => {
return Err(Error::InvalidArgument(format!(
"invalid attribute '{}'",
value
"invalid attribute {}",
value.quote()
)));
}
})
@@ -659,8 +660,8 @@ impl Options {
"never" => ReflinkMode::Never,
value => {
return Err(Error::InvalidArgument(format!(
"invalid argument '{}' for \'reflink\'",
value
"invalid argument {} for \'reflink\'",
value.quote()
)));
}
}
@@ -832,7 +833,7 @@ fn copy(sources: &[Source], target: &TargetSlice, options: &Options) -> CopyResu
let mut seen_sources = HashSet::with_capacity(sources.len());
for source in sources {
if seen_sources.contains(source) {
show_warning!("source '{}' specified more than once", source.display());
show_warning!("source {} specified more than once", source.quote());
} else {
let mut found_hard_link = false;
if preserve_hard_links {
@@ -873,8 +874,8 @@ fn construct_dest_path(
) -> CopyResult<PathBuf> {
if options.no_target_dir && target.is_dir() {
return Err(format!(
"cannot overwrite directory '{}' with non-directory",
target.display()
"cannot overwrite directory {} with non-directory",
target.quote()
)
.into());
}
@@ -941,7 +942,7 @@ fn adjust_canonicalization(p: &Path) -> Cow<Path> {
/// will not cause a short-circuit.
fn copy_directory(root: &Path, target: &TargetSlice, options: &Options) -> CopyResult<()> {
if !options.recursive {
return Err(format!("omitting directory '{}'", root.display()).into());
return Err(format!("omitting directory {}", root.quote()).into());
}
// if no-dereference is enabled and this is a symlink, copy it as a file
@@ -1041,12 +1042,12 @@ impl OverwriteMode {
match *self {
OverwriteMode::NoClobber => Err(Error::NotAllFilesCopied),
OverwriteMode::Interactive(_) => {
if prompt_yes!("{}: overwrite {}? ", uucore::util_name(), path.display()) {
if prompt_yes!("{}: overwrite {}? ", uucore::util_name(), path.quote()) {
Ok(())
} else {
Err(Error::Skipped(format!(
"Not overwriting {} at user request",
path.display()
path.quote()
)))
}
}
@@ -1056,7 +1057,7 @@ impl OverwriteMode {
}
fn copy_attribute(source: &Path, dest: &Path, attribute: &Attribute) -> CopyResult<()> {
let context = &*format!("'{}' -> '{}'", source.display().to_string(), dest.display());
let context = &*format!("{} -> {}", source.quote(), dest.quote());
let source_metadata = fs::symlink_metadata(source).context(context)?;
match *attribute {
Attribute::Mode => {
@@ -1152,7 +1153,7 @@ fn symlink_file(source: &Path, dest: &Path, context: &str) -> CopyResult<()> {
}
fn context_for(src: &Path, dest: &Path) -> String {
format!("'{}' -> '{}'", src.display(), dest.display())
format!("{} -> {}", src.quote(), dest.quote())
}
/// Implements a simple backup copy for the destination file.
@@ -1332,8 +1333,8 @@ fn copy_link(source: &Path, dest: &Path) -> CopyResult<()> {
Some(name) => dest.join(name).into(),
None => crash!(
EXIT_ERR,
"cannot stat '{}': No such file or directory",
source.display()
"cannot stat {}: No such file or directory",
source.quote()
),
}
} else {
@@ -1454,11 +1455,11 @@ fn copy_on_write_macos(
pub fn verify_target_type(target: &Path, target_type: &TargetType) -> CopyResult<()> {
match (target_type, target.is_dir()) {
(&TargetType::Directory, false) => {
Err(format!("target: '{}' is not a directory", target.display()).into())
Err(format!("target: {} is not a directory", target.quote()).into())
}
(&TargetType::File, true) => Err(format!(
"cannot overwrite directory '{}' with non-directory",
target.display()
"cannot overwrite directory {} with non-directory",
target.quote()
)
.into()),
_ => Ok(()),
+2 -1
View File
@@ -10,6 +10,7 @@ use std::{
fs::{remove_file, File},
io::{BufRead, BufWriter, Write},
};
use uucore::display::Quotable;
mod csplit_error;
mod patterns;
@@ -734,7 +735,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
let file = crash_if_err!(1, File::open(file_name));
let file_metadata = crash_if_err!(1, file.metadata());
if !file_metadata.is_file() {
crash!(1, "'{}' is not a regular file", file_name);
crash!(1, "{} is not a regular file", file_name.quote());
}
crash_if_err!(1, csplit(&options, patterns, BufReader::new(file)));
};
+8 -6
View File
@@ -1,26 +1,28 @@
use std::io;
use thiserror::Error;
use uucore::display::Quotable;
/// Errors thrown by the csplit command
#[derive(Debug, Error)]
pub enum CsplitError {
#[error("IO error: {}", _0)]
IoError(io::Error),
#[error("'{}': line number out of range", _0)]
#[error("{}: line number out of range", ._0.quote())]
LineOutOfRange(String),
#[error("'{}': line number out of range on repetition {}", _0, _1)]
#[error("{}: line number out of range on repetition {}", ._0.quote(), _1)]
LineOutOfRangeOnRepetition(String, usize),
#[error("'{}': match not found", _0)]
#[error("{}: match not found", ._0.quote())]
MatchNotFound(String),
#[error("'{}': match not found on repetition {}", _0, _1)]
#[error("{}: match not found on repetition {}", ._0.quote(), _1)]
MatchNotFoundOnRepetition(String, usize),
#[error("line number must be greater than zero")]
LineNumberIsZero,
#[error("line number '{}' is smaller than preceding line number, {}", _0, _1)]
LineNumberSmallerThanPrevious(usize, usize),
#[error("invalid pattern: {}", _0)]
#[error("{}: invalid pattern", ._0.quote())]
InvalidPattern(String),
#[error("invalid number: '{}'", _0)]
#[error("invalid number: {}", ._0.quote())]
InvalidNumber(String),
#[error("incorrect conversion specification in suffix")]
SuffixFormatIncorrect,
+4 -3
View File
@@ -15,6 +15,7 @@ use clap::{crate_version, App, Arg};
use std::fs::File;
use std::io::{stdin, stdout, BufReader, BufWriter, Read, Write};
use std::path::Path;
use uucore::display::Quotable;
use self::searcher::Searcher;
use uucore::ranges::Range;
@@ -351,19 +352,19 @@ fn cut_files(mut filenames: Vec<String>, mode: Mode) -> i32 {
let path = Path::new(&filename[..]);
if path.is_dir() {
show_error!("{}: Is a directory", filename);
show_error!("{}: Is a directory", filename.maybe_quote());
continue;
}
if path.metadata().is_err() {
show_error!("{}: No such file or directory", filename);
show_error!("{}: No such file or directory", filename.maybe_quote());
continue;
}
let file = match File::open(&path) {
Ok(f) => f,
Err(e) => {
show_error!("opening '{}': {}", &filename[..], e);
show_error!("opening {}: {}", filename.quote(), e);
continue;
}
};
+4 -3
View File
@@ -17,6 +17,7 @@ use libc::{clock_settime, timespec, CLOCK_REALTIME};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use uucore::display::Quotable;
#[cfg(windows)]
use winapi::{
shared::minwindef::WORD,
@@ -145,7 +146,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
let format = if let Some(form) = matches.value_of(OPT_FORMAT) {
if !form.starts_with('+') {
eprintln!("date: invalid date '{}'", form);
eprintln!("date: invalid date {}", form.quote());
return 1;
}
let form = form[1..].to_string();
@@ -174,7 +175,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
let set_to = match matches.value_of(OPT_SET).map(parse_date) {
None => None,
Some(Err((input, _err))) => {
eprintln!("date: invalid date '{}'", input);
eprintln!("date: invalid date {}", input.quote());
return 1;
}
Some(Ok(date)) => Some(date),
@@ -240,7 +241,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
println!("{}", formatted);
}
Err((input, _err)) => {
println!("date: invalid date '{}'", input);
println!("date: invalid date {}", input.quote());
}
}
}
+13 -6
View File
@@ -17,6 +17,7 @@ use std::fs::File;
use std::io::{BufRead, BufReader};
use clap::{crate_version, App, Arg};
use uucore::display::Quotable;
mod options {
pub const BOURNE_SHELL: &str = "bourne-shell";
@@ -94,9 +95,9 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
if matches.is_present(options::PRINT_DATABASE) {
if !files.is_empty() {
show_usage_error!(
"extra operand '{}'\nfile operands cannot be combined with \
"extra operand {}\nfile operands cannot be combined with \
--print-database (-p)",
files[0]
files[0].quote()
);
return 1;
}
@@ -126,7 +127,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
result = parse(INTERNAL_DB.lines(), out_format, "")
} else {
if files.len() > 1 {
show_usage_error!("extra operand '{}'", files[1]);
show_usage_error!("extra operand {}", files[1].quote());
return 1;
}
match File::open(files[0]) {
@@ -135,7 +136,7 @@ pub fn uumain(args: impl uucore::Args) -> i32 {
result = parse(fin.lines().filter_map(Result::ok), out_format, files[0])
}
Err(e) => {
show_error!("{}: {}", files[0], e);
show_error!("{}: {}", files[0].maybe_quote(), e);
return 1;
}
}
@@ -314,7 +315,8 @@ where
if val.is_empty() {
return Err(format!(
"{}:{}: invalid line; missing second token",
fp, num
fp.maybe_quote(),
num
));
}
let lower = key.to_lowercase();
@@ -341,7 +343,12 @@ where
} else if let Some(s) = table.get(lower.as_str()) {
result.push_str(format!("{}={}:", s, val).as_str());
} else {
return Err(format!("{}:{}: unrecognized keyword {}", fp, num, key));
return Err(format!(
"{}:{}: unrecognized keyword {}",
fp.maybe_quote(),
num,
key
));
}
}
}
+2 -1
View File
@@ -10,6 +10,7 @@ extern crate uucore;
use clap::{crate_version, App, Arg};
use std::path::Path;
use uucore::display::print_verbatim;
use uucore::error::{UResult, UUsageError};
use uucore::InvalidEncodingHandling;
@@ -65,7 +66,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
if d.components().next() == None {
print!(".")
} else {
print!("{}", d.to_string_lossy());
print_verbatim(d).unwrap();
}
}
None => {
+28 -26
View File
@@ -32,6 +32,7 @@ use std::path::PathBuf;
use std::str::FromStr;
use std::time::{Duration, UNIX_EPOCH};
use std::{error::Error, fmt::Display};
use uucore::display::{print_verbatim, Quotable};
use uucore::error::{UError, UResult};
use uucore::parse_size::{parse_size, ParseSizeError};
use uucore::InvalidEncodingHandling;
@@ -293,9 +294,9 @@ fn du(
Err(e) => {
safe_writeln!(
stderr(),
"{}: cannot read directory '{}': {}",
"{}: cannot read directory {}: {}",
options.util_name,
my_stat.path.display(),
my_stat.path.quote(),
e
);
return Box::new(iter::once(my_stat));
@@ -334,11 +335,11 @@ fn du(
}
Err(error) => match error.kind() {
ErrorKind::PermissionDenied => {
let description = format!("cannot access '{}'", entry.path().display());
let description = format!("cannot access {}", entry.path().quote());
let error_message = "Permission denied";
show_error_custom_description!(description, "{}", error_message)
}
_ => show_error!("cannot access '{}': {}", entry.path().display(), error),
_ => show_error!("cannot access {}: {}", entry.path().quote(), error),
},
},
Err(error) => show_error!("{}", error),
@@ -411,26 +412,30 @@ enum DuError {
impl Display for DuError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DuError::InvalidMaxDepthArg(s) => write!(f, "invalid maximum depth '{}'", s),
DuError::InvalidMaxDepthArg(s) => write!(f, "invalid maximum depth {}", s.quote()),
DuError::SummarizeDepthConflict(s) => {
write!(f, "summarizing conflicts with --max-depth={}", s)
write!(
f,
"summarizing conflicts with --max-depth={}",
s.maybe_quote()
)
}
DuError::InvalidTimeStyleArg(s) => write!(
f,
"invalid argument '{}' for 'time style'
"invalid argument {} for 'time style'
Valid arguments are:
- 'full-iso'
- 'long-iso'
- 'iso'
Try '{} --help' for more information.",
s,
s.quote(),
uucore::execution_phrase()
),
DuError::InvalidTimeArg(s) => write!(
f,
"Invalid argument '{}' for --time.
"Invalid argument {} for --time.
'birth' and 'creation' arguments are not supported on this platform.",
s
s.quote()
),
}
}
@@ -566,21 +571,14 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
};
if !summarize || index == len - 1 {
let time_str = tm.format(time_format_str).to_string();
print!(
"{}\t{}\t{}{}",
convert_size(size),
time_str,
stat.path.display(),
line_separator
);
print!("{}\t{}\t", convert_size(size), time_str);
print_verbatim(stat.path).unwrap();
print!("{}", line_separator);
}
} else if !summarize || index == len - 1 {
print!(
"{}\t{}{}",
convert_size(size),
stat.path.display(),
line_separator
);
print!("{}\t", convert_size(size));
print_verbatim(stat.path).unwrap();
print!("{}", line_separator);
}
if options.total && index == (len - 1) {
// The last element will be the total size of the the path under
@@ -590,7 +588,11 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
}
}
Err(_) => {
show_error!("{}: {}", path_string, "No such file or directory");
show_error!(
"{}: {}",
path_string.maybe_quote(),
"No such file or directory"
);
}
}
}
@@ -837,8 +839,8 @@ fn format_error_message(error: ParseSizeError, s: &str, option: &str) -> String
// GNU's du echos affected flag, -B or --block-size (-t or --threshold), depending user's selection
// GNU's du does distinguish between "invalid (suffix in) argument"
match error {
ParseSizeError::ParseFailure(_) => format!("invalid --{} argument '{}'", option, s),
ParseSizeError::SizeTooBig(_) => format!("--{} argument '{}' too large", option, s),
ParseSizeError::ParseFailure(_) => format!("invalid --{} argument {}", option, s.quote()),
ParseSizeError::SizeTooBig(_) => format!("--{} argument {} too large", option, s.quote()),
}
}
+8 -2
View File
@@ -65,8 +65,14 @@ fn parse_name_value_opt<'a>(opts: &mut Options<'a>, opt: &'a str) -> Result<bool
fn parse_program_opt<'a>(opts: &mut Options<'a>, opt: &'a str) -> Result<(), i32> {
if opts.null {
eprintln!("{}: cannot specify --null (-0) with command", crate_name!());
eprintln!("Type \"{} --help\" for detailed information", crate_name!());
eprintln!(
"{}: cannot specify --null (-0) with command",
uucore::util_name()
);
eprintln!(
"Type \"{} --help\" for detailed information",
uucore::execution_phrase()
);
Err(1)
} else {
opts.program.push(opt);

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