Prefer implementing Display over a custom .display() method

pull/640/head
Wilfred Hughes 2024-02-08 08:34:48 +07:00
parent 6cc1a5f3e3
commit 4146067be1
2 changed files with 12 additions and 15 deletions

@ -81,23 +81,16 @@ fn read_file_arg(file_arg: &FileArgument) -> std::io::Result<Vec<u8>> {
fn eprint_read_error(file_arg: &FileArgument, e: &std::io::Error) {
match e.kind() {
std::io::ErrorKind::NotFound => {
eprintln!("No such file: {}", file_arg.display());
eprintln!("No such file: {}", file_arg);
}
std::io::ErrorKind::PermissionDenied => {
eprintln!(
"Permission denied when reading file: {}",
file_arg.display()
);
eprintln!("Permission denied when reading file: {}", file_arg);
}
_ => match file_arg {
FileArgument::NamedPath(path) if path.is_dir() => {
eprintln!("Expected a file, got a directory: {}", path.display());
}
_ => eprintln!(
"Could not read file: {} (error {:?})",
file_arg.display(),
e.kind()
),
_ => eprintln!("Could not read file: {} (error {:?})", file_arg, e.kind()),
},
};
}

@ -1,6 +1,6 @@
//! CLI option parsing.
use std::{env, ffi::OsStr, path::Path, path::PathBuf};
use std::{env, ffi::OsStr, fmt::Display, path::Path, path::PathBuf};
use clap::{crate_authors, crate_description, Arg, Command};
use const_format::formatcp;
@ -352,12 +352,16 @@ impl FileArgument {
FileArgument::NamedPath(PathBuf::from(arg))
}
}
}
pub(crate) fn display(&self) -> String {
impl Display for FileArgument {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FileArgument::NamedPath(path) => relative_to_current(path).display().to_string(),
FileArgument::Stdin => "(stdin)".to_string(),
FileArgument::DevNull => "/dev/null".to_string(),
FileArgument::NamedPath(path) => {
write!(f, "{}", relative_to_current(path).display())
}
FileArgument::Stdin => write!(f, "(stdin)"),
FileArgument::DevNull => write!(f, "/dev/null"),
}
}
}