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