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()); 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"); +}