1use std::ffi::OsString;
5use std::path::PathBuf;
6
7use crate::{print, search};
8
9pub const HELP: &str = "\
10trg — search inside compressed log archives (.tgz, .tar.zst, .tar.xz)
11
12USAGE:
13 trg [OPTIONS] PATTERN PATH...
14 trg [OPTIONS] -e PATTERN... PATH...
15 trg [OPTIONS] -T PATH...
16
17At least one PATH is required. trg never searches the current directory by
18default: a silent walk of $PWD is not a safe guess for a tool whose exit 1
19is a claim that the logs are clean.
20
21MATCHING (same meaning as ripgrep):
22 -e, --regexp PAT add a pattern; repeatable
23 -i, --ignore-case case-insensitive
24 -S, --smart-case case-insensitive unless the pattern has uppercase
25 -w, --word-regexp match whole words only
26 -F, --fixed-strings treat patterns as literals
27 -v, --invert-match show non-matching lines
28 -a, --text search members that look binary
29 -m, --max-count NUM stop after NUM matches per member
30 --crlf treat CRLF as the line terminator
31
32OUTPUT (same meaning as ripgrep):
33 -n, --line-number show line numbers (default)
34 -N, --no-line-number hide line numbers
35 -A, --after NUM lines of trailing context
36 -B, --before NUM lines of leading context
37 -C, --context NUM lines of context on both sides
38 -o, --only-matching print only the matching part
39 -c, --count print a count per member
40 -l, --files-with-matches
41 print member paths only
42 -q, --quiet print nothing; exit code only
43 --json JSON Lines output
44 --color WHEN auto | always | never (auto: only on a tty)
45 --escape WHEN show control bytes from logs and member names as
46 text (\\x1b) instead of sending them to the
47 terminal: auto | always | never (auto: on a tty,
48 per stream; piped output stays byte-exact)
49 If several output modes are given, the most
50 suppressive wins: -q, then -l, then -c, then --json.
51
52ARCHIVES:
53 -g, --glob PAT filter MEMBERS inside archives; repeatable. A
54 leading ! excludes; the last matching glob wins
55 --archive-glob PAT
56 when walking a directory, search only the archives
57 matching PAT; repeatable. Without a `/` it matches
58 the file name at any depth, with one the path below
59 the directory named. Files named explicitly are
60 always searched. A leading ! excludes, as for -g.
61 Matching nothing is exit 2
62 -T, --list-members list member paths without searching. Takes no
63 PATTERN at all: every positional is a PATH, so
64 `trg -T *.tgz` lists all of them
65 --archive-sep C separator in archive:member:line (default ':')
66 --no-sort allow output in completion order
67
68RESOURCES:
69 -j, --jobs NUM archives searched concurrently (default 1)
70 --turbo -j <ncpus> --nice 0
71 --nice NUM scheduling priority (default 10)
72 --no-nice do not lower priority
73 --no-drop-cache keep archive pages in the page cache
74 --inflate MODE auto | stream | buffer (default auto, which streams).
75 buffer decompresses each gzip archive whole into
76 memory; measured, it costs more CPU than streaming
77 --inflate-budget SIZE
78 memory ceiling for --inflate=buffer (default 64M)
79 --load-limit N clamp jobs if 1-min load average exceeds N
80
81 -h, --help this message
82 -V, --version version
83
84EXIT CODES:
85 0 matches found, everything read
86 1 no matches, everything read
87 2 something went unread — never trust a 1 you did not get
88
89NOTES (documented, and surprising the first time):
90 -T lists every member, including ones a search skips as binary.
91 Two directories symlinking the same file search it once (identity dedup).
92 An intact archive behind a corrupt gzip trailer is a 0; truncation is
93 still caught and is a 2.
94 --turbo's ordered output is bounded by neither --inflate-budget nor the
95 spill cap; peak RSS grows with the match volume held in order.
96 On a broken pipe (`| head`) trg stops early and exits 0, leaving later
97 archives unread.
98 Compression is detected from content, never from the filename, so there is
99 no -z flag. gzip, zstd and xz are recognised, each unwrapped one level, so a
100 logrotate'd access.log.1.gz, .zst or .xz inside the archive is searched
101 as text rather than skipped as binary.
102 --inflate=buffer is gzip-only; a zstd or xz archive always streams, which costs a
103 slower path and never a wrong answer.
104";
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum InflateMode { Auto, Stream, Buffer }
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum ColorArg { Auto, Always, Never }
111
112pub struct Args {
113 pub patterns: Vec<String>,
114 pub paths: Vec<PathBuf>,
115 pub globs: Vec<String>,
116 pub archive_globs: Vec<String>,
117 pub jobs: usize,
118 pub nice: Option<i32>,
119 pub drop_cache: bool,
120 pub inflate: InflateMode,
121 pub inflate_budget: u64,
122 pub load_limit: Option<f64>,
123 pub archive_sep: char,
124 pub sort: bool,
125 pub list_members: bool,
126 pub count: bool,
127 pub files_with_matches: bool,
128 pub quiet: bool,
129 pub json: bool,
130 pub color: ColorArg,
131 pub escape: ColorArg,
132 pub search: search::SearchOpts,
133 pub print: print::PrintOpts,
134}
135
136impl Default for Args {
137 fn default() -> Self {
138 Self {
139 patterns: Vec::new(),
140 paths: Vec::new(),
141 globs: Vec::new(),
142 archive_globs: Vec::new(),
143 jobs: 1,
144 nice: Some(10),
145 drop_cache: true,
146 inflate: InflateMode::Auto,
147 inflate_budget: 64 * 1024 * 1024,
148 load_limit: None,
149 archive_sep: ':',
150 sort: true,
151 list_members: false,
152 count: false,
153 files_with_matches: false,
154 quiet: false,
155 json: false,
156 color: ColorArg::Auto,
157 escape: ColorArg::Auto,
158 search: search::SearchOpts::default(),
159 print: print::PrintOpts::default(),
160 }
161 }
162}
163
164fn parse_size(s: &str) -> anyhow::Result<u64> {
166 let s = s.trim();
167 let (num, mult) = match s.chars().last() {
168 Some('K') | Some('k') => (&s[..s.len() - 1], 1024),
169 Some('M') | Some('m') => (&s[..s.len() - 1], 1024 * 1024),
170 Some('G') | Some('g') => (&s[..s.len() - 1], 1024 * 1024 * 1024),
171 _ => (s, 1),
172 };
173 let n: u64 = num.parse()?;
174 n.checked_mul(mult)
175 .ok_or_else(|| anyhow::anyhow!("--inflate-budget value too large: {s}"))
176}
177
178pub fn parse() -> anyhow::Result<Args> {
179 parse_from(std::env::args_os())
180}
181
182pub fn parse_from<I>(argv: I) -> anyhow::Result<Args>
183where
184 I: IntoIterator<Item = OsString>,
185{
186 use lexopt::prelude::*;
187
188 let mut a = Args::default();
189 let mut explicit_jobs = false;
190 let mut explicit_nice = false;
191 let mut ctx_both: Option<usize> = None;
192 let mut positionals: Vec<OsString> = Vec::new();
196 let mut explicit_patterns = false;
197
198 let mut p = lexopt::Parser::from_iter(argv);
199 while let Some(arg) = p.next()? {
200 match arg {
201 Short('e') | Long("regexp") => {
202 a.patterns.push(p.value()?.string()?);
203 explicit_patterns = true;
204 }
205 Short('i') | Long("ignore-case") => a.search.case_insensitive = true,
206 Short('S') | Long("smart-case") => a.search.smart_case = true,
207 Short('w') | Long("word-regexp") => a.search.word = true,
208 Short('F') | Long("fixed-strings") => a.search.fixed = true,
209 Short('v') | Long("invert-match") => a.search.invert = true,
210 Short('a') | Long("text") => a.search.text = true,
211 Short('m') | Long("max-count") => {
212 a.search.max_count = Some(p.value()?.parse()?)
213 }
214 Long("crlf") => a.search.crlf = true,
215
216 Short('n') | Long("line-number") => a.search.line_numbers = true,
217 Short('N') | Long("no-line-number") => a.search.line_numbers = false,
218 Short('A') | Long("after") | Long("after-context") => {
219 a.search.after = p.value()?.parse()?
220 }
221 Short('B') | Long("before") | Long("before-context") => {
222 a.search.before = p.value()?.parse()?
223 }
224 Short('C') | Long("context") => ctx_both = Some(p.value()?.parse()?),
225 Short('o') | Long("only-matching") => a.print.only_matching = true,
226 Short('c') | Long("count") => a.count = true,
227 Short('l') | Long("files-with-matches") => a.files_with_matches = true,
228 Short('q') | Long("quiet") => a.quiet = true,
229 Long("json") => a.json = true,
230 Long("color") => {
231 a.color = match p.value()?.string()?.as_str() {
232 "auto" => ColorArg::Auto,
233 "always" => ColorArg::Always,
234 "never" => ColorArg::Never,
235 other => anyhow::bail!("--color expects auto|always|never, got '{other}'"),
236 }
237 }
238 Long("escape") => {
239 a.escape = match p.value()?.string()?.as_str() {
240 "auto" => ColorArg::Auto,
241 "always" => ColorArg::Always,
242 "never" => ColorArg::Never,
243 other => anyhow::bail!("--escape expects auto|always|never, got '{other}'"),
244 }
245 }
246
247 Short('g') | Long("glob") => a.globs.push(p.value()?.string()?),
248 Long("archive-glob") => a.archive_globs.push(p.value()?.string()?),
249 Short('T') | Long("list-members") => a.list_members = true,
250 Long("archive-sep") => {
251 let v = p.value()?.string()?;
252 let mut it = v.chars();
253 match (it.next(), it.next()) {
254 (Some(c), None) => a.archive_sep = c,
255 _ => anyhow::bail!("--archive-sep expects exactly one character"),
256 }
257 }
258 Long("no-sort") => a.sort = false,
259
260 Short('j') | Long("jobs") => {
261 a.jobs = p.value()?.parse()?;
262 explicit_jobs = true;
263 }
264 Long("turbo") => {
265 if !explicit_jobs { a.jobs = num_cpus::get(); }
266 if !explicit_nice { a.nice = Some(0); }
267 }
268 Long("nice") => {
269 a.nice = Some(p.value()?.parse()?);
270 explicit_nice = true;
271 }
272 Long("no-nice") => {
273 a.nice = None;
274 explicit_nice = true;
275 }
276 Long("no-drop-cache") => a.drop_cache = false,
277 Long("inflate") => {
278 a.inflate = match p.value()?.string()?.as_str() {
279 "auto" => InflateMode::Auto,
280 "stream" => InflateMode::Stream,
281 "buffer" => InflateMode::Buffer,
282 other => anyhow::bail!("--inflate expects auto|stream|buffer, got '{other}'"),
283 }
284 }
285 Long("inflate-budget") => a.inflate_budget = parse_size(&p.value()?.string()?)?,
286 Long("load-limit") => a.load_limit = Some(p.value()?.parse()?),
287
288 Short('h') | Long("help") => {
289 print!("{HELP}");
290 std::process::exit(0);
291 }
292 Short('V') | Long("version") => {
293 println!("trg {}", env!("CARGO_PKG_VERSION"));
294 std::process::exit(0);
295 }
296
297 Value(v) => positionals.push(v),
298 other => return Err(other.unexpected().into()),
299 }
300 }
301
302 if let Some(n) = ctx_both {
305 a.search.before = n;
306 a.search.after = n;
307 }
308 a.print.mode = if a.quiet {
313 print::Mode::Quiet
314 } else if a.files_with_matches {
315 print::Mode::FilesWithMatches
316 } else if a.count {
317 print::Mode::Count
318 } else if a.json {
319 print::Mode::Json
320 } else {
321 print::Mode::Standard
322 };
323
324 let mut rest = positionals.into_iter();
338 if !a.list_members
339 && !explicit_patterns
340 && let Some(first) = rest.next()
341 {
342 a.patterns.push(first.string()?);
343 }
344 a.paths.extend(rest.map(PathBuf::from));
345
346 if a.patterns.is_empty() && !a.list_members {
348 anyhow::bail!("no pattern given\n\n{HELP}");
349 }
350 if a.paths.is_empty() {
358 anyhow::bail!("no path given: name at least one archive or directory\n\n{HELP}");
359 }
360 Ok(a)
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 fn p(args: &[&str]) -> Args {
368 let argv: Vec<std::ffi::OsString> =
369 std::iter::once("trg".into()).chain(args.iter().map(|s| s.into())).collect();
370 parse_from(argv).unwrap()
371 }
372
373 #[test]
374 fn defaults_match_the_spec() {
375 let a = p(&["pat", "f.tgz"]);
376 assert_eq!(a.jobs, 1);
377 assert_eq!(a.nice, Some(10));
378 assert!(a.drop_cache);
379 assert!(matches!(a.inflate, InflateMode::Auto));
380 assert_eq!(a.inflate_budget, 64 * 1024 * 1024);
381 assert_eq!(a.archive_sep, ':');
382 assert!(a.sort);
383 assert_eq!(a.search.heap_limit, 16 * 1024 * 1024);
384 assert!(a.load_limit.is_none());
385 }
386
387 #[test]
388 fn first_positional_is_the_pattern_rest_are_paths() {
389 let a = p(&["NEEDLE", "a.tgz", "b.tgz"]);
390 assert_eq!(a.patterns, vec!["NEEDLE"]);
391 assert_eq!(a.paths.len(), 2);
392 }
393
394 #[test]
395 fn dash_e_patterns_do_not_consume_the_first_positional() {
396 let a = p(&["-e", "one", "-e", "two", "a.tgz"]);
397 assert_eq!(a.patterns, vec!["one", "two"]);
398 assert_eq!(a.paths.len(), 1);
399 }
400
401 #[test]
402 fn turbo_raises_jobs_and_clears_nice() {
403 let a = p(&["--turbo", "pat", "f.tgz"]);
404 assert_eq!(a.jobs, num_cpus::get());
405 assert_eq!(a.nice, Some(0));
406 assert!(a.drop_cache, "cache dropping stays on under --turbo");
407 }
408
409 #[test]
410 fn explicit_j_after_turbo_wins() {
411 let a = p(&["--turbo", "-j", "2", "pat", "f.tgz"]);
412 assert_eq!(a.jobs, 2);
413 }
414
415 #[test]
416 fn no_nice_disables_priority_lowering() {
417 let a = p(&["--no-nice", "pat", "f.tgz"]);
418 assert_eq!(a.nice, None);
419 }
420
421 #[test]
422 fn context_flags_match_rg_semantics() {
423 let a = p(&["-C", "3", "pat", "f.tgz"]);
424 assert_eq!((a.search.before, a.search.after), (3, 3));
425 let a = p(&["-A", "2", "-B", "1", "pat", "f.tgz"]);
426 assert_eq!((a.search.before, a.search.after), (1, 2));
427 }
428
429 #[test]
430 fn n_capital_disables_line_numbers() {
431 assert!(p(&["pat", "f.tgz"]).search.line_numbers);
432 assert!(!p(&["-N", "pat", "f.tgz"]).search.line_numbers);
433 }
434
435 #[test]
436 fn size_suffixes_parse() {
437 assert_eq!(p(&["--inflate-budget", "512K", "p", "f"]).inflate_budget, 512 * 1024);
438 assert_eq!(p(&["--inflate-budget", "2M", "p", "f"]).inflate_budget, 2 * 1024 * 1024);
439 assert_eq!(p(&["--inflate-budget", "1G", "p", "f"]).inflate_budget, 1024 * 1024 * 1024);
440 assert_eq!(p(&["--inflate-budget", "1024", "p", "f"]).inflate_budget, 1024);
441 }
442
443 #[test]
444 fn globs_accumulate() {
445 let a = p(&["-g", "*.access.log", "-g", "*.error.log", "pat", "f.tgz"]);
446 assert_eq!(a.globs.len(), 2);
447 }
448
449 #[test]
450 fn archive_sep_is_configurable() {
451 assert_eq!(p(&["--archive-sep", "!", "pat", "f.tgz"]).archive_sep, '!');
452 }
453
454 #[test]
455 fn unknown_flag_is_an_error_not_a_pattern() {
456 let argv: Vec<std::ffi::OsString> =
457 ["trg", "--nonsense", "pat", "f.tgz"].iter().map(|s| s.into()).collect();
458 assert!(parse_from(argv).is_err());
459 }
460
461 #[test]
462 fn inflate_mode_rejects_garbage() {
463 let argv: Vec<std::ffi::OsString> =
464 ["trg", "--inflate", "sideways", "p", "f"].iter().map(|s| s.into()).collect();
465 assert!(parse_from(argv).is_err());
466 }
467
468 #[test]
469 fn crlf_flag_sets_the_search_opt_and_defaults_to_false() {
470 assert!(!p(&["pat", "f.tgz"]).search.crlf);
471 assert!(p(&["--crlf", "pat", "f.tgz"]).search.crlf);
472 }
473
474 #[test]
475 fn inflate_budget_overflow_is_an_error_not_a_wrapped_value() {
476 let argv: Vec<std::ffi::OsString> =
477 ["trg", "--inflate-budget", "18446744073709551615G", "p", "f"]
478 .iter().map(|s| s.into()).collect();
479 assert!(parse_from(argv).is_err());
480 }
481
482 #[test]
483 fn output_mode_precedence_is_most_suppressive_wins() {
484 assert_eq!(p(&["pat", "f"]).print.mode, print::Mode::Standard);
485 assert_eq!(p(&["-c", "pat", "f"]).print.mode, print::Mode::Count);
486 assert_eq!(p(&["-l", "pat", "f"]).print.mode, print::Mode::FilesWithMatches);
487 assert_eq!(p(&["-q", "pat", "f"]).print.mode, print::Mode::Quiet);
488 assert_eq!(p(&["--json", "pat", "f"]).print.mode, print::Mode::Json);
489 assert_eq!(p(&["-c", "-l", "pat", "f"]).print.mode, print::Mode::FilesWithMatches);
490 assert_eq!(p(&["-c", "-l", "-q", "pat", "f"]).print.mode, print::Mode::Quiet);
491 assert_eq!(p(&["--json", "-c", "pat", "f"]).print.mode, print::Mode::Count);
492 }
493
494 #[test]
495 fn color_parses_all_three_and_rejects_the_rest() {
496 assert_eq!(p(&["pat", "f"]).color, ColorArg::Auto);
497 assert_eq!(p(&["--color", "always", "pat", "f"]).color, ColorArg::Always);
498 assert_eq!(p(&["--color", "never", "pat", "f"]).color, ColorArg::Never);
499 let argv: Vec<std::ffi::OsString> =
500 ["trg", "--color", "nonsense", "pat", "f"].iter().map(|s| s.into()).collect();
501 assert!(parse_from(argv).is_err());
502 }
503
504 #[test]
509 fn dash_t_with_one_positional_takes_it_as_a_path_not_a_pattern() {
510 let a = p(&["-T", "archive.tgz"]);
511 assert!(a.patterns.is_empty(), "-T needs no pattern, got {:?}", a.patterns);
512 assert_eq!(a.paths, vec![PathBuf::from("archive.tgz")]);
513 }
514
515 #[test]
519 fn dash_t_takes_every_positional_as_a_path() {
520 let a = p(&["-T", "a.tgz", "b.tgz", "c.tgz"]);
521 assert!(a.patterns.is_empty(), "-T takes no pattern, got {:?}", a.patterns);
522 assert_eq!(
523 a.paths,
524 vec![PathBuf::from("a.tgz"), PathBuf::from("b.tgz"), PathBuf::from("c.tgz")]
525 );
526 }
527
528 #[test]
531 fn dash_t_after_the_positionals_parses_the_same() {
532 let a = p(&["a.tgz", "b.tgz", "-T"]);
533 assert!(a.patterns.is_empty(), "got {:?}", a.patterns);
534 assert_eq!(a.paths, vec![PathBuf::from("a.tgz"), PathBuf::from("b.tgz")]);
535 }
536
537 #[test]
541 fn an_explicit_e_makes_every_positional_a_path_whatever_the_order() {
542 let a = p(&["a.tgz", "-e", "pat", "b.tgz"]);
543 assert_eq!(a.patterns, vec!["pat"]);
544 assert_eq!(a.paths, vec![PathBuf::from("a.tgz"), PathBuf::from("b.tgz")]);
545 }
546
547 #[test]
550 fn dash_t_with_an_explicit_e_pattern_keeps_both() {
551 let a = p(&["-T", "-e", "pat", "archive.tgz"]);
552 assert_eq!(a.patterns, vec!["pat"]);
553 assert_eq!(a.paths, vec![PathBuf::from("archive.tgz")]);
554 }
555
556 fn err(args: &[&str]) -> String {
557 let argv: Vec<std::ffi::OsString> =
558 std::iter::once("trg".into()).chain(args.iter().map(|s| s.into())).collect();
559 match parse_from(argv) {
560 Ok(_) => panic!("expected a usage error, got a parse"),
561 Err(e) => format!("{e:#}"),
562 }
563 }
564
565 #[test]
568 fn a_missing_pattern_is_still_an_error_without_dash_t() {
569 assert!(err(&[]).contains("no pattern given"));
570 assert!(err(&["-e", "pat"]).contains("no path given"), "pattern present, path missing");
571 }
572
573 #[test]
577 fn a_missing_path_is_a_usage_error_not_an_empty_clean_run() {
578 assert!(err(&["needle"]).contains("no path given"), "pattern with no path");
579 assert!(err(&["-T"]).contains("no path given"), "-T with no path");
580 assert!(err(&["-q", "needle"]).contains("no path given"), "-q must not hide it");
581 }
582
583 #[test]
587 fn one_positional_is_the_pattern_and_leaves_no_path() {
588 assert!(err(&["archive.tgz"]).contains("no path given"));
589 }
590
591 #[test]
592 fn inflate_budget_accepts_u64_max_with_no_suffix() {
593 let a = p(&["--inflate-budget", &u64::MAX.to_string(), "p", "f"]);
594 assert_eq!(a.inflate_budget, u64::MAX);
595 }
596
597 #[test]
598 fn inflate_budget_accepts_a_large_value_with_a_suffix_just_under_the_boundary() {
599 let n = u64::MAX / (1024 * 1024 * 1024);
601 let a = p(&["--inflate-budget", &format!("{n}G"), "p", "f"]);
602 assert_eq!(a.inflate_budget, n * 1024 * 1024 * 1024);
603 }
604}