Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
31 changes: 31 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Loading