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