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. Without
54 a `/` it also matches the member's file name. A
55 leading ! excludes; the last matching glob wins
56 --archive-glob PAT
57 when walking a directory, search only the archives
58 matching PAT; repeatable. Without a `/` it matches
59 the file name at any depth, with one the path below
60 the directory named. Files named explicitly are
61 always searched. A leading ! excludes, as for -g.
62 Matching nothing is exit 2
63 -T, --list-members list member paths without searching. Takes no
64 PATTERN at all: every positional is a PATH, so
65 `trg -T *.tgz` lists all of them
66 --archive-sep C separator in archive:member:line (default ':')
67 --no-sort allow output in completion order
68
69RESOURCES:
70 -j, --jobs NUM archives searched concurrently (default 1)
71 --turbo -j <ncpus> --nice 0
72 --nice NUM scheduling priority (default 10)
73 --no-nice do not lower priority
74 --no-drop-cache keep archive pages in the page cache
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 not bounded by the spill cap; peak RSS grows
91 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 and --inflate-budget are accepted and ignored since 0.7.0, with
99 a note on stderr: trg always streams.
100";
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum ColorArg { Auto, Always, Never }
104
105pub struct Args {
106 pub patterns: Vec<String>,
107 pub paths: Vec<PathBuf>,
108 pub globs: Vec<String>,
109 pub archive_globs: Vec<String>,
110 pub jobs: usize,
111 pub nice: Option<i32>,
112 pub drop_cache: bool,
113 pub deprecated: Vec<&'static str>,
116 pub load_limit: Option<f64>,
117 pub archive_sep: char,
118 pub sort: bool,
119 pub list_members: bool,
120 pub count: bool,
121 pub files_with_matches: bool,
122 pub quiet: bool,
123 pub json: bool,
124 pub color: ColorArg,
125 pub escape: ColorArg,
126 pub search: search::SearchOpts,
127 pub print: print::PrintOpts,
128}
129
130impl Default for Args {
131 fn default() -> Self {
132 Self {
133 patterns: Vec::new(),
134 paths: Vec::new(),
135 globs: Vec::new(),
136 archive_globs: Vec::new(),
137 jobs: 1,
138 nice: Some(10),
139 drop_cache: true,
140 deprecated: Vec::new(),
141 load_limit: None,
142 archive_sep: ':',
143 sort: true,
144 list_members: false,
145 count: false,
146 files_with_matches: false,
147 quiet: false,
148 json: false,
149 color: ColorArg::Auto,
150 escape: ColorArg::Auto,
151 search: search::SearchOpts::default(),
152 print: print::PrintOpts::default(),
153 }
154 }
155}
156
157fn parse_size(s: &str) -> anyhow::Result<u64> {
159 let s = s.trim();
160 let (num, mult) = match s.chars().last() {
161 Some('K') | Some('k') => (&s[..s.len() - 1], 1024),
162 Some('M') | Some('m') => (&s[..s.len() - 1], 1024 * 1024),
163 Some('G') | Some('g') => (&s[..s.len() - 1], 1024 * 1024 * 1024),
164 _ => (s, 1),
165 };
166 let n: u64 = num.parse()?;
167 n.checked_mul(mult)
168 .ok_or_else(|| anyhow::anyhow!("--inflate-budget value too large: {s}"))
169}
170
171fn deprecate(a: &mut Args, flag: &'static str) {
172 if !a.deprecated.contains(&flag) {
173 a.deprecated.push(flag);
174 }
175}
176
177pub fn parse() -> anyhow::Result<Args> {
178 parse_from(std::env::args_os())
179}
180
181pub fn parse_from<I>(argv: I) -> anyhow::Result<Args>
182where
183 I: IntoIterator<Item = OsString>,
184{
185 use lexopt::prelude::*;
186
187 let mut a = Args::default();
188 let mut explicit_jobs = false;
189 let mut explicit_nice = false;
190 let mut ctx_both: Option<usize> = None;
191 let mut positionals: Vec<OsString> = Vec::new();
195 let mut explicit_patterns = false;
196
197 let mut p = lexopt::Parser::from_iter(argv);
198 while let Some(arg) = p.next()? {
199 match arg {
200 Short('e') | Long("regexp") => {
201 a.patterns.push(p.value()?.string()?);
202 explicit_patterns = true;
203 }
204 Short('i') | Long("ignore-case") => a.search.case_insensitive = true,
205 Short('S') | Long("smart-case") => a.search.smart_case = true,
206 Short('w') | Long("word-regexp") => a.search.word = true,
207 Short('F') | Long("fixed-strings") => a.search.fixed = true,
208 Short('v') | Long("invert-match") => a.search.invert = true,
209 Short('a') | Long("text") => a.search.text = true,
210 Short('m') | Long("max-count") => {
211 a.search.max_count = Some(p.value()?.parse()?)
212 }
213 Long("crlf") => a.search.crlf = true,
214
215 Short('n') | Long("line-number") => a.search.line_numbers = true,
216 Short('N') | Long("no-line-number") => a.search.line_numbers = false,
217 Short('A') | Long("after") | Long("after-context") => {
218 a.search.after = p.value()?.parse()?
219 }
220 Short('B') | Long("before") | Long("before-context") => {
221 a.search.before = p.value()?.parse()?
222 }
223 Short('C') | Long("context") => ctx_both = Some(p.value()?.parse()?),
224 Short('o') | Long("only-matching") => a.print.only_matching = true,
225 Short('c') | Long("count") => a.count = true,
226 Short('l') | Long("files-with-matches") => a.files_with_matches = true,
227 Short('q') | Long("quiet") => a.quiet = true,
228 Long("json") => a.json = true,
229 Long("color") => {
230 a.color = match p.value()?.string()?.as_str() {
231 "auto" => ColorArg::Auto,
232 "always" => ColorArg::Always,
233 "never" => ColorArg::Never,
234 other => anyhow::bail!("--color expects auto|always|never, got '{other}'"),
235 }
236 }
237 Long("escape") => {
238 a.escape = match p.value()?.string()?.as_str() {
239 "auto" => ColorArg::Auto,
240 "always" => ColorArg::Always,
241 "never" => ColorArg::Never,
242 other => anyhow::bail!("--escape expects auto|always|never, got '{other}'"),
243 }
244 }
245
246 Short('g') | Long("glob") => a.globs.push(p.value()?.string()?),
247 Long("archive-glob") => a.archive_globs.push(p.value()?.string()?),
248 Short('T') | Long("list-members") => a.list_members = true,
249 Long("archive-sep") => {
250 let v = p.value()?.string()?;
251 let mut it = v.chars();
252 match (it.next(), it.next()) {
253 (Some(c), None) => a.archive_sep = c,
254 _ => anyhow::bail!("--archive-sep expects exactly one character"),
255 }
256 }
257 Long("no-sort") => a.sort = false,
258
259 Short('j') | Long("jobs") => {
260 a.jobs = p.value()?.parse()?;
261 explicit_jobs = true;
262 }
263 Long("turbo") => {
264 if !explicit_jobs { a.jobs = num_cpus::get(); }
265 if !explicit_nice { a.nice = Some(0); }
266 }
267 Long("nice") => {
268 a.nice = Some(p.value()?.parse()?);
269 explicit_nice = true;
270 }
271 Long("no-nice") => {
272 a.nice = None;
273 explicit_nice = true;
274 }
275 Long("no-drop-cache") => a.drop_cache = false,
276 Long("inflate") => {
281 match p.value()?.string()?.as_str() {
282 "auto" | "stream" | "buffer" => {}
283 other => anyhow::bail!("--inflate expects auto|stream|buffer, got '{other}'"),
284 }
285 deprecate(&mut a, "--inflate");
286 }
287 Long("inflate-budget") => {
288 parse_size(&p.value()?.string()?)?;
289 deprecate(&mut a, "--inflate-budget");
290 }
291 Long("load-limit") => a.load_limit = Some(p.value()?.parse()?),
292
293 Short('h') | Long("help") => {
294 print!("{HELP}");
295 std::process::exit(0);
296 }
297 Short('V') | Long("version") => {
298 println!("trg {}", env!("CARGO_PKG_VERSION"));
299 std::process::exit(0);
300 }
301
302 Value(v) => positionals.push(v),
303 other => return Err(other.unexpected().into()),
304 }
305 }
306
307 if let Some(n) = ctx_both {
310 a.search.before = n;
311 a.search.after = n;
312 }
313 a.print.mode = if a.quiet {
318 print::Mode::Quiet
319 } else if a.files_with_matches {
320 print::Mode::FilesWithMatches
321 } else if a.count {
322 print::Mode::Count
323 } else if a.json {
324 print::Mode::Json
325 } else {
326 print::Mode::Standard
327 };
328
329 let mut rest = positionals.into_iter();
343 if !a.list_members
344 && !explicit_patterns
345 && let Some(first) = rest.next()
346 {
347 a.patterns.push(first.string()?);
348 }
349 a.paths.extend(rest.map(PathBuf::from));
350
351 if a.patterns.is_empty() && !a.list_members {
353 anyhow::bail!("no pattern given\n\n{HELP}");
354 }
355 if a.paths.is_empty() {
363 anyhow::bail!("no path given: name at least one archive or directory\n\n{HELP}");
364 }
365 Ok(a)
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 fn p(args: &[&str]) -> Args {
373 let argv: Vec<std::ffi::OsString> =
374 std::iter::once("trg".into()).chain(args.iter().map(|s| s.into())).collect();
375 parse_from(argv).unwrap()
376 }
377
378 #[test]
379 fn defaults_match_the_spec() {
380 let a = p(&["pat", "f.tgz"]);
381 assert_eq!(a.jobs, 1);
382 assert_eq!(a.nice, Some(10));
383 assert!(a.drop_cache);
384 assert!(a.deprecated.is_empty());
385 assert_eq!(a.archive_sep, ':');
386 assert!(a.sort);
387 assert_eq!(a.search.heap_limit, 16 * 1024 * 1024);
388 assert!(a.load_limit.is_none());
389 }
390
391 #[test]
392 fn first_positional_is_the_pattern_rest_are_paths() {
393 let a = p(&["NEEDLE", "a.tgz", "b.tgz"]);
394 assert_eq!(a.patterns, vec!["NEEDLE"]);
395 assert_eq!(a.paths.len(), 2);
396 }
397
398 #[test]
399 fn dash_e_patterns_do_not_consume_the_first_positional() {
400 let a = p(&["-e", "one", "-e", "two", "a.tgz"]);
401 assert_eq!(a.patterns, vec!["one", "two"]);
402 assert_eq!(a.paths.len(), 1);
403 }
404
405 #[test]
406 fn turbo_raises_jobs_and_clears_nice() {
407 let a = p(&["--turbo", "pat", "f.tgz"]);
408 assert_eq!(a.jobs, num_cpus::get());
409 assert_eq!(a.nice, Some(0));
410 assert!(a.drop_cache, "cache dropping stays on under --turbo");
411 }
412
413 #[test]
414 fn explicit_j_after_turbo_wins() {
415 let a = p(&["--turbo", "-j", "2", "pat", "f.tgz"]);
416 assert_eq!(a.jobs, 2);
417 }
418
419 #[test]
420 fn no_nice_disables_priority_lowering() {
421 let a = p(&["--no-nice", "pat", "f.tgz"]);
422 assert_eq!(a.nice, None);
423 }
424
425 #[test]
426 fn context_flags_match_rg_semantics() {
427 let a = p(&["-C", "3", "pat", "f.tgz"]);
428 assert_eq!((a.search.before, a.search.after), (3, 3));
429 let a = p(&["-A", "2", "-B", "1", "pat", "f.tgz"]);
430 assert_eq!((a.search.before, a.search.after), (1, 2));
431 }
432
433 #[test]
434 fn n_capital_disables_line_numbers() {
435 assert!(p(&["pat", "f.tgz"]).search.line_numbers);
436 assert!(!p(&["-N", "pat", "f.tgz"]).search.line_numbers);
437 }
438
439 #[test]
440 fn size_suffixes_parse() {
441 assert_eq!(parse_size("512K").unwrap(), 512 * 1024);
442 assert_eq!(parse_size("2M").unwrap(), 2 * 1024 * 1024);
443 assert_eq!(parse_size("1G").unwrap(), 1024 * 1024 * 1024);
444 assert_eq!(parse_size("1024").unwrap(), 1024);
445 assert_eq!(p(&["--inflate-budget", "1G", "p", "f"]).deprecated, ["--inflate-budget"]);
446 }
447
448 #[test]
449 fn globs_accumulate() {
450 let a = p(&["-g", "*.access.log", "-g", "*.error.log", "pat", "f.tgz"]);
451 assert_eq!(a.globs.len(), 2);
452 }
453
454 #[test]
455 fn archive_sep_is_configurable() {
456 assert_eq!(p(&["--archive-sep", "!", "pat", "f.tgz"]).archive_sep, '!');
457 }
458
459 #[test]
460 fn unknown_flag_is_an_error_not_a_pattern() {
461 let argv: Vec<std::ffi::OsString> =
462 ["trg", "--nonsense", "pat", "f.tgz"].iter().map(|s| s.into()).collect();
463 assert!(parse_from(argv).is_err());
464 }
465
466 #[test]
467 fn inflate_mode_rejects_garbage() {
468 let argv: Vec<std::ffi::OsString> =
469 ["trg", "--inflate", "sideways", "p", "f"].iter().map(|s| s.into()).collect();
470 assert!(parse_from(argv).is_err());
471 }
472
473 #[test]
474 fn crlf_flag_sets_the_search_opt_and_defaults_to_false() {
475 assert!(!p(&["pat", "f.tgz"]).search.crlf);
476 assert!(p(&["--crlf", "pat", "f.tgz"]).search.crlf);
477 }
478
479 #[test]
480 fn inflate_budget_overflow_is_an_error_not_a_wrapped_value() {
481 let argv: Vec<std::ffi::OsString> =
482 ["trg", "--inflate-budget", "18446744073709551615G", "p", "f"]
483 .iter().map(|s| s.into()).collect();
484 assert!(parse_from(argv).is_err());
485 }
486
487 #[test]
488 fn output_mode_precedence_is_most_suppressive_wins() {
489 assert_eq!(p(&["pat", "f"]).print.mode, print::Mode::Standard);
490 assert_eq!(p(&["-c", "pat", "f"]).print.mode, print::Mode::Count);
491 assert_eq!(p(&["-l", "pat", "f"]).print.mode, print::Mode::FilesWithMatches);
492 assert_eq!(p(&["-q", "pat", "f"]).print.mode, print::Mode::Quiet);
493 assert_eq!(p(&["--json", "pat", "f"]).print.mode, print::Mode::Json);
494 assert_eq!(p(&["-c", "-l", "pat", "f"]).print.mode, print::Mode::FilesWithMatches);
495 assert_eq!(p(&["-c", "-l", "-q", "pat", "f"]).print.mode, print::Mode::Quiet);
496 assert_eq!(p(&["--json", "-c", "pat", "f"]).print.mode, print::Mode::Count);
497 }
498
499 #[test]
500 fn color_parses_all_three_and_rejects_the_rest() {
501 assert_eq!(p(&["pat", "f"]).color, ColorArg::Auto);
502 assert_eq!(p(&["--color", "always", "pat", "f"]).color, ColorArg::Always);
503 assert_eq!(p(&["--color", "never", "pat", "f"]).color, ColorArg::Never);
504 let argv: Vec<std::ffi::OsString> =
505 ["trg", "--color", "nonsense", "pat", "f"].iter().map(|s| s.into()).collect();
506 assert!(parse_from(argv).is_err());
507 }
508
509 #[test]
514 fn dash_t_with_one_positional_takes_it_as_a_path_not_a_pattern() {
515 let a = p(&["-T", "archive.tgz"]);
516 assert!(a.patterns.is_empty(), "-T needs no pattern, got {:?}", a.patterns);
517 assert_eq!(a.paths, vec![PathBuf::from("archive.tgz")]);
518 }
519
520 #[test]
524 fn dash_t_takes_every_positional_as_a_path() {
525 let a = p(&["-T", "a.tgz", "b.tgz", "c.tgz"]);
526 assert!(a.patterns.is_empty(), "-T takes no pattern, got {:?}", a.patterns);
527 assert_eq!(
528 a.paths,
529 vec![PathBuf::from("a.tgz"), PathBuf::from("b.tgz"), PathBuf::from("c.tgz")]
530 );
531 }
532
533 #[test]
536 fn dash_t_after_the_positionals_parses_the_same() {
537 let a = p(&["a.tgz", "b.tgz", "-T"]);
538 assert!(a.patterns.is_empty(), "got {:?}", a.patterns);
539 assert_eq!(a.paths, vec![PathBuf::from("a.tgz"), PathBuf::from("b.tgz")]);
540 }
541
542 #[test]
546 fn an_explicit_e_makes_every_positional_a_path_whatever_the_order() {
547 let a = p(&["a.tgz", "-e", "pat", "b.tgz"]);
548 assert_eq!(a.patterns, vec!["pat"]);
549 assert_eq!(a.paths, vec![PathBuf::from("a.tgz"), PathBuf::from("b.tgz")]);
550 }
551
552 #[test]
555 fn dash_t_with_an_explicit_e_pattern_keeps_both() {
556 let a = p(&["-T", "-e", "pat", "archive.tgz"]);
557 assert_eq!(a.patterns, vec!["pat"]);
558 assert_eq!(a.paths, vec![PathBuf::from("archive.tgz")]);
559 }
560
561 fn err(args: &[&str]) -> String {
562 let argv: Vec<std::ffi::OsString> =
563 std::iter::once("trg".into()).chain(args.iter().map(|s| s.into())).collect();
564 match parse_from(argv) {
565 Ok(_) => panic!("expected a usage error, got a parse"),
566 Err(e) => format!("{e:#}"),
567 }
568 }
569
570 #[test]
573 fn a_missing_pattern_is_still_an_error_without_dash_t() {
574 assert!(err(&[]).contains("no pattern given"));
575 assert!(err(&["-e", "pat"]).contains("no path given"), "pattern present, path missing");
576 }
577
578 #[test]
582 fn a_missing_path_is_a_usage_error_not_an_empty_clean_run() {
583 assert!(err(&["needle"]).contains("no path given"), "pattern with no path");
584 assert!(err(&["-T"]).contains("no path given"), "-T with no path");
585 assert!(err(&["-q", "needle"]).contains("no path given"), "-q must not hide it");
586 }
587
588 #[test]
592 fn one_positional_is_the_pattern_and_leaves_no_path() {
593 assert!(err(&["archive.tgz"]).contains("no path given"));
594 }
595
596 #[test]
597 fn inflate_budget_accepts_u64_max_with_no_suffix() {
598 assert_eq!(parse_size(&u64::MAX.to_string()).unwrap(), u64::MAX);
599 }
600
601 #[test]
602 fn inflate_budget_accepts_a_large_value_with_a_suffix_just_under_the_boundary() {
603 let n = u64::MAX / (1024 * 1024 * 1024);
605 assert_eq!(parse_size(&format!("{n}G")).unwrap(), n * 1024 * 1024 * 1024);
606 }
607}