From 6c9841534020eacc62aee5e450f57d1439db295e Mon Sep 17 00:00:00 2001 From: Yagiz Degirmenci <62724709+ycd@users.noreply.github.com> Date: Sun, 21 Mar 2021 23:27:44 +0300 Subject: [PATCH] fix(head): check the whether file exists before unwrap (#1858) closes https://github.com/uutils/coreutils/issues/1800 --- src/uu/head/src/head.rs | 7 +++++++ tests/by-util/test_head.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/uu/head/src/head.rs b/src/uu/head/src/head.rs index ae5807c22..0036dbba9 100644 --- a/src/uu/head/src/head.rs +++ b/src/uu/head/src/head.rs @@ -149,6 +149,13 @@ pub fn uumain(args: impl uucore::Args) -> i32 { first_time = false; let path = Path::new(file); + if path.is_dir() || !path.metadata().is_ok() { + eprintln!( + "cannot open '{}' for reading: No such file or directory", + &path.to_str().unwrap() + ); + continue; + } let reader = File::open(&path).unwrap(); let mut buffer = BufReader::new(reader); if !head(&mut buffer, &settings) { diff --git a/tests/by-util/test_head.rs b/tests/by-util/test_head.rs index eec82b51f..a1086c004 100644 --- a/tests/by-util/test_head.rs +++ b/tests/by-util/test_head.rs @@ -167,3 +167,15 @@ fn test_bug_in_negative_zero_lines() { //GNU Head returns "a\nb\n" .stdout_is(""); } + +#[test] +fn test_no_such_file_or_directory() { + let result = new_ucmd!().arg("no_such_file.toml").run(); + + assert_eq!( + true, + result + .stderr + .contains("cannot open 'no_such_file.toml' for reading: No such file or directory") + ) +}