Skip to content

Commit

Permalink
cli: don't let context flags override eachother
Browse files Browse the repository at this point in the history
Match the behavior of GNU grep which does not ignore before-context and
after-context completely if the context flag is also provided.

Fixes BurntSushi#2288
  • Loading branch information
r2p2 committed Mar 13, 2023
1 parent 44fb9fc commit 37470e6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
17 changes: 6 additions & 11 deletions crates/core/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -698,16 +698,15 @@ fn flag_after_context(args: &mut Vec<RGArg>) {
"\
Show NUM lines after each match.
This overrides the --context and --passthru flags.
This overrides the --passthru flag.
"
);
let arg = RGArg::flag("after-context", "NUM")
.short("A")
.help(SHORT)
.long_help(LONG)
.number()
.overrides("passthru")
.overrides("context");
.overrides("passthru");
args.push(arg);
}

Expand Down Expand Up @@ -768,16 +767,15 @@ fn flag_before_context(args: &mut Vec<RGArg>) {
"\
Show NUM lines before each match.
This overrides the --context and --passthru flags.
This overrides the --passthru flag.
"
);
let arg = RGArg::flag("before-context", "NUM")
.short("B")
.help(SHORT)
.long_help(LONG)
.number()
.overrides("passthru")
.overrides("context");
.overrides("passthru");
args.push(arg);
}

Expand Down Expand Up @@ -1009,18 +1007,15 @@ fn flag_context(args: &mut Vec<RGArg>) {
Show NUM lines before and after each match. This is equivalent to providing
both the -B/--before-context and -A/--after-context flags with the same value.
This overrides both the -B/--before-context and -A/--after-context flags,
in addition to the --passthru flag.
This overrides the --passthru flag.
"
);
let arg = RGArg::flag("context", "NUM")
.short("C")
.help(SHORT)
.long_help(LONG)
.number()
.overrides("passthru")
.overrides("before-context")
.overrides("after-context");
.overrides("passthru");
args.push(arg);
}

Expand Down
6 changes: 3 additions & 3 deletions crates/core/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,10 +1020,10 @@ impl ArgMatches {
/// If there was a problem parsing the values from the user as an integer,
/// then an error is returned.
fn contexts(&self) -> Result<(usize, usize)> {
let after = self.usize_of("after-context")?.unwrap_or(0);
let before = self.usize_of("before-context")?.unwrap_or(0);
let both = self.usize_of("context")?.unwrap_or(0);
Ok(if both > 0 { (both, both) } else { (before, after) })
let after = self.usize_of("after-context")?.unwrap_or(both);
let before = self.usize_of("before-context")?.unwrap_or(both);
Ok((before, after))
}

/// Returns the unescaped context separator in UTF-8 bytes.
Expand Down

0 comments on commit 37470e6

Please sign in to comment.