Skip to content
Myr

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

authored by Pavel Safronov · committed by Andrew Gallant · parent a60e62d · Browse files · 8 files+310 added−121 removed
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

8 files+310 added−121 removed

modified:crates/core/flags/defs.rs+4 added
3875 unmodified lines
3876 fn doc_long(&self) -> &'static str {3877 r"3878Limit the number of matching lines per file searched to \fINUM\fP.3879.sp3880When \flag{multiline} is used, a single match that spans multiple lines is only3881counted once for the purposes of this limit. Multiple matches in a single line3882are counted only once, as they would be in non-multiline mode.3883.sp3884Note that \fB0\fP is a legal value but not likely to be useful. When used,3885ripgrep won't search anything.3886"3887 }
3865 unmodified lines
modified:crates/core/flags/hiargs.rs+1 added-1 removed
615 unmodified lines
616 .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 lines
717 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 lines
modified:crates/printer/src/standard.rs+173 added-91 removed
9 unmodified lines
10use {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 lines
44 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 lines
69 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 lines
322 self.config.max_columns_preview = yes;323 self324 }325329 /// 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 }338326 /// 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 lines
527 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 lines
563 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 lines
643 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 lines
757 )?;758 }759 Ok(())760 }777778 /// 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 }793794 /// 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}762763impl<'p, 's, M: Matcher, W: WriteColor> Sink for StandardSink<'p, 's, M, W> {764 type Error = io::Error;
3 unmodified lines
768 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 }772773 self.record_matches(774 searcher,775 mat.buffer(),
9 unmodified lines
785 if self.binary_byte_offset.is_some() {786 return Ok(false);787 }788 }844789 StandardImpl::from_match(searcher, self, mat).sink()?;846 Ok(!self.should_quit())790 Ok(true)791 }792793 fn context(794 &mut self,
2 unmodified lines
797 ) -> Result<bool, io::Error> {798 self.standard.matches.clear();799 self.replacer.clear();800857 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 lines
808 }809 }810811 StandardImpl::from_context(searcher, self, ctx).sink()?;872 Ok(!self.should_quit())812 Ok(true)813 }814815 fn context_break(816 &mut self,
24 unmodified lines
841 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 }848849 fn finish(
535 unmodified lines
1385 Ok(())1386 }13871388 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 }13921393 let bin = self.searcher.binary_detection();
1283 unmodified lines
26772678 #[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 lines
2700 #[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 lines
2721";2722 assert_eq_printed!(expected, got);27232724 // 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 lines
2746 assert_eq_printed!(expected, got);27472748 // 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 lines
2770";2771 assert_eq_printed!(expected, got);27722773 // 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();27862787 let got = printer_contents(&mut printer);2788 let expected = "\2789For the Doctor Watsons of this world, as opposed to the Sherlock2790Holmeses, success in the province of detective work must always2791be, to a very large extent, the result of luck. Sherlock Holmes2792can extract a clew from a wisp of straw or a flake of cigar ash;2793but Doctor Watson has to have it taken out for him and dusted,2794and exhibited clearly, with a label attached.2795";2796 assert_eq_printed!(expected, got);2797 }27982799 #[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();28172818 let got = printer_contents(&mut printer);2819 let expected = "\2820For the Doctor Watsons of this world, as opposed to the Sherlock2821Holmeses, success in the province of detective work must always2822";2823 assert_eq_printed!(expected, got);28242825 // 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 lines
2843Holmeses, success in the province of detective work must always2844be, to a very large extent, the result of luck. Sherlock Holmes2845can extract a clew from a wisp of straw or a flake of cigar ash;2846but Doctor Watson has to have it taken out for him and dusted,2847";2848 assert_eq_printed!(expected, got);28492850 // 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();28662867 let got = printer_contents(&mut printer);2868 let expected = "\2869For the Doctor Watsons of this world, as opposed to the Sherlock2870Holmeses, success in the province of detective work must always2871--2872but Doctor Watson has to have it taken out for him and dusted,2873and exhibited clearly, with a label attached.2874";2875 assert_eq_printed!(expected, got);28762877 // 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();28912892 let got = printer_contents(&mut printer);2893 let expected = "\2894For the Doctor Watsons of this world, as opposed to the Sherlock2895Holmeses, success in the province of detective work must always2896be, to a very large extent, the result of luck. Sherlock Holmes2897can extract a clew from a wisp of straw or a flake of cigar ash;2898but Doctor Watson has to have it taken out for him and dusted,2899and exhibited clearly, with a label attached.2900";2901 assert_eq_printed!(expected, got);2902 }29032904 #[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 lines
2927 #[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 lines
2949 assert_eq_printed!(expected, got);2950 }29512952 #[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();29672968 let got = printer_contents(&mut printer);2969 let expected = "\2970line 22971line 3 x2972";2973 assert_eq_printed!(expected, got);2974 }29752976 #[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();29922993 let got = printer_contents(&mut printer);2994 let expected = "\2995line 22996line 3 x2997";2998 assert_eq_printed!(expected, got);2999 }30003001 #[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 lines
3929e3930";39313932 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 lines
modified:crates/searcher/src/searcher/core.rs+91 added-23 removed
31 unmodified lines
32 last_line_visited: usize,33 after_context_left: usize,34 has_sunk: bool,35 has_matched: bool,36 count: u64,37}3839impl<'s, M: Matcher, S: Sink> Core<'s, M, S> {40 pub(crate) fn new(
18 unmodified lines
59 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 lines
79 pub(crate) fn set_pos(&mut self, pos: usize) {80 self.pos = pos;81 }8283 fn count(&self) -> u64 {84 self.count85 }8687 fn increment_count(&mut self) {88 self.count += 1;89 }9091 pub(crate) fn binary_byte_offset(&self) -> Option<u64> {92 self.binary_byte_offset.map(|offset| offset as u64)93 }94
15 unmodified lines
110 ) -> Result<bool, S::Error> {111 self.sink.binary_data(&self.searcher, binary_byte_offset)112 }113114 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 }123124 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 }140141 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 }154155 pub(crate) fn begin(&mut self) -> Result<bool, S::Error> {156 self.sink.begin(&self.searcher)157 }158
117 unmodified lines
276 ) -> 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 lines
332 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 at
1 unmodified line
347 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());354355 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 lines
390 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 lines
414 }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 lines
456 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 }470471 #[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());478479 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 lines
503 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 lines
701 }702 }703 false704 }705706 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 lines
324 Ok(true)325 }326327 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 }332333 /// Advance the search position based on the previous match.334 ///
1215 unmodified lines
modified:crates/searcher/src/searcher/mod.rs+35 added-1 removed
178 unmodified lines
179 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}186187impl Default for Config {188 fn default() -> Config {
10 unmodified lines
199 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 lines
566 ) -> &mut SearcherBuilder {567 self.config.stop_on_nonmatch = stop_on_nonmatch;568 self569 }570571 /// 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}588589/// A searcher executes searches over a haystack and writes results to a caller590/// provided sink.
273 unmodified lines
864 pub fn multi_line(&self) -> bool {865 self.config.multi_line866 }867848 /// 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 }874875 /// 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 }888889 /// 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 the
196 unmodified lines
modified:tests/regression.rs+1 added
1457 unmodified lines
1458// See: https://github.com/BurntSushi/ripgrep/pull/29441459rgtest!(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});14651466// See: https://github.com/BurntSushi/ripgrep/issues/2990
55 unmodified lines
modified:CHANGELOG.md+2 added
23 unmodified lines
24* [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