Skip to content

Commit d868818

Browse files
authored
head: fix error message when input is a directory (#11541)
* head: fix error message when input is a directory * head: check for directory before trying to open
1 parent f41a088 commit d868818

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/uu/head/src/head.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
1313
use std::num::TryFromIntError;
1414
#[cfg(unix)]
1515
use std::os::fd::AsFd;
16-
use std::path::PathBuf;
16+
use std::path::{Path, PathBuf};
1717
use thiserror::Error;
1818
use uucore::display::{Quotable, print_verbatim};
19-
use uucore::error::{FromIo, UError, UResult};
19+
use uucore::error::{FromIo, UError, UResult, USimpleError};
2020
use uucore::line_ending::LineEnding;
2121
use uucore::translate;
2222
use uucore::{format_usage, show};
@@ -510,6 +510,13 @@ fn uu_head(options: &HeadOptions) -> UResult<()> {
510510

511511
Ok(())
512512
} else {
513+
if Path::new(file).is_dir() {
514+
show!(USimpleError::new(
515+
1,
516+
translate!("head-error-reading-file", "name" => file.quote(), "err" => "Is a directory")
517+
));
518+
continue;
519+
}
513520
let mut file_handle = match File::open(file) {
514521
Ok(f) => f,
515522
Err(err) => {

tests/by-util/test_head.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -911,3 +911,11 @@ fn test_head_non_utf8_paths() {
911911
assert!(output.contains("line3"));
912912
}
913913
// Test that head handles non-UTF-8 file names without crashing
914+
915+
#[test]
916+
fn test_do_not_attempt_to_read_a_directory() {
917+
new_ucmd!()
918+
.arg(".")
919+
.fails_with_code(1)
920+
.stderr_contains("error reading '.'");
921+
}

0 commit comments

Comments
 (0)