Skip to content

Commit

Permalink
Ensure PathBuf isn't used for STDIN "-" source
Browse files Browse the repository at this point in the history
  • Loading branch information
havenwood committed Nov 18, 2024
1 parent e1cab6a commit 0a77622
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 17 deletions.
4 changes: 2 additions & 2 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use word_tally::{Case, Sort};
#[command(about, version)]
pub struct Args {
/// File path to use as input rather than stdin ("-").
#[arg(value_name = "PATH", default_value = "-", value_parser = clap::value_parser!(PathBuf))]
pub input: PathBuf,
#[arg(default_value = "-", value_name = "PATH")]
pub input: String,

/// Sort order.
#[arg(short, long, default_value_t, value_enum, value_name = "ORDER")]
Expand Down
19 changes: 12 additions & 7 deletions src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ pub enum Input {

impl Input {
/// Construct an `Input` from a file path or stdin.
pub fn from_args(path: PathBuf) -> Result<Self> {
if path.to_str() == Some("-") {
pub fn from_args(path: String) -> Result<Self> {
if path == "-" {
Ok(Self::Stdin)
} else {
Ok(Self::File(path))
Ok(Self::File(PathBuf::from(path)))
}
}

Expand All @@ -31,11 +31,16 @@ impl Input {
}
}

/// Returns the file name of the input if available.
pub fn file_name(&self) -> Option<&str> {
/// Returns the file name of the input or `"-"` for STDIN.
pub fn source(&self) -> String {
match self {
Self::File(path) => path.file_name()?.to_str(),
Self::Stdin => None,
Self::File(path) => path
.file_name()
.expect("File name inaccessible.")
.to_str()
.expect("File name invalid UTF-8."),
Self::Stdin => "-",
}
.to_string()
}
}
11 changes: 3 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ fn main() -> Result<()> {
let delimiter = unescape(&args.delimiter)?;

let input = Input::from_args(args.input)?;
let input_file_name = input.file_name().unwrap_or("-").to_string();
let source = input.source();
let reader = input
.get_reader()
.context(format!("Failed to read from {}.", input_file_name))?;
.context(format!("Failed to read from {}.", source))?;

let options = Options {
case: args.case,
Expand All @@ -41,12 +41,7 @@ fn main() -> Result<()> {
let verbose = Verbose {};

let mut stderr_output = Output::stderr();
verbose.log(
&mut stderr_output,
&word_tally,
&delimiter,
&input_file_name,
)?;
verbose.log(&mut stderr_output, &word_tally, &delimiter, &source)?;
};

let mut output = Output::from_args(args.output)?;
Expand Down

0 comments on commit 0a77622

Please sign in to comment.