From 7c79cb4e3ad355d74995517aebeb17b28836dda0 Mon Sep 17 00:00:00 2001 From: Wondr Date: Fri, 5 Jun 2026 15:06:49 +0100 Subject: [PATCH] grep: keep invalid UTF-8 text under -I (#49) --- src/searcher.rs | 4 +++- tests/test_grep.rs | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/searcher.rs b/src/searcher.rs index 5da5936..68e2f97 100644 --- a/src/searcher.rs +++ b/src/searcher.rs @@ -493,7 +493,9 @@ impl<'a> Searcher<'a> { if let Some(positions) = self.session_match_line(line) { // TODO: GNU grep respects LANG. Here, I'm always checking for valid UTF-8. - if !self.session_mark_binary_if(|| std::str::from_utf8(line).is_err()) { + if self.config.binary_mode != BinaryMode::WithoutMatch + && !self.session_mark_binary_if(|| std::str::from_utf8(line).is_err()) + { return Ok(false); } diff --git a/tests/test_grep.rs b/tests/test_grep.rs index 2c16db4..20b3f83 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -939,6 +939,7 @@ fn binary_files_text_forces_text_mode() { fn binary_files_without_match_skips() { let (scene, _) = ucmd(); scene.fixtures.write_bytes("b", b"hit\0more\n"); + scene.fixtures.write_bytes("invalid", b"a\x9db\n"); let mut c = scene.cmd(env!("CARGO_BIN_EXE_grep")); c.args(&["-I", "hit", "b"]).fails_with_code(1).no_output(); @@ -947,6 +948,18 @@ fn binary_files_without_match_skips() { c.args(&["--binary-files=without-match", "hit", "b"]) .fails_with_code(1) .no_output(); + + let mut c = scene.cmd(env!("CARGO_BIN_EXE_grep")); + c.args(&["-I", "a", "invalid"]) + .succeeds() + .stdout_is_bytes(b"a\x9db\n") + .no_stderr(); + + let mut c = scene.cmd(env!("CARGO_BIN_EXE_grep")); + c.args(&["--binary-files=without-match", "a", "invalid"]) + .succeeds() + .stdout_is_bytes(b"a\x9db\n") + .no_stderr(); } fn build_tree(scene: &TestScenario) {