searcher: move "max matches" from printer to searcher
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This is a bit of a brutal change, but I believe is necessary in order to fix a bug in how we handle the "max matches" limit in multi-line mode while simultaneously handling context lines correctly. The main problem here is that "max matches" refers to the shorter of "one match per line" or "a single match." In typical grep, matches *can't* span multiple lines, so there's never a difference. But in multi-line mode, they can. So match counts necessarily must be handled differently for multi-line mode. The printer was previously responsible for this. But for $reasons, the printer is fundamentally not in charge of how matches are found and reported. See my comments in #3094 for even more context. This is a breaking change for `grep-printer`. Fixes #3076, Closes #3094
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+310 added−121 removed
- tests:+1 added−0 removed
- other:+309 added−121 removed
Provenance
- Commit
a6e0be3- Tree
a68606e- Author
Pavel Safronov <pv.safronov@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
a60e62d
8 files changed+310 added−121 removed
modified:crates/core/flags/defs.rs+4 added
3875 unmodified lines3876 fn doc_long(&self) -> &'static str {3877 r"3878 Limit the number of matching lines per file searched to \fINUM\fP.3879 .sp3880+When \flag{multiline} is used, a single match that spans multiple lines is only3881+counted once for the purposes of this limit. Multiple matches in a single line3882+are counted only once, as they would be in non-multiline mode.3883+.sp3884 Note that \fB0\fP is a legal value but not likely to be useful. When used,3885 ripgrep won't search anything.3886 "3887 }3865 unmodified linesmodified:crates/core/flags/hiargs.rs+1 added-1 removed
615 unmodified lines616 .heading(self.heading)617 .hyperlink(self.hyperlink_config.clone())618 .max_columns_preview(self.max_columns_preview)619 .max_columns(self.max_columns)620- .max_matches(self.max_count)620 .only_matching(self.only_matching)621 .path(self.with_filename)622 .path_terminator(self.path_terminator.clone())623 .per_match_one_line(true)93 unmodified lines717 grep::matcher::LineTerminator::byte(b'\n')718 };719 let mut builder = grep::searcher::SearcherBuilder::new();720 builder721+ .max_matches(self.max_count)722 .line_terminator(line_term)723 .invert_match(self.invert_match)724 .line_number(self.line_number)725 .multi_line(self.multiline)756 unmodified linesmodified:crates/printer/src/standard.rs+173 added-91 removed
9 unmodified lines10 use {11 bstr::ByteSlice,12 grep_matcher::{Match, Matcher},13 grep_searcher::{14- LineStep, Searcher, Sink, SinkContext, SinkContextKind, SinkFinish,15- SinkMatch,14+ LineStep, Searcher, Sink, SinkContext, SinkFinish, SinkMatch,15 },16 termcolor::{ColorSpec, NoColor, WriteColor},17 };18 25 unmodified lines44 per_match_one_line: bool,45 replacement: Arc<Option<Vec<u8>>>,46 max_columns: Option<u64>,47 max_columns_preview: bool,49- max_matches: Option<u64>,48 column: bool,49 byte_offset: bool,50 trim_ascii: bool,51 separator_search: Arc<Option<Vec<u8>>>,17 unmodified lines69 per_match_one_line: false,70 replacement: Arc::new(None),71 max_columns: None,72 max_columns_preview: false,75- max_matches: None,73 column: false,74 byte_offset: false,75 trim_ascii: false,76 separator_search: Arc::new(None),245 unmodified lines322 self.config.max_columns_preview = yes;323 self324 }325 329- /// Set the maximum amount of matching lines that are printed.330- ///331- /// If multi line search is enabled and a match spans multiple lines, then332- /// that match is counted exactly once for the purposes of enforcing this333- /// limit, regardless of how many lines it spans.334- pub fn max_matches(&mut self, limit: Option<u64>) -> &mut StandardBuilder {335- self.config.max_matches = limit;336- self337- }338-326 /// Print the column number of the first match in a line.327 ///328 /// This option is convenient for use with `per_match` which will print a329 /// line for every match along with the starting offset for that match.197 unmodified lines527 interpolator,528 path: None,529 start_time: Instant::now(),530 match_count: 0,544- after_context_remaining: 0,531 binary_byte_offset: None,532 stats,533 needs_match_granularity,534 }28 unmodified lines563 interpolator,564 path: Some(ppath),565 start_time: Instant::now(),566 match_count: 0,581- after_context_remaining: 0,567 binary_byte_offset: None,568 stats,569 needs_match_granularity,570 }72 unmodified lines643 interpolator: hyperlink::Interpolator,644 path: Option<PrinterPath<'p>>,645 start_time: Instant,646 match_count: u64,662- after_context_remaining: u64,647 binary_byte_offset: Option<u64>,648 stats: Option<Stats>,649 needs_match_granularity: bool,650 }106 unmodified lines757 )?;758 }759 Ok(())760 }777-778- /// Returns true if this printer should quit.779- ///780- /// This implements the logic for handling quitting after seeing a certain781- /// amount of matches. In most cases, the logic is simple, but we must782- /// permit all "after" contextual lines to print after reaching the limit.783- fn should_quit(&self) -> bool {784- let limit = match self.standard.config.max_matches {785- None => return false,786- Some(limit) => limit,787- };788- if self.match_count < limit {789- return false;790- }791- self.after_context_remaining == 0792- }793-794- /// Returns whether the current match count exceeds the configured limit.795- /// If there is no limit, then this always returns false.796- fn match_more_than_limit(&self) -> bool {797- let limit = match self.standard.config.max_matches {798- None => return false,799- Some(limit) => limit,800- };801- self.match_count > limit802- }761 }762 763 impl<'p, 's, M: Matcher, W: WriteColor> Sink for StandardSink<'p, 's, M, W> {764 type Error = io::Error;3 unmodified lines768 searcher: &Searcher,769 mat: &SinkMatch<'_>,770 ) -> Result<bool, io::Error> {771 self.match_count += 1;814- // When we've exceeded our match count, then the remaining context815- // lines should not be reset, but instead, decremented. This avoids a816- // bug where we display more matches than a configured limit. The main817- // idea here is that 'matched' might be called again while printing818- // an after-context line. In that case, we should treat this as a819- // contextual line rather than a matching line for the purposes of820- // termination.821- if self.match_more_than_limit() {822- self.after_context_remaining =823- self.after_context_remaining.saturating_sub(1);824- } else {825- self.after_context_remaining = searcher.after_context() as u64;826- }772 773 self.record_matches(774 searcher,775 mat.buffer(),9 unmodified lines785 if self.binary_byte_offset.is_some() {786 return Ok(false);787 }788 }844-789 StandardImpl::from_match(searcher, self, mat).sink()?;846- Ok(!self.should_quit())790+ Ok(true)791 }792 793 fn context(794 &mut self,2 unmodified lines797 ) -> Result<bool, io::Error> {798 self.standard.matches.clear();799 self.replacer.clear();800 857- if ctx.kind() == &SinkContextKind::After {858- self.after_context_remaining =859- self.after_context_remaining.saturating_sub(1);860- }801 if searcher.invert_match() {802 self.record_matches(searcher, ctx.bytes(), 0..ctx.bytes().len())?;803 self.replace(searcher, ctx.bytes(), 0..ctx.bytes().len())?;804 }3 unmodified lines808 }809 }810 811 StandardImpl::from_context(searcher, self, ctx).sink()?;872- Ok(!self.should_quit())812+ Ok(true)813 }814 815 fn context_break(816 &mut self,24 unmodified lines841 fn begin(&mut self, _searcher: &Searcher) -> Result<bool, io::Error> {842 self.standard.wtr.borrow_mut().reset_count();843 self.start_time = Instant::now();844 self.match_count = 0;905- self.after_context_remaining = 0;845 self.binary_byte_offset = None;907- if self.standard.config.max_matches == Some(0) {908- return Ok(false);909- }846 Ok(true)847 }848 849 fn finish(535 unmodified lines1385 Ok(())1386 }1387 1388 fn write_binary_message(&self, offset: u64) -> io::Result<()> {1453- if self.sink.match_count == 0 {1389+ if !self.sink.has_match() {1390 return Ok(());1391 }1392 1393 let bin = self.searcher.binary_detection();1283 unmodified lines2677 2678 #[test]2679 fn max_matches() {2680 let matcher = RegexMatcher::new("Sherlock").unwrap();2745- let mut printer = StandardBuilder::new()2746- .max_matches(Some(1))2747- .build(NoColor::new(vec![]));2681+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2682 SearcherBuilder::new()2683 .line_number(false)2684+ .max_matches(Some(1))2685 .build()2686 .search_reader(2687 &matcher,2688 SHERLOCK.as_bytes(),11 unmodified lines2700 #[test]2701 fn max_matches_context() {2702 // after context: 12703 let matcher = RegexMatcher::new("Doctor Watsons").unwrap();2769- let mut printer = StandardBuilder::new()2770- .max_matches(Some(1))2771- .build(NoColor::new(vec![]));2704+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2705 SearcherBuilder::new()2706+ .max_matches(Some(1))2707 .line_number(false)2708 .after_context(1)2709 .build()2710 .search_reader(10 unmodified lines2721 ";2722 assert_eq_printed!(expected, got);2723 2724 // after context: 42791- let mut printer = StandardBuilder::new()2792- .max_matches(Some(1))2793- .build(NoColor::new(vec![]));2725+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2726 SearcherBuilder::new()2727+ .max_matches(Some(1))2728 .line_number(false)2729 .after_context(4)2730 .build()2731 .search_reader(14 unmodified lines2746 assert_eq_printed!(expected, got);2747 2748 // after context: 1, max matches: 22749 let matcher = RegexMatcher::new("Doctor Watsons|but Doctor").unwrap();2817- let mut printer = StandardBuilder::new()2818- .max_matches(Some(2))2819- .build(NoColor::new(vec![]));2750+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2751 SearcherBuilder::new()2752+ .max_matches(Some(2))2753 .line_number(false)2754 .after_context(1)2755 .build()2756 .search_reader(13 unmodified lines2770 ";2771 assert_eq_printed!(expected, got);2772 2773 // after context: 4, max matches: 22842- let mut printer = StandardBuilder::new()2774+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2775+ SearcherBuilder::new()2776 .max_matches(Some(2))2844- .build(NoColor::new(vec![]));2777+ .line_number(false)2778+ .after_context(4)2779+ .build()2780+ .search_reader(2781+ &matcher,2782+ SHERLOCK.as_bytes(),2783+ printer.sink(&matcher),2784+ )2785+ .unwrap();2786+2787+ let got = printer_contents(&mut printer);2788+ let expected = "\2789+For the Doctor Watsons of this world, as opposed to the Sherlock2790+Holmeses, success in the province of detective work must always2791+be, to a very large extent, the result of luck. Sherlock Holmes2792+can extract a clew from a wisp of straw or a flake of cigar ash;2793+but Doctor Watson has to have it taken out for him and dusted,2794+and exhibited clearly, with a label attached.2795+";2796+ assert_eq_printed!(expected, got);2797+ }2798+2799+ #[test]2800+ fn max_matches_context_invert() {2801+ // after context: 12802+ let matcher =2803+ RegexMatcher::new("success|extent|clew|dusted|exhibited").unwrap();2804+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2805 SearcherBuilder::new()2806+ .invert_match(true)2807+ .max_matches(Some(1))2808 .line_number(false)2809+ .after_context(1)2810+ .build()2811+ .search_reader(2812+ &matcher,2813+ SHERLOCK.as_bytes(),2814+ printer.sink(&matcher),2815+ )2816+ .unwrap();2817+2818+ let got = printer_contents(&mut printer);2819+ let expected = "\2820+For the Doctor Watsons of this world, as opposed to the Sherlock2821+Holmeses, success in the province of detective work must always2822+";2823+ assert_eq_printed!(expected, got);2824+2825+ // after context: 42826+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2827+ SearcherBuilder::new()2828+ .invert_match(true)2829+ .max_matches(Some(1))2830+ .line_number(false)2831 .after_context(4)2832 .build()2833 .search_reader(2834 &matcher,8 unmodified lines2843 Holmeses, success in the province of detective work must always2844 be, to a very large extent, the result of luck. Sherlock Holmes2845 can extract a clew from a wisp of straw or a flake of cigar ash;2846 but Doctor Watson has to have it taken out for him and dusted,2847+";2848+ assert_eq_printed!(expected, got);2849+2850+ // after context: 1, max matches: 22851+ let matcher =2852+ RegexMatcher::new("success|extent|clew|exhibited").unwrap();2853+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2854+ SearcherBuilder::new()2855+ .invert_match(true)2856+ .max_matches(Some(2))2857+ .line_number(false)2858+ .after_context(1)2859+ .build()2860+ .search_reader(2861+ &matcher,2862+ SHERLOCK.as_bytes(),2863+ printer.sink(&matcher),2864+ )2865+ .unwrap();2866+2867+ let got = printer_contents(&mut printer);2868+ let expected = "\2869+For the Doctor Watsons of this world, as opposed to the Sherlock2870+Holmeses, success in the province of detective work must always2871+--2872+but Doctor Watson has to have it taken out for him and dusted,2873 and exhibited clearly, with a label attached.2874 ";2875 assert_eq_printed!(expected, got);2876+2877+ // after context: 4, max matches: 22878+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2879+ SearcherBuilder::new()2880+ .invert_match(true)2881+ .max_matches(Some(2))2882+ .line_number(false)2883+ .after_context(4)2884+ .build()2885+ .search_reader(2886+ &matcher,2887+ SHERLOCK.as_bytes(),2888+ printer.sink(&matcher),2889+ )2890+ .unwrap();2891+2892+ let got = printer_contents(&mut printer);2893+ let expected = "\2894+For the Doctor Watsons of this world, as opposed to the Sherlock2895+Holmeses, success in the province of detective work must always2896+be, to a very large extent, the result of luck. Sherlock Holmes2897+can extract a clew from a wisp of straw or a flake of cigar ash;2898+but Doctor Watson has to have it taken out for him and dusted,2899+and exhibited clearly, with a label attached.2900+";2901+ assert_eq_printed!(expected, got);2902 }2903 2904 #[test]2905 fn max_matches_multi_line1() {2906 let matcher = RegexMatcher::new("(?s:.{0})Sherlock").unwrap();2871- let mut printer = StandardBuilder::new()2872- .max_matches(Some(1))2873- .build(NoColor::new(vec![]));2907+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2908 SearcherBuilder::new()2909 .line_number(false)2910 .multi_line(true)2911+ .max_matches(Some(1))2912 .build()2913 .search_reader(2914 &matcher,2915 SHERLOCK.as_bytes(),11 unmodified lines2927 #[test]2928 fn max_matches_multi_line2() {2929 let matcher =2930 RegexMatcher::new(r"(?s)Watson.+?(Holmeses|clearly)").unwrap();2896- let mut printer = StandardBuilder::new()2897- .max_matches(Some(1))2898- .build(NoColor::new(vec![]));2931+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2932 SearcherBuilder::new()2933 .line_number(false)2934 .multi_line(true)2935+ .max_matches(Some(1))2936 .build()2937 .search_reader(2938 &matcher,2939 SHERLOCK.as_bytes(),9 unmodified lines2949 assert_eq_printed!(expected, got);2950 }2951 2952 #[test]2953+ fn max_matches_multi_line3() {2954+ let matcher = RegexMatcher::new(r"line 2\nline 3").unwrap();2955+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2956+ SearcherBuilder::new()2957+ .line_number(false)2958+ .multi_line(true)2959+ .max_matches(Some(1))2960+ .build()2961+ .search_reader(2962+ &matcher,2963+ "line 2\nline 3 x\nline 2\nline 3\n".as_bytes(),2964+ printer.sink(&matcher),2965+ )2966+ .unwrap();2967+2968+ let got = printer_contents(&mut printer);2969+ let expected = "\2970+line 22971+line 3 x2972+";2973+ assert_eq_printed!(expected, got);2974+ }2975+2976+ #[test]2977+ fn max_matches_multi_line4() {2978+ let matcher =2979+ RegexMatcher::new(r"line 2\nline 3|x\nline 2\n").unwrap();2980+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));2981+ SearcherBuilder::new()2982+ .line_number(false)2983+ .multi_line(true)2984+ .max_matches(Some(1))2985+ .build()2986+ .search_reader(2987+ &matcher,2988+ "line 2\nline 3 x\nline 2\nline 3 x\n".as_bytes(),2989+ printer.sink(&matcher),2990+ )2991+ .unwrap();2992+2993+ let got = printer_contents(&mut printer);2994+ let expected = "\2995+line 22996+line 3 x2997+";2998+ assert_eq_printed!(expected, got);2999+ }3000+3001+ #[test]3002 fn only_matching() {3003 let matcher = RegexMatcher::new("Doctor Watsons|Sherlock").unwrap();3004 let mut printer = StandardBuilder::new()3005 .only_matching(true)923 unmodified lines3929 e3930 ";3931 3932 let matcher = RegexMatcherBuilder::new().build(r"d").unwrap();3850- let mut printer = StandardBuilder::new()3851- .max_matches(Some(1))3852- .build(NoColor::new(vec![]));3933+ let mut printer = StandardBuilder::new().build(NoColor::new(vec![]));3934 SearcherBuilder::new()3935+ .max_matches(Some(1))3936 .line_number(true)3937 .after_context(2)3938 .build()3939 .search_reader(11 unmodified linesmodified:crates/searcher/src/searcher/core.rs+91 added-23 removed
31 unmodified lines32 last_line_visited: usize,33 after_context_left: usize,34 has_sunk: bool,35 has_matched: bool,36+ count: u64,37 }38 39 impl<'s, M: Matcher, S: Sink> Core<'s, M, S> {40 pub(crate) fn new(18 unmodified lines59 last_line_visited: 0,60 after_context_left: 0,61 has_sunk: false,62 has_matched: false,63+ count: 0,64 };65 if !core.searcher.multi_line_with_matcher(&core.matcher) {66 if core.is_line_by_line_fast() {67 log::trace!("searcher core: will use fast line searcher");11 unmodified lines79 pub(crate) fn set_pos(&mut self, pos: usize) {80 self.pos = pos;81 }82 83+ fn count(&self) -> u64 {84+ self.count85+ }86+87+ fn increment_count(&mut self) {88+ self.count += 1;89+ }90+91 pub(crate) fn binary_byte_offset(&self) -> Option<u64> {92 self.binary_byte_offset.map(|offset| offset as u64)93 }94 15 unmodified lines110 ) -> Result<bool, S::Error> {111 self.sink.binary_data(&self.searcher, binary_byte_offset)112 }113 114+ fn is_match(&self, line: &[u8]) -> Result<bool, S::Error> {115+ // We need to strip the line terminator here to match the116+ // semantics of line-by-line searching. Namely, regexes117+ // like `(?m)^$` can match at the final position beyond a118+ // line terminator, which is non-sensical in line oriented119+ // matching.120+ let line = lines::without_terminator(line, self.config.line_term);121+ self.matcher.is_match(line).map_err(S::Error::error_message)122+ }123+124+ pub(crate) fn find(125+ &mut self,126+ slice: &[u8],127+ ) -> Result<Option<Range>, S::Error> {128+ if self.has_exceeded_match_limit() {129+ return Ok(None);130+ }131+ match self.matcher().find(slice) {132+ Err(err) => Err(S::Error::error_message(err)),133+ Ok(None) => Ok(None),134+ Ok(Some(m)) => {135+ self.increment_count();136+ Ok(Some(m))137+ }138+ }139+ }140+141+ fn shortest_match(142+ &mut self,143+ slice: &[u8],144+ ) -> Result<Option<usize>, S::Error> {145+ if self.has_exceeded_match_limit() {146+ return Ok(None);147+ }148+ match self.matcher.shortest_match(slice) {149+ Err(err) => return Err(S::Error::error_message(err)),150+ Ok(None) => return Ok(None),151+ Ok(Some(m)) => Ok(Some(m)),152+ }153+ }154+155 pub(crate) fn begin(&mut self) -> Result<bool, S::Error> {156 self.sink.begin(&self.searcher)157 }158 117 unmodified lines276 ) -> Result<bool, S::Error> {277 if self.after_context_left == 0 {278 return Ok(true);279 }280+ let exceeded_match_limit = self.has_exceeded_match_limit();281 let range = Range::new(self.last_line_visited, upto);282 let mut stepper = LineStep::new(283 self.config.line_term.as_byte(),284 range.start(),285 range.end(),286 );287 while let Some(line) = stepper.next_match(buf) {288+ if exceeded_match_limit289+ && self.is_match(&buf[line])? != self.config.invert_match290+ {291+ let after_context_left = self.after_context_left;292+ self.set_pos(line.end());293+ if !self.sink_matched(buf, &line)? {294+ return Ok(false);295+ }296+ self.after_context_left = after_context_left - 1;236- if !self.sink_after_context(buf, &line)? {297+ } else if !self.sink_after_context(buf, &line)? {298 return Ok(false);299 }300 if self.after_context_left == 0 {301 break;30 unmodified lines332 range.start(),333 range.end(),334 );335 while let Some(line) = stepper.next_match(buf) {336+ if self.has_exceeded_match_limit()337+ && !self.config.passthru338+ && self.after_context_left == 0339+ {340+ return Ok(false);341+ }342 let matched = {343 // Stripping the line terminator is necessary to prevent some344 // classes of regexes from matching the empty position *after*345 // the end of the line. For example, `(?m)^$` will match at1 unmodified line347 let slice = lines::without_terminator(348 &buf[line],349 self.config.line_term,350 );284- match self.matcher.shortest_match(slice) {285- Err(err) => return Err(S::Error::error_message(err)),286- Ok(result) => result.is_some(),287- }351+ self.shortest_match(slice)?.is_some()352 };353 self.set_pos(line.end());354+355 let success = matched != self.config.invert_match;356 if success {357 self.has_matched = true;358+ self.increment_count();359 if !self.before_context_by_line(buf, line.start())? {360 return Ok(false);361 }362 if !self.sink_matched(buf, &line)? {27 unmodified lines390 return Ok(SwitchToSlow);391 }392 if self.config.invert_match {393 if !self.match_by_line_fast_invert(buf)? {328- return Ok(Stop);394+ break;395 }396 } else if let Some(line) = self.find_by_line_fast(buf)? {397 self.has_matched = true;398+ self.increment_count();399 if self.config.max_context() > 0 {400 if !self.after_context_by_line(buf, line.start())? {401 return Ok(Stop);402 }11 unmodified lines414 }415 if !self.after_context_by_line(buf, buf.len())? {416 return Ok(Stop);417 }418+ if self.has_exceeded_match_limit() && self.after_context_left == 0 {419+ return Ok(Stop);420+ }421 self.set_pos(buf.len());422 Ok(Continue)423 }424 31 unmodified lines456 invert_match.start(),457 invert_match.end(),458 );459 while let Some(line) = stepper.next_match(buf) {460+ self.increment_count();461 if !self.sink_matched(buf, &line)? {462 return Ok(false);463 }464+ if self.has_exceeded_match_limit() {465+ return Ok(false);466+ }467 }468 Ok(true)469 }470 471 #[inline(always)]472 fn find_by_line_fast(399- &self,473+ &mut self,474 buf: &[u8],475 ) -> Result<Option<Range>, S::Error> {476 debug_assert!(!self.searcher.multi_line_with_matcher(&self.matcher));477 debug_assert!(self.is_line_by_line_fast());478 479 let mut pos = self.pos();480 while !buf[pos..].is_empty() {481+ if self.has_exceeded_match_limit() {482+ return Ok(None);483+ }484 match self.matcher.find_candidate_line(&buf[pos..]) {485 Err(err) => return Err(S::Error::error_message(err)),486 Ok(None) => return Ok(None),487 Ok(Some(LineMatchKind::Confirmed(i))) => {15 unmodified lines503 buf,504 self.config.line_term.as_byte(),505 Range::zero(i).offset(pos),506 );430- // We need to strip the line terminator here to match the431- // semantics of line-by-line searching. Namely, regexes432- // like `(?m)^$` can match at the final position beyond a433- // line terminator, which is non-sensical in line oriented434- // matching.435- let slice = lines::without_terminator(436- &buf[line],437- self.config.line_term,438- );439- match self.matcher.is_match(slice) {440- Err(err) => return Err(S::Error::error_message(err)),441- Ok(true) => return Ok(Some(line)),442- Ok(false) => {443- pos = line.end();444- continue;445- }507+ if self.is_match(&buf[line])? {508+ return Ok(Some(line));509 }510+ pos = line.end();511 }512 }513 }514 Ok(None)186 unmodified lines701 }702 }703 false704 }705+706+ fn has_exceeded_match_limit(&self) -> bool {707+ self.config.max_matches.map_or(false, |limit| self.count() >= limit)708+ }709 }modified:crates/searcher/src/searcher/glue.rs+3 added-5 removed
323 unmodified lines324 Ok(true)325 }326 327 fn find(&mut self) -> Result<Option<Range>, S::Error> {328- match self.core.matcher().find(&self.slice[self.core.pos()..]) {329- Err(err) => Err(S::Error::error_message(err)),330- Ok(None) => Ok(None),331- Ok(Some(m)) => Ok(Some(m.offset(self.core.pos()))),332- }328+ self.core329+ .find(&self.slice[self.core.pos()..])330+ .map(|m| m.map(|m| m.offset(self.core.pos())))331 }332 333 /// Advance the search position based on the previous match.334 ///1215 unmodified linesmodified:crates/searcher/src/searcher/mod.rs+35 added-1 removed
178 unmodified lines179 bom_sniffing: bool,180 /// Whether to stop searching when a non-matching line is found after a181 /// matching line.182 stop_on_nonmatch: bool,183+ /// The maximum number of matches this searcher should emit.184+ max_matches: Option<u64>,185 }186 187 impl Default for Config {188 fn default() -> Config {10 unmodified lines199 multi_line: false,200 encoding: None,201 bom_sniffing: true,202 stop_on_nonmatch: false,203+ max_matches: None,204 }205 }206 }207 358 unmodified lines566 ) -> &mut SearcherBuilder {567 self.config.stop_on_nonmatch = stop_on_nonmatch;568 self569 }570+571+ /// Sets the maximum number of matches that should be emitted by this572+ /// searcher.573+ ///574+ /// If multi line search is enabled and a match spans multiple lines, then575+ /// that match is counted exactly once for the purposes of enforcing this576+ /// limit, regardless of how many lines it spans.577+ ///578+ /// Note that `0` is a legal value. This will cause the searcher to579+ /// immediately quick without searching anything.580+ ///581+ /// By default, no limit is set.582+ #[inline]583+ pub fn max_matches(&mut self, limit: Option<u64>) -> &mut SearcherBuilder {584+ self.config.max_matches = limit;585+ self586+ }587 }588 589 /// A searcher executes searches over a haystack and writes results to a caller590 /// provided sink.273 unmodified lines864 pub fn multi_line(&self) -> bool {865 self.config.multi_line866 }867 848- /// Returns true if and only if this searcher is configured to stop when in868+ /// Returns true if and only if this searcher is configured to stop when it869 /// finds a non-matching line after a matching one.870 #[inline]871 pub fn stop_on_nonmatch(&self) -> bool {872 self.config.stop_on_nonmatch873 }874 875+ /// Returns the maximum number of matches emitted by this searcher, if876+ /// such a limit was set.877+ ///878+ /// If multi line search is enabled and a match spans multiple lines, then879+ /// that match is counted exactly once for the purposes of enforcing this880+ /// limit, regardless of how many lines it spans.881+ ///882+ /// Note that `0` is a legal value. This will cause the searcher to883+ /// immediately quick without searching anything.884+ #[inline]885+ pub fn max_matches(&self) -> Option<u64> {886+ self.config.max_matches887+ }888+889 /// Returns true if and only if this searcher will choose a multi-line890 /// strategy given the provided matcher.891 ///892 /// This may diverge from the result of `multi_line` in cases where the196 unmodified linesmodified:tests/regression.rs+1 added
1457 unmodified lines1458 // See: https://github.com/BurntSushi/ripgrep/pull/29441459 rgtest!(r2944_incorrect_bytes_searched, |dir: Dir, mut cmd: TestCommand| {1460 dir.create("haystack", "foo1\nfoo2\nfoo3\nfoo4\nfoo5\n");1461 let got = cmd.args(&["--stats", "-m2", "foo", "."]).stdout();1462+ println!("{got}");1463 assert!(got.contains("10 bytes searched\n"));1464 });1465 1466 // See: https://github.com/BurntSushi/ripgrep/issues/299055 unmodified linesmodified:CHANGELOG.md+2 added
23 unmodified lines24 * [BUG #2944](https://github.com/BurntSushi/ripgrep/pull/2944):25 Fix a bug where the "bytes searched" in `--stats` output could be incorrect.26 * [BUG #2990](https://github.com/BurntSushi/ripgrep/issues/2990):27 Fix a bug where ripgrep would mishandle globs that ended with a `.`.28+* [BUG #3076](https://github.com/BurntSushi/ripgrep/issues/3076):29+ Fix bug with `-m/--max-count` and `-U/--multiline` showing too many matches.30 * [BUG #3108](https://github.com/BurntSushi/ripgrep/issues/3108):31 Fix a bug where `-q --files-without-match` inverted the exit code.32 * [BUG #3140](https://github.com/BurntSushi/ripgrep/issues/3140):33 Ensure hyphens in flag names are escaped in the roff text for the man page.1737 unmodified lines