diff --git a/src/uu/mcookie/src/mcookie.rs b/src/uu/mcookie/src/mcookie.rs index 29b008e..843f05b 100644 --- a/src/uu/mcookie/src/mcookie.rs +++ b/src/uu/mcookie/src/mcookie.rs @@ -70,7 +70,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { } } else { input_name = file_path; - let mut f = File::open(file_path)?; + let open_result = File::open(file_path); + if let Err(err) = open_result { + eprintln!("mcookie: cannot open {file_path}: {err}"); + continue; + } + + let mut f = open_result.unwrap(); if let Some(max_bytes) = &max_size { let mut limited_reader = f.take(*max_bytes); limited_reader.read_to_end(&mut buffer)?; diff --git a/tests/by-util/test_mcookie.rs b/tests/by-util/test_mcookie.rs index 6d38f87..5260340 100644 --- a/tests/by-util/test_mcookie.rs +++ b/tests/by-util/test_mcookie.rs @@ -140,3 +140,40 @@ fn test_stdin_input() { assert_eq!(stdout.len(), 32); assert!(stdout.chars().all(|c| c.is_ascii_hexdigit())); } + +#[test] +fn test_not_existing_file() { + let mut file1 = NamedTempFile::new().unwrap(); + const CONTENT1: &str = "Some seed data"; + file1.write_all(CONTENT1.as_bytes()).unwrap(); + + let file_not_existing = file1.path().to_str().unwrap().to_owned() + "_extra"; + + let mut file2 = NamedTempFile::new().unwrap(); + const CONTENT2: [u8; 2048] = [1; 2048]; + file2.write_all(&CONTENT2).unwrap(); + + let res = new_ucmd!() + .arg("--verbose") + .arg("-f") + .arg(file1.path()) + .arg("-f") + .arg(&file_not_existing) + .arg("-f") + .arg(file2.path()) + .succeeds(); + + res.stderr_contains(format!( + "Got {} bytes from {}", + CONTENT1.len(), + file1.path().to_str().unwrap() + )); + + res.stderr_contains(format!("mcookie: cannot open {}", file_not_existing)); + + // Ensure we only read up to the limit of bytes, despite the file being bigger + res.stderr_contains(format!( + "Got 2048 bytes from {}", + file2.path().to_str().unwrap() + )); +}