From e8d911d9d5ccf1c92d53a02ed8cc8fc729950b36 Mon Sep 17 00:00:00 2001 From: Jeffrey Finkelstein Date: Sat, 15 May 2021 10:32:03 -0400 Subject: [PATCH] wc: correct some error messages for invalid inputs Change the error messages that get printed to `stderr` for compatibility with GNU `wc` when an input is a directory and when an input does not exist. Fixes #2211. --- src/uu/wc/src/wc.rs | 27 +++++++++++++++++++++++++-- tests/by-util/test_wc.rs | 23 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index 226608d40..5670508f4 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -22,7 +22,7 @@ use thiserror::Error; use std::cmp::max; use std::fs::File; -use std::io::{self, Write}; +use std::io::{self, ErrorKind, Write}; use std::path::Path; #[derive(Error, Debug)] @@ -254,6 +254,29 @@ fn word_count_from_input(input: &Input, settings: &Settings) -> WcResult { + show_error_custom_description!(path, "Is a directory"); + } + (Input::Path(path), WcError::Io(e)) if e.kind() == ErrorKind::NotFound => { + show_error_custom_description!(path, "No such file or directory"); + } + (_, e) => { + show_error!("{}", e); + } + }; +} + fn wc(inputs: Vec, settings: &Settings) -> Result<(), u32> { let mut total_word_count = WordCount::default(); let mut results = vec![]; @@ -264,7 +287,7 @@ fn wc(inputs: Vec, settings: &Settings) -> Result<(), u32> { for input in &inputs { let word_count = word_count_from_input(&input, settings).unwrap_or_else(|err| { - show_error!("{}", err); + show_error(&input, err); error_count += 1; WordCount::default() }); diff --git a/tests/by-util/test_wc.rs b/tests/by-util/test_wc.rs index b61d7e3aa..8036d0eaa 100644 --- a/tests/by-util/test_wc.rs +++ b/tests/by-util/test_wc.rs @@ -168,3 +168,26 @@ fn test_file_one_long_word() { .run() .stdout_is(" 1 1 10001 10001 10000 onelongword.txt\n"); } + +/// Test that getting counts from a directory is an error. +#[test] +fn test_read_from_directory_error() { + // TODO To match GNU `wc`, the `stdout` should be: + // + // " 0 0 0 .\n" + // + new_ucmd!() + .args(&["."]) + .fails() + .stderr_contains(".: Is a directory\n") + .stdout_is("0 0 0 .\n"); +} + +/// Test that getting counts from nonexistent file is an error. +#[test] +fn test_read_from_nonexistent_file() { + new_ucmd!() + .args(&["bogusfile"]) + .fails() + .stderr_contains("bogusfile: No such file or directory\n"); +}