From 1031b9cd4411c13fdafd5b4537ed4ad393dcf1cc Mon Sep 17 00:00:00 2001 From: Froloket64 Date: Sun, 28 Jun 2026 19:00:27 +0300 Subject: [PATCH 1/2] grep: make '-o' override context arguments --- src/lib.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 690953e..6b9a25e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -316,11 +316,17 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { _ => ColorMode::Auto, }; let (before_context, after_context, has_context) = { - let fallback = context.unwrap_or(0); - let before = before_context.unwrap_or(fallback); - let after = after_context.unwrap_or(fallback); - let has = context.is_some() || before_context.is_some() || after_context.is_some(); - (before, after, has) + // "-o" overrides any context arguments + if only_matching { + (0, 0, false) + } else { + let fallback = context.unwrap_or(0); + let before = before_context.unwrap_or(fallback); + let after = after_context.unwrap_or(fallback); + let has = context.is_some() || before_context.is_some() || after_context.is_some(); + + (before, after, has) + } }; let include_globs = { let mut patterns = GlobSet::with_capacity(include.len()); From bfd2a8770d07f740b70fbcc9f0968d0cd84f5c09 Mon Sep 17 00:00:00 2001 From: Froloket64 Date: Sun, 28 Jun 2026 20:17:02 +0300 Subject: [PATCH 2/2] test: cover -o with context arguments --- tests/test_grep.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/test_grep.rs b/tests/test_grep.rs index d612a40..a517b44 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -1696,3 +1696,34 @@ fn fast_path_binary_detected_after_a_printed_line() { .stdout_is("hit\n") .stderr_contains("binary file matches"); } + +#[test] +fn only_matching_with_context() { + // `only_matching` should override any context arguments. + let input = "aa\nbb\ncc\nxx\n"; + + let (_s, mut c) = ucmd(); + c.args(&["aa", "-o", "-A", "2"]) + .pipe_in(input) + .succeeds() + .stdout_only("aa\n"); + + let (_s, mut c) = ucmd(); + c.args(&["xx", "-o", "-B", "2"]) + .pipe_in("aa\nbb\ncc\nxx\n") + .succeeds() + .stdout_only("xx\n"); + + let (_s, mut c) = ucmd(); + c.args(&["cc", "-o", "-C", "2"]) + .pipe_in("aa\nbb\ncc\nxx\n") + .succeeds() + .stdout_only("cc\n"); + + // With line numbers. + let (_s, mut c) = ucmd(); + c.args(&["xx", "-o", "-C", "2", "-n"]) + .pipe_in("aa\nbb\ncc\nxx\n") + .succeeds() + .stdout_only("4:xx\n"); +}