diff --git a/AGENTS.md b/AGENTS.md index 8b4a428..9f23424 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 a9e4aa9..50b910c 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,18 @@ 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. 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`, +`--count-matches`, `-q` or `--files`. + ### JSON statistics `--json` emits ripgrep-shaped `begin`, `match`, `context`, `end`, and `summary` @@ -830,7 +843,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 c18593b..263fb4d 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 989272b..894912b 100644 --- a/tgrep-cli/src/output.rs +++ b/tgrep-cli/src/output.rs @@ -302,6 +302,8 @@ pub struct OutputWriter { all_searches: u64, total_matches: u64, total_matched_lines: u64, + /// Matching lines of the files reported so far, for `--max-results`. + reported_lines: u64, } impl OutputWriter { @@ -340,9 +342,21 @@ impl OutputWriter { all_searches: 0, total_matches: 0, total_matched_lines: 0, + reported_lines: 0, } } + /// 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) { (self.total_matches, self.total_matched_lines) } diff --git a/tgrep-cli/src/search.rs b/tgrep-cli/src/search.rs index 48330a9..f9697ca 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 that brings the matching lines + /// of the files reported to this many. + pub max_results: Option, pub json: bool, pub vimgrep: bool, pub stats: bool, @@ -247,6 +250,22 @@ 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 + .is_some_and(|limit| writer.reported_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 +1154,17 @@ 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.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. + 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}")?; @@ -1408,7 +1432,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, }); @@ -1617,7 +1644,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> { @@ -1719,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 { @@ -1783,8 +1812,34 @@ fn render_server_result( writer.write_count(file, n)?; } } else { - for m in matches { + // 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 (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) { + reported_rows = at; + 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]); } @@ -1867,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") @@ -1902,6 +1971,77 @@ 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 max_results_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); + } + + #[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( root: &Path, index_dir: &Path, @@ -2051,7 +2191,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 +2405,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; } } @@ -2682,6 +2822,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 3d237d9..ec24122 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 += file.matched_lines; + } 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); } @@ -2716,6 +2748,10 @@ 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, + /// 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, } @@ -2844,6 +2880,11 @@ fn search_file_matches_bounded( } let mut result = FileSearchResult { rows: Vec::new(), + 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(); @@ -3526,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" @@ -7625,7 +7671,7 @@ fn refresh_stale_locked( ); } - if !stream_merge_stale_changes( + stream_merge_stale_changes( state, &changed, &added, @@ -7639,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. @@ -10297,6 +10339,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 new file mode 100644 index 0000000..d712130 --- /dev/null +++ b/tgrep-cli/tests/max_results.rs @@ -0,0 +1,435 @@ +//! `--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, PathBuf}; +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:?}" + ); + 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(); + 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 { + 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, index_dir) = build_index(root); + let index_arg = index_dir.to_str().unwrap(); + + 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 (_guard, port) = start_server(root, &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}"); +} + +/// 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}"); +} + +/// 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"); +} + +/// `--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(); + 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/shared_daemon.rs b/tgrep-cli/tests/shared_daemon.rs index 670d468..20bbcd7 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"), diff --git a/tgrep-cli/tests/streamed_search.rs b/tgrep-cli/tests/streamed_search.rs index 895ea9e..7791864 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]);