From 851817ce8d57349d1ff663ba009a13c85fd638a7 Mon Sep 17 00:00:00 2001 From: Dan Elksnitis <117392555+dpelksnitis@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:49:49 -0700 Subject: [PATCH 1/5] Add --max-results to end a search after the file with the N-th matching line A pattern that matches most of a large tree is only cut short by killing the search or piping it into head, and a server searches every candidate either way. --max-results stops after the file in which the N-th matching line is found, so the output is whole files. A scan and the on-disk index stop there. The plain server gets it as the max_results search option, stops after the chunk of candidates that reaches it, and marks the final reply "truncated". A shared daemon and a search with --sort search every candidate, and the limit is applied to the result. It cannot be combined with -l, --files-without-match, -c, --count-matches, -q or --files. On a 154k-file private tree (Windows), with the candidate reads batched (a separate change), a query with 37k candidate files that takes 6.5 s in full ends after 0.6 s with --max-results 10000. --- AGENTS.md | 5 + README.md | 14 +- tgrep-cli/src/main.rs | 14 ++ tgrep-cli/src/output.rs | 24 +++ tgrep-cli/src/search.rs | 33 +++- tgrep-cli/src/serve.rs | 74 ++++++++ tgrep-cli/tests/max_results.rs | 286 +++++++++++++++++++++++++++++ tgrep-cli/tests/streamed_search.rs | 9 + 8 files changed, 454 insertions(+), 5 deletions(-) create mode 100644 tgrep-cli/tests/max_results.rs diff --git a/AGENTS.md b/AGENTS.md index 8b4a4281..9f234244 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -315,6 +315,11 @@ legacy-format support for migration. ## Keep `index`, `serve` and search flags aligned +`--max-results ` ends a search after the file in which the N-th matching +line is found, and a server stops reading files there. Prefer it to piping +into `head` when a pattern may be broad: the output is whole files, and the +search itself is cut short. + Some flags describe the index, so `index`, `serve` and search have to agree on them. If they differ, the client either cannot find the server or silently searches a different set of files. diff --git a/README.md b/README.md index a9e4aa9e..49b9e37e 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,7 @@ These tables describe search flags. Use `tgrep index --help` and | `--files-without-match` | Print files that do NOT match | | `-q, --quiet` | Suppress output; exit code only | | `-m, --max-count ` | Limit matching lines per file (see [Match limits](#match-limits)) | +| `--max-results ` | Stop after the file in which the N-th matching line is found (see [Match limits](#match-limits)) | | `-g, --glob ` | Filter files by glob pattern, case-sensitive (repeatable); overrides `-t`/`-T` | | `--iglob ` | Case-insensitive glob filter (repeatable) | | `--glob-case-insensitive` | Treat all `-g` globs as case-insensitive | @@ -619,6 +620,15 @@ of lines covered by matches, so a multiline match is not cut short. tgrep reads a whole-file buffer even with `-m`; its `bytes_searched` statistic can therefore exceed ripgrep's. +`--max-results` limits matching lines across the whole invocation, which +ripgrep has no flag for. Files are reported whole: the search ends after the +file that brings the total to the limit, so a few more lines than the limit +can be printed. A server stops reading candidate files at that point too, +which keeps a broad query on a large tree fast; a shared daemon and a search +with `--sort` search every candidate and apply the limit to the result. It +cannot be combined with `-l`, `--files-without-match`, `-c`, +`--count-matches`, `-q` or `--files`. + ### JSON statistics `--json` emits ripgrep-shaped `begin`, `match`, `context`, `end`, and `summary` @@ -830,7 +840,9 @@ exit code determined by the search alone. Suppress the message with with the rows of the candidates searched since the last one and the `candidates` and `searched` counts so far, then the final result with the remaining rows. The CLI asks for this when it prints one file's rows after - another, and prints each part as it arrives. + another, and prints each part as it arrives. `"max_results": N` ends the + search after the file in which the N-th matching line is found, and the + final result then carries `"truncated": true`. The server's content cache is limited to 50,000 entries and 1 GiB of decoded content, with a 64 MiB per-entry limit. `--files` combines content-index paths diff --git a/tgrep-cli/src/main.rs b/tgrep-cli/src/main.rs index c18593bc..263fb4d5 100644 --- a/tgrep-cli/src/main.rs +++ b/tgrep-cli/src/main.rs @@ -139,6 +139,16 @@ struct Cli { #[arg(short = 'm', long = "max-count", global = true)] max_count: Option, + /// Stop after the file in which the NUM-th matching line is found. + #[arg( + long = "max-results", + global = true, + value_name = "NUM", + value_parser = clap::value_parser!(u64).range(1..), + conflicts_with_all = ["files_only", "files_without_match", "count", "count_matches", "quiet", "list_files"] + )] + max_results: Option, + /// List files that would be searched (no search performed). #[arg(long = "files", global = true)] list_files: bool, @@ -1142,6 +1152,7 @@ impl Cli { count: self.count, word_boundary: self.word_regexp, max_count: self.max_count, + max_results: self.max_results, json, vimgrep: self.vimgrep, stats: self.stats || self.debug || self.trace, @@ -1687,6 +1698,9 @@ fn run_search( process::exit(2); } } + if opts.max_results_reached(&writer) { + break; + } } writer.finish()?; diff --git a/tgrep-cli/src/output.rs b/tgrep-cli/src/output.rs index 989272ba..923be8fb 100644 --- a/tgrep-cli/src/output.rs +++ b/tgrep-cli/src/output.rs @@ -302,6 +302,11 @@ pub struct OutputWriter { all_searches: u64, total_matches: u64, total_matched_lines: u64, + /// Matching lines written so far, for `--max-results`. + written_lines: u64, + /// File and line of the last match written. A line with several match + /// rows (`-o`, `--vimgrep`) is one matching line. + last_written_line: Option<(String, usize)>, } impl OutputWriter { @@ -340,9 +345,16 @@ impl OutputWriter { all_searches: 0, total_matches: 0, total_matched_lines: 0, + written_lines: 0, + last_written_line: None, } } + /// How many matching lines have been written across the invocation. + pub fn written_lines(&self) -> u64 { + self.written_lines + } + pub fn match_totals(&self) -> (u64, u64) { (self.total_matches, self.total_matched_lines) } @@ -654,6 +666,18 @@ impl OutputWriter { } pub fn write_match(&mut self, m: &Match) -> io::Result<()> { + match &mut self.last_written_line { + Some((file, line)) if *file == m.file => { + if *line != m.line_number { + *line = m.line_number; + self.written_lines += 1; + } + } + last => { + *last = Some((m.file.clone(), m.line_number)); + self.written_lines += 1; + } + } // The context position moves past the whole source block, however // many lines its rewrite printed. let last_line = m.block.map_or(m.line_number, |(_, last)| last); diff --git a/tgrep-cli/src/search.rs b/tgrep-cli/src/search.rs index 48330a9a..b767ae08 100644 --- a/tgrep-cli/src/search.rs +++ b/tgrep-cli/src/search.rs @@ -41,6 +41,9 @@ pub struct SearchOptions { pub count: bool, pub word_boundary: bool, pub max_count: Option, + /// `--max-results`: stop after the file in which this many matching lines + /// have been written. + pub max_results: Option, pub json: bool, pub vimgrep: bool, pub stats: bool, @@ -247,6 +250,12 @@ impl SearchOptions { || self.effective_passthru()) } + /// Whether `--max-results` has been reached, so no further file is searched. + pub fn max_results_reached(&self, writer: &OutputWriter) -> bool { + self.max_results + .is_some_and(|limit| writer.written_lines() >= limit) + } + /// Resolve smart-case from literals in every supplied pattern. pub fn effective_case_insensitive(&self) -> Result { // `-s` wins over `-S`, matching ripgrep, but `-i` still wins over `-s`. @@ -1135,12 +1144,21 @@ fn search_via_server( ) -> Result { let mut stream = info.connect(SERVER_READ_TIMEOUT)?; let mut request = server_search_request(scope, opts, ci)?; + if let Some(limit) = opts.max_results + && opts.sort.is_none() + { + // Lets the server stop reading candidate files at the limit. One that + // predates the option ignores it and replies in full, and rendering + // applies the limit either way. A shared daemon is not sent it: that + // one rejects options it does not know and pages its replies. Nor is + // a sorted search: its limit counts files in sorted order, which the + // server does not search in. + request["params"]["max_results"] = serde_json::json!(limit); + } if opts.streams_from_server() { // The server then sends each chunk of files as soon as it is searched, // as `partial` replies ahead of the final one, and the rows are // printed as they arrive. One that predates the option replies once. - // A shared daemon is not asked: that one rejects options it does not - // know and pages its replies. request["params"]["stream"] = serde_json::json!(true); } writeln!(stream, "{request}")?; @@ -1783,8 +1801,15 @@ fn render_server_result( writer.write_count(file, n)?; } } else { + let mut current_file = None; for m in matches { let file = m.get("file").and_then(|f| f.as_str()).unwrap_or(""); + if current_file != Some(file) { + if opts.max_results_reached(writer) { + break; + } + current_file = Some(file); + } if let Some(stats) = &search_stats { writer.set_file_bytes_searched(stats[file]); } @@ -2051,7 +2076,7 @@ fn search_local_index( if search_file(&read, &matcher, rel_path, opts, writer, explicit)? { had_matches = true; - if opts.quiet { + if opts.quiet || opts.max_results_reached(writer) { break; } } @@ -2265,7 +2290,7 @@ fn brute_force_search( if search_file(&read, &matcher, &rel_path, opts, writer, false)? { had_matches = true; - if opts.quiet { + if opts.quiet || opts.max_results_reached(writer) { break; } } diff --git a/tgrep-cli/src/serve.rs b/tgrep-cli/src/serve.rs index 3d237d9f..005bee0c 100644 --- a/tgrep-cli/src/serve.rs +++ b/tgrep-cli/src/serve.rs @@ -1883,6 +1883,8 @@ struct SearchRequest { encoding: tgrep_core::encoding::EncodingMode, opts: SearchOpts, scope: SearchScope, + /// Stop after the file in which this many matching lines have been found. + max_results: Option, /// Send the rows of each chunk of candidates as soon as it is searched, /// as `partial` replies ahead of the final one. stream: bool, @@ -2121,6 +2123,14 @@ fn parse_search_params(params: &serde_json::Value) -> std::result::Result None, + Some(value) => Some( + value + .as_u64() + .ok_or_else(|| "max_results must be a non-negative integer".to_string())?, + ), + }; let stream = match params.get("stream") { None | Some(serde_json::Value::Null) => false, Some(value) => value @@ -2138,6 +2148,7 @@ fn parse_search_params(params: &serde_json::Value) -> std::result::Result= limit) { + truncated = true; + break; + } if stream && part_ready { part_ready = false; let mut part = serde_json::json!({ @@ -2609,6 +2627,16 @@ fn search_with_budget( Err(e) => return json_rpc_error(id, -32603, &format!("{e}")), }; for file in per_file { + if let Some(limit) = max_results { + // Whole files in candidate order, ending with the one that + // reaches the limit, so the result does not depend on how the + // candidates fall into chunks. + if matched_lines >= limit { + truncated = true; + break; + } + matched_lines += matched_line_count(&file.rows); + } matches.extend(file.rows); file_stats.extend(file.stats); search_stats.extend(file.search_stats); @@ -2652,6 +2680,10 @@ fn search_with_budget( "multiline_replace": true, "report_replacements": true, }); + if truncated { + // `max_results` ended the search before every candidate was searched. + result["truncated"] = serde_json::json!(true); + } if opts.stats || opts.count_matches { result["file_stats"] = serde_json::json!(file_stats); } @@ -2670,6 +2702,48 @@ fn search_with_budget( json_rpc_result(id, result) } +/// The matching lines among one file's rows: a line with several rows counts +/// once, and context and binary rows do not count. +fn matched_line_count(rows: &[serde_json::Value]) -> u64 { + let mut count = 0; + let mut last_line = None; + for row in rows { + if row + .get("type") + .and_then(|kind| kind.as_str()) + .unwrap_or("match") + != "match" + { + continue; + } + let line = row.get("line").and_then(|line| line.as_u64()); + if line != last_line { + last_line = line; + count += 1; + } + } + count +} + +#[cfg(test)] +mod matched_line_count_tests { + use super::*; + + #[test] + fn counts_lines_once() { + let rows = serde_json::json!([ + {"file": "a", "line": 3, "type": "context"}, + {"file": "a", "line": 4}, + {"file": "a", "line": 4, "type": "match"}, + {"file": "a", "line": 5, "type": "context"}, + {"file": "a", "line": 9, "type": "match"}, + {"file": "a", "type": "binary", "lines": 7}, + ]); + assert_eq!(matched_line_count(rows.as_array().unwrap()), 2); + assert_eq!(matched_line_count(&[]), 0); + } +} + fn update_content_cache( state: &ServerState, expected_generation: u64, diff --git a/tgrep-cli/tests/max_results.rs b/tgrep-cli/tests/max_results.rs new file mode 100644 index 00000000..c828098f --- /dev/null +++ b/tgrep-cli/tests/max_results.rs @@ -0,0 +1,286 @@ +//! `--max-results` ends a search after the file that brings the number of +//! matching lines to the limit, whichever backend answers: a full scan, the +//! on-disk index, or a server. The server applies the limit itself, so that a +//! broad query stops reading candidate files instead of only printing fewer. + +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpStream; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant}; + +use tempfile::TempDir; + +const MARKER: &str = "limited_marker"; +const FILES: usize = 5; +const LINES_PER_FILE: usize = 2; + +fn tgrep_bin() -> std::path::PathBuf { + assert_cmd::cargo::cargo_bin("tgrep") +} + +struct ServerGuard { + child: Child, +} + +impl Drop for ServerGuard { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Five files in separate directories, each with two matching lines and one +/// line that does not match. +fn setup_fixture() -> TempDir { + let dir = TempDir::new().unwrap(); + for file in 0..FILES { + let parent = dir.path().join(format!("dir{file}")); + fs::create_dir(&parent).unwrap(); + fs::write( + parent.join("file.txt"), + format!("{MARKER} one\nnothing here\n{MARKER} two\n"), + ) + .unwrap(); + } + dir +} + +/// The matching lines a search printed, as `(file, line)` in output order. +fn search(args: &[&str]) -> Vec<(String, String)> { + let output = Command::new(tgrep_bin()) + .args(["--color", "never", "--no-heading", "-n"]) + .args(args) + .output() + .expect("failed to run tgrep"); + assert!( + output.status.success(), + "tgrep {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout) + .unwrap() + .lines() + .map(|line| { + let (file, rest) = line.split_once(".txt:").expect("file:line:content"); + let (number, _) = rest.split_once(':').expect("line:content"); + (file.to_string(), number.to_string()) + }) + .collect() +} + +/// Whole files only: `limit` lines are reached inside the last file printed. +fn assert_limited(lines: &[(String, String)], limit: usize, backend: &str) { + let expected_files = limit.div_ceil(LINES_PER_FILE); + assert_eq!( + lines.len(), + expected_files * LINES_PER_FILE, + "{backend}: {lines:?}" + ); + let mut files: Vec<&str> = lines.iter().map(|(file, _)| file.as_str()).collect(); + files.dedup(); + assert_eq!(files.len(), expected_files, "{backend}: {lines:?}"); +} + +fn wait_for_port(index_dir: &Path) -> u16 { + let serve_json = index_dir.join("serve.json"); + let start = Instant::now(); + loop { + assert!( + start.elapsed() <= Duration::from_secs(60), + "tgrep serve did not start within 60 seconds" + ); + if let Ok(data) = fs::read_to_string(&serve_json) + && let Ok(info) = serde_json::from_str::(&data) + && let Some(port) = info.get("port").and_then(|v| v.as_u64()) + && TcpStream::connect(format!("127.0.0.1:{port}")).is_ok() + { + return port as u16; + } + thread::sleep(Duration::from_millis(20)); + } +} + +fn search_rpc(port: u16, params: serde_json::Value) -> serde_json::Value { + let request = + serde_json::json!({"jsonrpc": "2.0", "method": "search", "id": 1, "params": params}); + let mut stream = TcpStream::connect(format!("127.0.0.1:{port}")).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(30))) + .unwrap(); + writeln!(stream, "{request}").unwrap(); + stream.flush().unwrap(); + let mut response = String::new(); + BufReader::new(stream).read_line(&mut response).unwrap(); + let value: serde_json::Value = serde_json::from_str(&response).expect("invalid JSON response"); + value + .get("result") + .cloned() + .unwrap_or_else(|| panic!("no result in response: {response}")) +} + +#[test] +fn scan_stops_at_limit() { + let fixture = setup_fixture(); + let root = fixture.path().to_str().unwrap(); + + let mut all = search(&["--no-index", MARKER, root]); + assert_eq!(all.len(), FILES * LINES_PER_FILE); + all.sort(); + + for limit in [1, 2, 3, 4] { + let limit_arg = limit.to_string(); + let lines = search(&["--no-index", "--max-results", &limit_arg, MARKER, root]); + assert_limited(&lines, limit, "scan"); + } + // A scan visits files in no fixed order, so compare the sets. + let mut lines = search(&["--no-index", "--max-results", "1000", MARKER, root]); + lines.sort(); + assert_eq!(lines, all, "a limit that is not reached changes nothing"); +} + +#[test] +fn limit_spans_paths() { + let fixture = setup_fixture(); + let first = fixture.path().join("dir0"); + let second = fixture.path().join("dir1"); + let lines = search(&[ + "--no-index", + "--max-results", + "2", + MARKER, + first.to_str().unwrap(), + second.to_str().unwrap(), + ]); + assert_limited(&lines, 2, "two search paths"); +} + +#[test] +fn index_and_server_stop_at_limit() { + let fixture = setup_fixture(); + let root = fixture.path().to_str().unwrap(); + let index = TempDir::new().unwrap(); + let index_dir = index.path().join("index"); + let index_arg = index_dir.to_str().unwrap(); + + let output = Command::new(tgrep_bin()) + .args(["index", root, "--index-path", index_arg]) + .output() + .expect("failed to run tgrep index"); + assert!( + output.status.success(), + "index build failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let indexed = search(&[ + "--index-path", + index_arg, + "--max-results", + "3", + MARKER, + root, + ]); + assert_limited(&indexed, 3, "on-disk index"); + let sorted_args = [ + "--index-path", + index_arg, + "--sort", + "path", + "--max-results", + "3", + MARKER, + root, + ]; + let sorted_indexed = search(&sorted_args); + assert_limited(&sorted_indexed, 3, "on-disk index, sorted"); + assert!( + sorted_indexed[0].0.contains("dir0"), + "a sorted search starts with the first path: {sorted_indexed:?}" + ); + + let child = Command::new(tgrep_bin()) + .args(["serve", root, "--index-path", index_arg, "--no-watch"]) + .stderr(Stdio::null()) + .spawn() + .expect("failed to spawn tgrep serve"); + let _guard = ServerGuard { child }; + let port = wait_for_port(&index_dir); + + let served = search(&[ + "--index-path", + index_arg, + "--max-results", + "3", + MARKER, + root, + ]); + assert_eq!( + served, indexed, + "the server and the index report the same files" + ); + // A sorted search counts its limit in sorted order, whatever order the + // server searches in. + assert_eq!(search(&sorted_args), sorted_indexed); + + // The server truncates the reply itself rather than leaving it to the client. + let limited = search_rpc( + port, + serde_json::json!({"pattern": MARKER, "max_results": 3}), + ); + assert_eq!(limited["matches"].as_array().unwrap().len(), 4, "{limited}"); + assert_eq!(limited["truncated"], true, "{limited}"); + + let exact = search_rpc( + port, + serde_json::json!({"pattern": MARKER, "max_results": 4}), + ); + assert_eq!(exact["matches"].as_array().unwrap().len(), 4, "{exact}"); + assert_eq!(exact["truncated"], true, "{exact}"); + + let unreached = search_rpc( + port, + serde_json::json!({"pattern": MARKER, "max_results": 1000}), + ); + assert_eq!( + unreached["matches"].as_array().unwrap().len(), + FILES * LINES_PER_FILE, + "{unreached}" + ); + assert!(unreached.get("truncated").is_none(), "{unreached}"); + + let unlimited = search_rpc(port, serde_json::json!({"pattern": MARKER})); + assert_eq!( + unlimited["matches"].as_array().unwrap().len(), + FILES * LINES_PER_FILE, + "{unlimited}" + ); + assert!(unlimited.get("truncated").is_none(), "{unlimited}"); +} + +#[test] +fn conflicting_modes_rejected() { + let fixture = setup_fixture(); + let root = fixture.path().to_str().unwrap(); + for mode in [ + "-l", + "--files-without-match", + "-c", + "--count-matches", + "-q", + "--files", + ] { + let output = Command::new(tgrep_bin()) + .args(["--no-index", mode, "--max-results", "2", MARKER, root]) + .output() + .expect("failed to run tgrep"); + assert_eq!(output.status.code(), Some(2), "{mode}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("--max-results"), + "{mode}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } +} diff --git a/tgrep-cli/tests/streamed_search.rs b/tgrep-cli/tests/streamed_search.rs index 895ea9e4..77918648 100644 --- a/tgrep-cli/tests/streamed_search.rs +++ b/tgrep-cli/tests/streamed_search.rs @@ -187,6 +187,15 @@ fn parts_add_up() { let streamed_files: Vec = parts.iter().flat_map(files_of).collect(); assert_eq!(streamed_files, whole_files, "same rows in the same order"); + // With a limit, the parts end at the file that reaches it. + let limited = search_replies( + port, + serde_json::json!({"pattern": MARKER, "stream": true, "max_results": 100}), + ); + let limited_files: Vec = limited.iter().flat_map(files_of).collect(); + assert_eq!(limited_files, whole_files[..100]); + assert_eq!(limited.last().unwrap()["truncated"], true); + // The CLI prints the same lines whether the server streamed them (plain // output) or replied once (`--sort` needs the whole result). let streamed = cli_lines(&["--index-path", index_arg, MARKER, root]); From 4121801a9864ccf0018b59d1fc3007db1cf8a3da Mon Sep 17 00:00:00 2001 From: Dan Elksnitis <117392555+dpelksnitis@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:10:52 -0700 Subject: [PATCH 2/5] Count a file's source lines towards --max-results The limit was counted from the rows written, keyed by the file's path under its search root and the row's line number. Files of one name under separate search paths were taken for one file, and a match of several lines printed as one row (-U with --vimgrep or --replace) counted as one line. Each reported file now adds the matching lines of its source, as its match totals give them. A scan and the on-disk index take them from the file's matches, and the server carries them with the file's result. For the count it keeps across search paths, the client asks every limited search for the per-file totals; rows are only counted for a server that predates those. --- README.md | 5 +- tgrep-cli/src/output.rs | 34 +++------ tgrep-cli/src/search.rs | 86 +++++++++++++++++++-- tgrep-cli/src/serve.rs | 47 +----------- tgrep-cli/tests/max_results.rs | 127 ++++++++++++++++++++++++++----- tgrep-cli/tests/shared_daemon.rs | 41 ++++++++++ 6 files changed, 247 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 49b9e37e..50b910c7 100644 --- a/README.md +++ b/README.md @@ -623,7 +623,10 @@ can therefore exceed ripgrep's. `--max-results` limits matching lines across the whole invocation, which ripgrep has no flag for. Files are reported whole: the search ends after the file that brings the total to the limit, so a few more lines than the limit -can be printed. A server stops reading candidate files at that point too, +can be printed. The lines counted are those of the source: a multiline match +counts every line it covers, however it is printed, and so do the matching +lines of a binary file that is reported with a note. A server stops reading +candidate files at that point too, which keeps a broad query on a large tree fast; a shared daemon and a search with `--sort` search every candidate and apply the limit to the result. It cannot be combined with `-l`, `--files-without-match`, `-c`, diff --git a/tgrep-cli/src/output.rs b/tgrep-cli/src/output.rs index 923be8fb..894912bd 100644 --- a/tgrep-cli/src/output.rs +++ b/tgrep-cli/src/output.rs @@ -302,11 +302,8 @@ pub struct OutputWriter { all_searches: u64, total_matches: u64, total_matched_lines: u64, - /// Matching lines written so far, for `--max-results`. - written_lines: u64, - /// File and line of the last match written. A line with several match - /// rows (`-o`, `--vimgrep`) is one matching line. - last_written_line: Option<(String, usize)>, + /// Matching lines of the files reported so far, for `--max-results`. + reported_lines: u64, } impl OutputWriter { @@ -345,14 +342,19 @@ impl OutputWriter { all_searches: 0, total_matches: 0, total_matched_lines: 0, - written_lines: 0, - last_written_line: None, + reported_lines: 0, } } - /// How many matching lines have been written across the invocation. - pub fn written_lines(&self) -> u64 { - self.written_lines + /// The matching lines of the files reported across the invocation. + pub fn reported_lines(&self) -> u64 { + self.reported_lines + } + + /// Count a reported file's matching lines towards `--max-results`. These + /// are lines of the source, however its matches are printed. + pub fn note_reported_lines(&mut self, lines: u64) { + self.reported_lines += lines; } pub fn match_totals(&self) -> (u64, u64) { @@ -666,18 +668,6 @@ impl OutputWriter { } pub fn write_match(&mut self, m: &Match) -> io::Result<()> { - match &mut self.last_written_line { - Some((file, line)) if *file == m.file => { - if *line != m.line_number { - *line = m.line_number; - self.written_lines += 1; - } - } - last => { - *last = Some((m.file.clone(), m.line_number)); - self.written_lines += 1; - } - } // The context position moves past the whole source block, however // many lines its rewrite printed. let last_line = m.block.map_or(m.line_number, |(_, last)| last); diff --git a/tgrep-cli/src/search.rs b/tgrep-cli/src/search.rs index b767ae08..522e750d 100644 --- a/tgrep-cli/src/search.rs +++ b/tgrep-cli/src/search.rs @@ -41,8 +41,8 @@ pub struct SearchOptions { pub count: bool, pub word_boundary: bool, pub max_count: Option, - /// `--max-results`: stop after the file in which this many matching lines - /// have been written. + /// `--max-results`: stop after the file that brings the matching lines + /// of the files reported to this many. pub max_results: Option, pub json: bool, pub vimgrep: bool, @@ -253,7 +253,7 @@ impl SearchOptions { /// Whether `--max-results` has been reached, so no further file is searched. pub fn max_results_reached(&self, writer: &OutputWriter) -> bool { self.max_results - .is_some_and(|limit| writer.written_lines() >= limit) + .is_some_and(|limit| writer.reported_lines() >= limit) } /// Resolve smart-case from literals in every supplied pattern. @@ -1426,7 +1426,10 @@ fn server_search_request( "vimgrep": opts.vimgrep, "detail": detail, "positions": positions, - "stats": opts.stats, + // The per-file totals are also what `--max-results` counts: the + // limit runs across every search path, and rows do not show how + // many lines of the source a match covers. + "stats": opts.stats || opts.max_results.is_some(), }, "id": 1, }); @@ -1635,7 +1638,7 @@ fn render_server_result( } else { None }; - let file_stats = if opts.stats || opts.count_matches { + let file_stats = if opts.stats || opts.count_matches || opts.max_results.is_some() { result .get("file_stats") .map(|stats| -> Result> { @@ -1801,14 +1804,32 @@ fn render_server_result( writer.write_count(file, n)?; } } else { + // Each file's matching lines, for `--max-results`, when the reply + // has them. + let source_lines: Option> = file_stats + .as_ref() + .filter(|_| opts.max_results.is_some()) + .map(|stats| { + stats + .iter() + .map(|stats| (stats.file.as_str(), stats.matched_lines)) + .collect() + }); let mut current_file = None; - for m in matches { + for (at, m) in matches.iter().enumerate() { let file = m.get("file").and_then(|f| f.as_str()).unwrap_or(""); if current_file != Some(file) { if opts.max_results_reached(writer) { break; } current_file = Some(file); + if opts.max_results.is_some() { + let lines = source_lines + .as_ref() + .and_then(|lines| lines.get(file).copied()) + .unwrap_or_else(|| row_source_lines(&matches[at..])); + writer.note_reported_lines(lines); + } } if let Some(stats) = &search_stats { writer.set_file_bytes_searched(stats[file]); @@ -1927,6 +1948,58 @@ fn render_server_result( Ok(had_matches) } +/// The matching source lines among the rows of the file that `rows` starts +/// with, for a server that predates per-file totals. A row of a rewritten +/// block counts the source lines of the block, and any other row its own +/// line, which is all that such a reply tells. +fn row_source_lines(rows: &[serde_json::Value]) -> u64 { + let file = rows.first().and_then(|row| row.get("file")); + let mut count = 0; + let mut counted_to = 0; + for row in rows.iter().take_while(|row| row.get("file") == file) { + if row + .get("type") + .and_then(|kind| kind.as_str()) + .unwrap_or("match") + != "match" + { + continue; + } + let line = row.get("line").and_then(|line| line.as_u64()).unwrap_or(0); + let block = row.get("block").and_then(|block| block.as_array()); + let bound = |at: usize| block.and_then(|block| block.get(at)?.as_u64()); + let first = bound(0).unwrap_or(line).max(counted_to + 1); + let last = bound(1).unwrap_or(line); + if last >= first { + count += last - first + 1; + counted_to = last; + } + } + count +} + +#[cfg(test)] +mod row_source_lines_tests { + use super::*; + + #[test] + fn rows_count_source_lines() { + let rows = serde_json::json!([ + {"file": "a", "line": 3, "type": "context"}, + {"file": "a", "line": 4}, + {"file": "a", "line": 4, "type": "match"}, + {"file": "a", "line": 6, "type": "match", "block": [6, 8]}, + {"file": "a", "line": 8, "type": "match", "block": [8, 9]}, + {"file": "a", "type": "binary", "lines": 7}, + {"file": "b", "line": 1}, + ]); + let rows = rows.as_array().unwrap(); + assert_eq!(row_source_lines(rows), 5); + assert_eq!(row_source_lines(&rows[6..]), 1); + assert_eq!(row_source_lines(&[]), 0); + } +} + fn search_local_index( root: &Path, index_dir: &Path, @@ -2707,6 +2780,7 @@ fn search_decoded_file( let (matches, matched_lines) = found.match_totals(); writer.note_matches(matches, matched_lines); } + writer.note_reported_lines(found.match_totals().1); let has_matches = !found.is_empty(); if !has_matches { diff --git a/tgrep-cli/src/serve.rs b/tgrep-cli/src/serve.rs index 005bee0c..59115f73 100644 --- a/tgrep-cli/src/serve.rs +++ b/tgrep-cli/src/serve.rs @@ -2635,7 +2635,7 @@ fn search_with_budget( truncated = true; break; } - matched_lines += matched_line_count(&file.rows); + matched_lines += file.matched_lines; } matches.extend(file.rows); file_stats.extend(file.stats); @@ -2702,48 +2702,6 @@ fn search_with_budget( json_rpc_result(id, result) } -/// The matching lines among one file's rows: a line with several rows counts -/// once, and context and binary rows do not count. -fn matched_line_count(rows: &[serde_json::Value]) -> u64 { - let mut count = 0; - let mut last_line = None; - for row in rows { - if row - .get("type") - .and_then(|kind| kind.as_str()) - .unwrap_or("match") - != "match" - { - continue; - } - let line = row.get("line").and_then(|line| line.as_u64()); - if line != last_line { - last_line = line; - count += 1; - } - } - count -} - -#[cfg(test)] -mod matched_line_count_tests { - use super::*; - - #[test] - fn counts_lines_once() { - let rows = serde_json::json!([ - {"file": "a", "line": 3, "type": "context"}, - {"file": "a", "line": 4}, - {"file": "a", "line": 4, "type": "match"}, - {"file": "a", "line": 5, "type": "context"}, - {"file": "a", "line": 9, "type": "match"}, - {"file": "a", "type": "binary", "lines": 7}, - ]); - assert_eq!(matched_line_count(rows.as_array().unwrap()), 2); - assert_eq!(matched_line_count(&[]), 0); - } -} - fn update_content_cache( state: &ServerState, expected_generation: u64, @@ -2790,6 +2748,8 @@ fn invalidate_cached_paths_locked<'a>( #[derive(Default)] struct FileSearchResult { rows: Vec, + /// The file's matching lines in the source, however its rows render them. + matched_lines: u64, stats: Option, search_stats: Option, } @@ -2918,6 +2878,7 @@ fn search_file_matches_bounded( } let mut result = FileSearchResult { rows: Vec::new(), + matched_lines: found.match_totals().1, search_stats, stats: (opts.stats || opts.count_matches).then(|| { let (matches, matched_lines) = found.match_totals(); diff --git a/tgrep-cli/tests/max_results.rs b/tgrep-cli/tests/max_results.rs index c828098f..0b790e1c 100644 --- a/tgrep-cli/tests/max_results.rs +++ b/tgrep-cli/tests/max_results.rs @@ -6,7 +6,7 @@ use std::fs; use std::io::{BufRead, BufReader, Write}; use std::net::TcpStream; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::thread; use std::time::{Duration, Instant}; @@ -79,9 +79,44 @@ fn assert_limited(lines: &[(String, String)], limit: usize, backend: &str) { expected_files * LINES_PER_FILE, "{backend}: {lines:?}" ); + assert_eq!(file_count(lines), expected_files, "{backend}: {lines:?}"); +} + +/// How many files `lines` are from. +fn file_count(lines: &[(String, String)]) -> usize { let mut files: Vec<&str> = lines.iter().map(|(file, _)| file.as_str()).collect(); files.dedup(); - assert_eq!(files.len(), expected_files, "{backend}: {lines:?}"); + files.len() +} + +/// An index of `root` in a directory of its own. +fn build_index(root: &str) -> (TempDir, PathBuf) { + let index = TempDir::new().unwrap(); + let index_dir = index.path().join("index"); + let output = Command::new(tgrep_bin()) + .args(["index", root, "--index-path"]) + .arg(&index_dir) + .output() + .expect("failed to run tgrep index"); + assert!( + output.status.success(), + "index build failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + (index, index_dir) +} + +/// A server for `root` and the port it listens on. +fn start_server(root: &str, index_dir: &Path) -> (ServerGuard, u16) { + let child = Command::new(tgrep_bin()) + .args(["serve", root, "--no-watch", "--index-path"]) + .arg(index_dir) + .stderr(Stdio::null()) + .spawn() + .expect("failed to spawn tgrep serve"); + let guard = ServerGuard { child }; + let port = wait_for_port(index_dir); + (guard, port) } fn wait_for_port(index_dir: &Path) -> u16 { @@ -161,20 +196,9 @@ fn limit_spans_paths() { fn index_and_server_stop_at_limit() { let fixture = setup_fixture(); let root = fixture.path().to_str().unwrap(); - let index = TempDir::new().unwrap(); - let index_dir = index.path().join("index"); + let (_index, index_dir) = build_index(root); let index_arg = index_dir.to_str().unwrap(); - let output = Command::new(tgrep_bin()) - .args(["index", root, "--index-path", index_arg]) - .output() - .expect("failed to run tgrep index"); - assert!( - output.status.success(), - "index build failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - let indexed = search(&[ "--index-path", index_arg, @@ -201,13 +225,7 @@ fn index_and_server_stop_at_limit() { "a sorted search starts with the first path: {sorted_indexed:?}" ); - let child = Command::new(tgrep_bin()) - .args(["serve", root, "--index-path", index_arg, "--no-watch"]) - .stderr(Stdio::null()) - .spawn() - .expect("failed to spawn tgrep serve"); - let _guard = ServerGuard { child }; - let port = wait_for_port(&index_dir); + let (_guard, port) = start_server(root, &index_dir); let served = search(&[ "--index-path", @@ -260,6 +278,73 @@ fn index_and_server_stop_at_limit() { assert!(unlimited.get("truncated").is_none(), "{unlimited}"); } +/// Files of one name under separate search paths are separate files. +#[test] +fn same_name_across_paths() { + let dir = TempDir::new().unwrap(); + let mut paths = Vec::new(); + for name in ["a", "b", "c"] { + let path = dir.path().join(name); + fs::create_dir(&path).unwrap(); + fs::write(path.join("file.txt"), format!("{MARKER}\n")).unwrap(); + paths.push(path.to_str().unwrap().to_string()); + } + let mut args = vec!["--no-index", "--max-results", "2", MARKER]; + args.extend(paths.iter().map(String::as_str)); + assert_eq!(search(&args).len(), 2); +} + +/// The limit counts lines of the source. A match of two lines counts as two, +/// also where it is printed as one row. +#[test] +fn multiline_counts_source_lines() { + let fixture = setup_fixture(); + let root = fixture.path().to_str().unwrap(); + let (_index, index_dir) = build_index(root); + let index_arg = index_dir.to_str().unwrap(); + let pattern = format!("{MARKER} one\\nnothing"); + + let check = |backend: &str, backend_args: &[&str]| { + for rendering in [&["--vimgrep"][..], &["--replace", "X"]] { + for order in [&[][..], &["--sort", "path"]] { + for (limit, files) in [("2", 1), ("3", 2), ("4", 2)] { + let mut args = vec!["-U", "--max-results", limit]; + args.extend(backend_args); + args.extend(rendering); + args.extend(order); + args.extend([pattern.as_str(), root]); + let lines = search(&args); + assert_eq!(lines.len(), files, "{backend} {args:?}: one row a file"); + assert_eq!(file_count(&lines), files, "{backend} {args:?}"); + } + } + } + }; + check("scan", &["--no-index"]); + check("on-disk index", &["--index-path", index_arg]); + + let (_guard, port) = start_server(root, &index_dir); + check("server", &["--index-path", index_arg]); + + // The count carries from one search path to the next. + let paths: Vec = (0..3) + .map(|at| fixture.path().join(format!("dir{at}"))) + .collect(); + let mut args = vec!["-U", "--vimgrep", "--max-results", "3"]; + args.extend(["--index-path", index_arg, pattern.as_str()]); + args.extend(paths.iter().map(|path| path.to_str().unwrap())); + assert_eq!(search(&args).len(), 2, "server, three paths"); + + let limited = search_rpc( + port, + serde_json::json!({ + "pattern": pattern, "multiline": true, "vimgrep": true, "max_results": 3, + }), + ); + assert_eq!(limited["matches"].as_array().unwrap().len(), 2, "{limited}"); + assert_eq!(limited["truncated"], true, "{limited}"); +} + #[test] fn conflicting_modes_rejected() { let fixture = setup_fixture(); diff --git a/tgrep-cli/tests/shared_daemon.rs b/tgrep-cli/tests/shared_daemon.rs index 670d468b..20bbcd7b 100644 --- a/tgrep-cli/tests/shared_daemon.rs +++ b/tgrep-cli/tests/shared_daemon.rs @@ -590,6 +590,47 @@ fn multiline_count_matches_uses_shared_per_file_totals() { ); } +/// `--max-results` counts the lines of the source when a shared daemon +/// answers: a match of two lines counts as two, though it is one row. +#[test] +fn shared_limit_counts_source_lines() { + let mut f = Fixture::new(); + let root = f.a.join("limit"); + fs::create_dir(&root).unwrap(); + for name in ["a.txt", "b.txt", "c.txt"] { + fs::write(root.join(name), "hello\nworld\n").unwrap(); + } + git(&f.a, &["add", "limit"]); + git(&f.a, &["commit", "-qm", "limit"]); + f.revision = git(&f.a, &["rev-parse", "HEAD"]); + let d = f.start(&["--no-watch"]); + let lease = d.attach(&f.a, &f.revision); + let before = d.lookup(&f.a)["queries"].as_u64().unwrap(); + let mut queries = 0; + for order in [&[][..], &["--sort", "path"]] { + for (limit, files) in [("2", 1), ("3", 2), ("4", 2)] { + let mut args = vec![ + "-U", + "--vimgrep", + "--color", + "never", + "--max-results", + limit, + ]; + args.extend(order); + args.extend(["--", r"hello\nworld", root.to_str().unwrap()]); + let rows = success(cli(&root, &args)); + queries += 1; + assert_eq!(rows.lines().count(), files, "{args:?}: {rows}"); + } + } + assert_eq!(d.lookup(&f.a)["queries"], before + queries); + d.rpc( + "detach", + json!({"root":f.a,"view":lease["view"],"lease":lease["lease"]}), + ); +} + fn prepare_multiline_counts(f: &mut Fixture) { fs::write( f.a.join("count-heavy.txt"), From 6050c06671a732c975036ac167044c868dc4f23b Mon Sep 17 00:00:00 2001 From: Dan Elksnitis <117392555+dpelksnitis@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:06:19 -0700 Subject: [PATCH 3/5] Keep a binary file out of the server's max_results count A file can be indexed as text and still be found binary when it is searched: indexing inspects only its first 8 KiB, and a file can change before the index catches up. The server counted the matching lines of such a file towards max_results, while the client leaves a binary file out of a directory search. A limit reached on that file ended the search with nothing printed, though text files matched. The server no longer counts a binary file. The client counts one that it reports, as a scan does. --- tgrep-cli/src/serve.rs | 35 +++++++++++++++++++++++++++++-- tgrep-cli/tests/max_results.rs | 38 ++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/tgrep-cli/src/serve.rs b/tgrep-cli/src/serve.rs index 59115f73..37371895 100644 --- a/tgrep-cli/src/serve.rs +++ b/tgrep-cli/src/serve.rs @@ -2748,7 +2748,9 @@ fn invalidate_cached_paths_locked<'a>( #[derive(Default)] struct FileSearchResult { rows: Vec, - /// The file's matching lines in the source, however its rows render them. + /// The file's matching lines in the source, however its rows render them, + /// for `max_results`. Zero for a binary file: the client decides whether + /// that one is reported, and counts it then. matched_lines: u64, stats: Option, search_stats: Option, @@ -2878,7 +2880,11 @@ fn search_file_matches_bounded( } let mut result = FileSearchResult { rows: Vec::new(), - matched_lines: found.match_totals().1, + matched_lines: if binary_offset.is_some() { + 0 + } else { + found.match_totals().1 + }, search_stats, stats: (opts.stats || opts.count_matches).then(|| { let (matches, matched_lines) = found.match_totals(); @@ -10332,6 +10338,31 @@ mod tests { assert_eq!(row_files(parts), order[..big_at]); } + /// A binary file does not use up `max_results`, since the client may not + /// report it. The search goes on to the next file. + #[test] + fn binary_not_counted() { + let (_temp, root, index_dir, state) = needle_files(8); + let order = needle_order(&state); + // Binary only past the part of a file that indexing inspects. + let mut late_binary = format!("needle\n{}\n", "x".repeat(16 * 1024)).into_bytes(); + late_binary.push(0); + std::fs::write(root.join(&order[0]), late_binary).unwrap(); + // A fresh state, which has not cached that file as text. + let state = test_server_state_from_index(&root, &index_dir); + + let reply: serde_json::Value = serde_json::from_str(&handle_search( + None, + &serde_json::json!({"pattern": "needle", "max_results": 1}), + &state, + )) + .unwrap(); + let rows = reply["result"]["matches"].as_array().unwrap(); + assert_eq!(rows[0]["type"], "binary", "{reply}"); + assert_eq!(row_files(std::slice::from_ref(&reply)), order[..2]); + assert_eq!(reply["result"]["truncated"], true, "{reply}"); + } + fn install_reader_file( state: &ServerState, root: &Path, diff --git a/tgrep-cli/tests/max_results.rs b/tgrep-cli/tests/max_results.rs index 0b790e1c..7b58b2d8 100644 --- a/tgrep-cli/tests/max_results.rs +++ b/tgrep-cli/tests/max_results.rs @@ -345,6 +345,44 @@ fn multiline_counts_source_lines() { assert_eq!(limited["truncated"], true, "{limited}"); } +/// A binary file that a directory search does not report does not use up the +/// limit either, whichever backend finds it. +#[test] +fn hidden_binary_not_counted() { + const TEXT_FILES: usize = 4; + let dir = TempDir::new().unwrap(); + // Binary only past the part of a file that indexing inspects, so these + // are candidates of an indexed search too. + let mut late_binary = format!("{MARKER}\n{}\n", "x".repeat(16 * 1024)).into_bytes(); + late_binary.push(0); + for file in 0..64 { + fs::write(dir.path().join(format!("binary{file}.txt")), &late_binary).unwrap(); + } + for file in 0..TEXT_FILES { + fs::write( + dir.path().join(format!("text{file}.txt")), + format!("{MARKER}\n"), + ) + .unwrap(); + } + let root = dir.path().to_str().unwrap(); + let (_index, index_dir) = build_index(root); + let index_arg = index_dir.to_str().unwrap(); + + // A limit of every text line is only reached by the last text file, in + // whatever order the files are searched. + let limit = TEXT_FILES.to_string(); + let limited = ["--max-results", &limit, MARKER, root]; + let all_text = |lines: Vec<(String, String)>, backend: &str| { + assert_eq!(lines.len(), TEXT_FILES, "{backend}: {lines:?}"); + }; + all_text(search(&[&["--no-index"], &limited[..]].concat()), "scan"); + let indexed = [&["--index-path", index_arg], &limited[..]].concat(); + all_text(search(&indexed), "on-disk index"); + let (_guard, _port) = start_server(root, &index_dir); + all_text(search(&indexed), "server"); +} + #[test] fn conflicting_modes_rejected() { let fixture = setup_fixture(); From 3ad98c77a10f84800fe366b2e501fd485e8015b3 Mon Sep 17 00:00:00 2001 From: Dan Elksnitis <117392555+dpelksnitis@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:42:04 -0700 Subject: [PATCH 4/5] Send a server what is left of --max-results; total the files printed A search of several paths sent each path's server the whole limit, so a later path was searched for more lines than the output still needed. It now gets what is left. With --stats, a limit applied to a server's or shared daemon's reply (a sorted search, a shared daemon) printed the totals of every file in the reply, where a scan reports the files it printed. The totals now cover the files ahead of the one at which the limit ended the output. --- tgrep-cli/src/search.rs | 58 +++++++++++++++++++++++++++++----- tgrep-cli/tests/max_results.rs | 26 +++++++++++++++ 2 files changed, 76 insertions(+), 8 deletions(-) diff --git a/tgrep-cli/src/search.rs b/tgrep-cli/src/search.rs index 522e750d..f9697ca2 100644 --- a/tgrep-cli/src/search.rs +++ b/tgrep-cli/src/search.rs @@ -250,6 +250,16 @@ impl SearchOptions { || self.effective_passthru()) } + /// The `max_results` to send a plain server when `reported` lines are + /// already counted: what is left of the limit, so that a later search + /// path ends as early as the first. None for a sorted search: its limit + /// counts files in sorted order, which the server does not search in. + fn server_max_results(&self, reported: u64) -> Option { + self.max_results + .filter(|_| self.sort.is_none()) + .map(|limit| limit.saturating_sub(reported)) + } + /// Whether `--max-results` has been reached, so no further file is searched. pub fn max_results_reached(&self, writer: &OutputWriter) -> bool { self.max_results @@ -1144,15 +1154,11 @@ fn search_via_server( ) -> Result { let mut stream = info.connect(SERVER_READ_TIMEOUT)?; let mut request = server_search_request(scope, opts, ci)?; - if let Some(limit) = opts.max_results - && opts.sort.is_none() - { + if let Some(limit) = opts.server_max_results(writer.reported_lines()) { // Lets the server stop reading candidate files at the limit. One that // predates the option ignores it and replies in full, and rendering // applies the limit either way. A shared daemon is not sent it: that - // one rejects options it does not know and pages its replies. Nor is - // a sorted search: its limit counts files in sorted order, which the - // server does not search in. + // one rejects options it does not know and pages its replies. request["params"]["max_results"] = serde_json::json!(limit); } if opts.streams_from_server() { @@ -1740,6 +1746,8 @@ fn render_server_result( } } + // The rows ahead of the file at which `--max-results` ended the output. + let mut reported_rows = matches.len(); if opts.quiet { // No output, but still report stats for the first matching file. } else if opts.files_only { @@ -1820,6 +1828,7 @@ fn render_server_result( let file = m.get("file").and_then(|f| f.as_str()).unwrap_or(""); if current_file != Some(file) { if opts.max_results_reached(writer) { + reported_rows = at; break; } current_file = Some(file); @@ -1913,18 +1922,32 @@ fn render_server_result( // Apply the same scope to per-file totals as to output rows. The // server's `num_matches` includes context rows, and // rendered spans can split or merge the original matches. + // Nor do the totals cover files that `--max-results` left out. + let reported = &matches[..reported_rows]; let (num, lines) = if let Some(stats) = &file_stats { let first_file = matches .first() .and_then(|m| m.get("file")) .and_then(|f| f.as_str()); + let reported_files: Option> = + (reported_rows < matches.len()).then(|| { + reported + .iter() + .filter_map(|m| m.get("file").and_then(|f| f.as_str())) + .collect() + }); stats .iter() .filter(|s| !opts.quiet || first_file == Some(s.file.as_str())) + .filter(|s| { + reported_files + .as_ref() + .is_none_or(|files| files.contains(s.file.as_str())) + }) .fold((0, 0), |(m, l), s| (m + s.matches, l + s.matched_lines)) } else { // Older servers only provide rendered rows. - count_reported_matches(matches) + count_reported_matches(reported) }; let mut narrowing_note = ""; if let Some(stats) = result.get("index_stats") @@ -1979,7 +2002,7 @@ fn row_source_lines(rows: &[serde_json::Value]) -> u64 { } #[cfg(test)] -mod row_source_lines_tests { +mod max_results_tests { use super::*; #[test] @@ -1998,6 +2021,25 @@ mod row_source_lines_tests { assert_eq!(row_source_lines(&rows[6..]), 1); assert_eq!(row_source_lines(&[]), 0); } + + #[test] + fn limited_request() { + let mut opts = SearchOptions { + pattern: "needle".into(), + ..Default::default() + }; + let stats = |opts: &SearchOptions| { + server_search_request(&IndexScope::Whole, opts, false).unwrap()["params"]["stats"] + .clone() + }; + assert_eq!(stats(&opts), false); + assert_eq!(opts.server_max_results(0), None); + + opts.max_results = Some(10); + assert_eq!(stats(&opts), true, "the limit counts per-file totals"); + assert_eq!(opts.server_max_results(0), Some(10)); + assert_eq!(opts.server_max_results(9), Some(1), "a later search path"); + } } fn search_local_index( diff --git a/tgrep-cli/tests/max_results.rs b/tgrep-cli/tests/max_results.rs index 7b58b2d8..d7121303 100644 --- a/tgrep-cli/tests/max_results.rs +++ b/tgrep-cli/tests/max_results.rs @@ -383,6 +383,32 @@ fn hidden_binary_not_counted() { all_text(search(&indexed), "server"); } +/// `--stats` totals cover the files printed, not those the limit left out. +#[test] +fn stats_cover_reported_files() { + let fixture = setup_fixture(); + let root = fixture.path().to_str().unwrap(); + let (_index, index_dir) = build_index(root); + let (_guard, _port) = start_server(root, &index_dir); + + for order in [&[][..], &["--sort", "path"]] { + let output = Command::new(tgrep_bin()) + .args(["--stats", "--max-results", "3", "--index-path"]) + .arg(&index_dir) + .args(order) + .args([MARKER, root]) + .output() + .expect("failed to run tgrep"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("via server"), "{order:?}: {stderr}"); + // Two files of two lines each reach a limit of three. + assert!( + stderr.contains("4 matches (4 matched lines)"), + "{order:?}: {stderr}" + ); + } +} + #[test] fn conflicting_modes_rejected() { let fixture = setup_fixture(); From 6d79b43d8978b58624d9fc21f68527eae14c0ec9 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Tue, 24 Nov 2026 17:29:04 -0800 Subject: [PATCH 5/5] Fix needless_bool clippy lints from Rust 1.100 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tgrep-cli/src/serve.rs | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/tgrep-cli/src/serve.rs b/tgrep-cli/src/serve.rs index 37371895..ec24122a 100644 --- a/tgrep-cli/src/serve.rs +++ b/tgrep-cli/src/serve.rs @@ -3567,24 +3567,29 @@ fn stop_native_watcher(state: &ServerState) { fn native_capacity_error(error: ¬ify::Error) -> bool { match &error.kind { notify::ErrorKind::MaxFilesWatch => true, - notify::ErrorKind::Io(error) => { - #[cfg(unix)] - if matches!( - error.raw_os_error(), - Some(libc::ENOSPC | libc::EMFILE | libc::ENFILE | libc::ENOMEM) - ) { - return true; - } - #[cfg(windows)] - if matches!(error.raw_os_error(), Some(4 | 8 | 14 | 1450 | 1816)) { - return true; - } - false - } + notify::ErrorKind::Io(error) => error.raw_os_error().is_some_and(native_capacity_os_error), _ => false, } } +#[cfg(unix)] +fn native_capacity_os_error(code: i32) -> bool { + matches!( + code, + libc::ENOSPC | libc::EMFILE | libc::ENFILE | libc::ENOMEM + ) +} + +#[cfg(windows)] +fn native_capacity_os_error(code: i32) -> bool { + matches!(code, 4 | 8 | 14 | 1450 | 1816) +} + +#[cfg(not(any(unix, windows)))] +fn native_capacity_os_error(_code: i32) -> bool { + false +} + fn watch_failure_reason(error: ¬ify::Error) -> String { let kind = if native_capacity_error(error) { "native watch capacity exhausted" @@ -7666,7 +7671,7 @@ fn refresh_stale_locked( ); } - if !stream_merge_stale_changes( + stream_merge_stale_changes( state, &changed, &added, @@ -7680,11 +7685,7 @@ fn refresh_stale_locked( visibility: Some(&walk.visibility), scanned_files: current_meta, }, - ) { - return false; - } - - true + ) } /// Restore a known-empty on-disk index after a failed bootstrap.