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