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
This commit is contained in:
Alvaro Guimaraes
2026-03-30 10:54:50 -04:00
committed by GitHub
parent f41a088522
commit d8688183ff
2 changed files with 17 additions and 2 deletions
+9 -2
View File
@@ -13,10 +13,10 @@ use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
use std::num::TryFromIntError;
#[cfg(unix)]
use std::os::fd::AsFd;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use thiserror::Error;
use uucore::display::{Quotable, print_verbatim};
use uucore::error::{FromIo, UError, UResult};
use uucore::error::{FromIo, UError, UResult, USimpleError};
use uucore::line_ending::LineEnding;
use uucore::translate;
use uucore::{format_usage, show};
@@ -510,6 +510,13 @@ fn uu_head(options: &HeadOptions) -> UResult<()> {
Ok(())
} else {
if Path::new(file).is_dir() {
show!(USimpleError::new(
1,
translate!("head-error-reading-file", "name" => file.quote(), "err" => "Is a directory")
));
continue;
}
let mut file_handle = match File::open(file) {
Ok(f) => f,
Err(err) => {
+8
View File
@@ -911,3 +911,11 @@ fn test_head_non_utf8_paths() {
assert!(output.contains("line3"));
}
// Test that head handles non-UTF-8 file names without crashing
#[test]
fn test_do_not_attempt_to_read_a_directory() {
new_ucmd!()
.arg(".")
.fails_with_code(1)
.stderr_contains("error reading '.'");
}