tess/cli.rs
1use std::path::PathBuf;
2use clap::Parser;
3use clap::builder::styling::{AnsiColor, Color, Style};
4use clap::builder::Styles;
5
6const HELP_STYLES: Styles = Styles::styled()
7 .header(Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Yellow))))
8 .usage(Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Yellow))))
9 .literal(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))))
10 .placeholder(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))));
11
12#[derive(Parser, Debug, Clone)]
13#[command(name = "tess", version, about = "A less-style terminal pager.", styles = HELP_STYLES)]
14// Repeated scalar flags take the last value rather than erroring. This makes
15// `less`-style "last flag wins" work and, crucially, lets a CLI flag override
16// the same flag injected by a group expansion (e.g. `--mygroup --display ...`
17// overriding the group's own `display`). Repeatable flags (`--filter`,
18// `--grep`) use Append actions and are unaffected — they still accumulate.
19#[command(args_override_self = true)]
20// Fields are ordered alphabetically by long-flag name (case-insensitive) so
21// that `--help` lists them in that order — clap's derive renders options in
22// field-declaration order. The `help_lists_flags_in_alphabetical_order` test
23// enforces this; keep new flags in their sorted slot.
24//
25// `IGNORE_CASE` (-I) and `QUIT_AT_EOF` (-E) are intentionally upper-case to
26// mirror less's case-distinguished flag pairs (`-i`/`-I`, `-e`/`-E`) and to
27// stay distinct from their lower-case `ignore_case`/`quit_at_eof` siblings.
28#[allow(non_snake_case)]
29pub struct Args {
30 /// Render images with Unicode half-blocks (▀, fg=top pixel, bg=bottom
31 /// pixel) for ~2× vertical detail instead of the default character ramp.
32 #[arg(long = "blocks")]
33 pub blocks: bool,
34
35 /// Chop long lines instead of wrapping.
36 #[arg(short = 'S', long = "chop-long-lines")]
37 pub chop: bool,
38
39 /// Enable interactive clipboard yank: `:yank` copies the current line to the
40 /// system clipboard. Bind a key via `clipboard-yank-line` in keys.toml
41 /// (unbound by default, so it never clobbers existing keys).
42 #[arg(long = "clipboard")]
43 pub clipboard: bool,
44
45 /// Force the content type for `--prettify` (otherwise auto-detected from
46 /// the filename extension and the first bytes). Values:
47 /// `auto`, `raw`, `json`, `yaml`, `toml`, `xml`, `html`, `csv`.
48 /// Setting this implies `--prettify` (unless the value is `raw`/`auto`).
49 #[arg(long = "content-type", value_name = "TYPE")]
50 pub content_type: Option<String>,
51
52 /// With `--filter`, dim non-matching lines instead of hiding them. Keeps
53 /// surrounding context visible.
54 #[arg(long = "dim")]
55 pub dim: bool,
56
57 /// Render each parsed line through this template instead of showing the
58 /// raw line. Syntax: `<fieldname>` placeholders, `\<` for literal `<`,
59 /// `\\` for literal `\`. Example: `--display '[<time>] <status> <msg>'`.
60 /// Overrides the format's `display` key (if set). Requires `--format`.
61 /// Search still matches against the raw line.
62 #[arg(long = "display", value_name = "TEMPLATE")]
63 pub display: Option<String>,
64
65 /// Print a curated list of usage examples and exit.
66 #[arg(long = "examples")]
67 pub examples: bool,
68
69 /// In follow mode with piped stdin, exit when the upstream writer
70 /// closes the pipe. Default behavior (off): tess remains open on
71 /// the captured content after stdin EOF. Mirrors
72 /// `less --exit-follow-on-close`.
73 #[arg(long = "exit-follow-on-close")]
74 pub exit_follow_on_close: bool,
75
76 /// Filter visible lines by parsed field. Repeatable; multiple filters AND.
77 /// Operators: `=` (exact), `!=` (exact ≠), `~` (regex), `!~` (regex ≠),
78 /// `<`, `<=`, `>`, `>=` (numeric if both sides parse as numbers, else
79 /// lexicographic). Examples: `--filter status=500`, `--filter ip~^10\.`,
80 /// `--filter 'status>=500'` (quote `<` and `>` to avoid shell redirection).
81 /// Requires `--format`.
82 #[arg(long = "filter", value_name = "FIELD<op>VALUE")]
83 pub filter: Vec<String>,
84
85 /// Follow mode: keep watching the source for new bytes (like `tail -f`).
86 /// Jumps to the bottom on startup. Toggle with Shift-F at runtime.
87 #[arg(short = 'f', long = "follow")]
88 pub follow: bool,
89
90 /// Follow the file by path rather than by descriptor (matches
91 /// `tail -F` / `less --follow-name`). `tess` already does this —
92 /// rotation and truncation are detected on every poll and the
93 /// source re-opens by path (since 0.25.0). This flag is accepted
94 /// for compatibility and currently has no behavioral effect.
95 #[arg(long = "follow-name")]
96 pub follow_name: bool,
97
98 /// In follow mode, any user motion (scroll, page, goto-line) suspends
99 /// following. Re-engage with Shift-F. Default off: today's behavior
100 /// (movement keeps follow on; auto-scroll suspended while the viewport
101 /// is not at bottom). Matches `less +F` semantics when enabled.
102 #[arg(long = "follow-suspend-on-motion")]
103 pub follow_suspend_on_motion: bool,
104
105 /// Apply a named log format (built-in or user-defined in
106 /// ~/.config/tess/formats.toml). Required by `--filter`.
107 #[arg(long = "format", value_name = "NAME")]
108 pub format: Option<String>,
109
110 /// Use the system clipboard contents as input (like `pbpaste | tess`).
111 /// Mutually exclusive with file arguments and piped stdin.
112 #[arg(long = "from-clipboard", conflicts_with = "files")]
113 pub from_clipboard: bool,
114
115 /// Filter visible lines by regex against the raw line. Repeatable;
116 /// multiple `--grep` arguments AND. Works on any input — no `--format`
117 /// required. Composes with `--filter` (both must match) and with
118 /// `--dim` (non-matches stay visible but faded).
119 /// Example: `--grep error --grep '^\['`.
120 #[arg(long = "grep", value_name = "PATTERN")]
121 pub grep: Vec<String>,
122
123 /// Show only the first N lines of the source. Mutually exclusive with --tail.
124 #[arg(long = "head", value_name = "N", conflicts_with = "tail")]
125 pub head: Option<usize>,
126
127 /// Pin the top L source lines (and the left C columns, when
128 /// horizontal scroll is supported) at the top of the viewport.
129 /// Form: `L` or `L,C`. Default `0,0` (off). Mirrors `less --header`.
130 /// Runtime adjustment: `:header L [C]`.
131 #[arg(long = "header", value_name = "L[,C]")]
132 pub header: Option<String>,
133
134 /// Render the source as an xxd-style hex dump instead of byte-faithful
135 /// text. 16 bytes per row, offset prefix, ASCII gutter. Mutually
136 /// exclusive with parsing- and rendering-oriented flags.
137 #[arg(
138 long = "hex",
139 conflicts_with_all = ["filter", "grep", "prettify", "format", "display", "record_start", "prompt", "preprocess", "or_filter", "or_grep", "or_group"],
140 )]
141 pub hex: bool,
142
143 /// Hex characters per group in `--hex` mode. One of 2, 4, 8, 16, 32
144 /// (default 4, matching `xxd`). 32 means the whole row as a single
145 /// group with no spacing between hex pairs. Requires `--hex`. Can be
146 /// changed at runtime with `:hex N`.
147 #[arg(
148 long = "hex-group",
149 value_name = "N",
150 default_value_t = 4,
151 requires = "hex",
152 )]
153 pub hex_group: usize,
154
155 /// Smart-case search. `/`, `?`, `--grep`, and `--filter`'s `~` / `!~`
156 /// operators match case-insensitively unless the pattern contains an
157 /// uppercase character. Mirrors `less -i` / ripgrep / vim smartcase.
158 /// Mutually exclusive with `-I`. Runtime toggle: `:case`.
159 #[arg(short = 'i', long = "ignore-case", conflicts_with = "IGNORE_CASE")]
160 pub ignore_case: bool,
161
162 /// Force case-insensitive search regardless of pattern case. Mirrors
163 /// `less -I`. Mutually exclusive with `-i`.
164 #[arg(short = 'I', long = "IGNORE-CASE")]
165 pub IGNORE_CASE: bool,
166
167 /// Target width in columns for image rendering. Defaults to the terminal
168 /// width interactively, or 80 when exporting to a file/stdout.
169 #[arg(long = "image-width", value_name = "N")]
170 pub image_width: Option<usize>,
171
172 /// Incremental search: in the `/`/`?` prompt, jump to and highlight the
173 /// first match as you type (from where the prompt opened). Esc restores the
174 /// original position; Enter commits. Default off. Mirrors `less --incsearch`.
175 /// Runtime toggle: `:incsearch`.
176 #[arg(long = "incsearch")]
177 pub incsearch: bool,
178
179 /// Show line numbers.
180 #[arg(short = 'N', long = "LINE-NUMBERS")]
181 pub line_numbers: bool,
182
183 /// Print available log formats and their named fields, then exit.
184 #[arg(long = "list-formats")]
185 pub list_formats: bool,
186
187 /// Live mode: re-read the file when its on-disk content changes (mtime,
188 /// size, or inode). Use this for files rewritten in place — source files
189 /// being edited, files saved by an editor or AI agent. Different from
190 /// `--follow` (which watches for *appended* bytes); the two are mutually
191 /// exclusive. Press `R` inside the pager to force a reload.
192 #[arg(long = "live", conflicts_with = "follow")]
193 pub live: bool,
194
195 /// Print the full user manual and exit.
196 #[arg(long = "manual")]
197 pub manual: bool,
198
199 /// Enable mouse capture: click rows in the file picker / help overlay,
200 /// and scrollwheel scrolls the body. Trade-off: most terminals disable
201 /// their native text selection while mouse capture is on.
202 #[arg(long = "mouse")]
203 pub mouse: bool,
204
205 /// Show raw control bytes as `^X` glyphs (pre-0.18 default). Disables
206 /// SGR / OSC interpretation. Honoured also by the `NO_COLOR` environment
207 /// variable (any non-empty value) and `CLICOLOR=0`.
208 #[arg(long = "no-color")]
209 pub no_color: bool,
210
211 /// Disable search-match highlighting by default. Search still
212 /// navigates (`n` / `N` jump to matches); the visual reverse-video
213 /// highlight is suppressed. Runtime toggle: `:hlsearch` / `:nohlsearch`.
214 /// Mirrors `less -G`.
215 #[arg(short = 'G', long = "no-hilite-search")]
216 pub no_hilite_search: bool,
217
218 /// Treat a detected image file as raw/normal text instead of rendering it
219 /// as ASCII art. Has no effect on non-image inputs.
220 #[arg(long = "no-image")]
221 pub no_image: bool,
222
223 /// Don't enter the alt-screen on startup. Content remains in
224 /// terminal scrollback after exit. Crucial for piped use and
225 /// debugging. Mirrors `less -X` / `--no-init`.
226 #[arg(short = 'X', long = "no-init")]
227 pub no_init: bool,
228
229 /// Ignore $LESSOPEN. Useful when LESSOPEN is exported but not wanted
230 /// for one invocation.
231 #[arg(long = "no-preprocess", conflicts_with = "preprocess")]
232 pub no_preprocess: bool,
233
234 /// OR-filter: a field condition where matching ANY condition in its
235 /// OR-group is enough (the group is satisfied). AND'd with the required
236 /// --filter/--grep. Joins the group set by the most recent --or-group, or
237 /// `default` if none. Requires --format. Repeatable.
238 #[arg(long = "or-filter", value_name = "FIELD<op>VALUE")]
239 pub or_filter: Vec<String>,
240
241 /// OR-grep: a raw-regex condition where matching ANY condition in its
242 /// OR-group is enough. Works on any input. Joins the group set by the most
243 /// recent --or-group, or `default` if none. Repeatable.
244 #[arg(long = "or-grep", value_name = "PATTERN")]
245 pub or_grep: Vec<String>,
246
247 /// Open an OR-group: subsequent --or-filter/--or-grep join NAME until the
248 /// next --or-group. Conditions before any marker form the `default` group.
249 /// Every non-empty group must have ≥1 match (groups are AND'd). Repeatable.
250 #[arg(long = "or-group", value_name = "NAME")]
251 pub or_group: Vec<String>,
252
253 /// Non-interactive batch mode: apply --filter / --grep / --head / --tail / --prettify
254 /// to the source and write the resulting raw bytes to FILE, then exit.
255 /// Use `-` for stdout (`--stdout` is a synonym). Skips the alt-screen and
256 /// raw mode entirely. With `--follow`, doesn't exit — keeps appending
257 /// matching new bytes to FILE as they arrive (Ctrl-C to stop). Not
258 /// compatible with `--live`.
259 #[arg(short = 'o', long = "output", value_name = "FILE")]
260 pub output: Option<String>,
261
262 /// Pipe the source file through this command before rendering.
263 /// Must start with `|`; `%s` is substituted with the file path.
264 /// Example: `--preprocess '|pdftotext %s -'`. Overrides $LESSOPEN.
265 #[arg(
266 long = "preprocess",
267 value_name = "CMD",
268 conflicts_with_all = ["no_preprocess", "hex", "follow", "live"],
269 )]
270 pub preprocess: Option<String>,
271
272 /// Pretty-print structured content (JSON, YAML, TOML, XML, HTML, CSV).
273 /// Detects the type from the filename extension or the first bytes; use
274 /// `--content-type=NAME` to override. Static files only — not allowed
275 /// with `--follow`, `--live`, or `--filter`. Toggle interactively with
276 /// `Shift-P`; force a type with `-P` then a letter (j/y/t/x/h/c).
277 #[arg(long = "prettify")]
278 pub prettify: bool,
279
280 /// Replace the hardcoded status format with a templated string.
281 /// Uses the same `<field>` syntax as `--display`. Available fields:
282 /// label, top, bottom, total, pct, rec-top, rec-bottom, rec-total,
283 /// rec-block, wrap-offset, format-tag, filter-tag, grep-tag,
284 /// hide-tag, search-tag, pretty-tag, live-tag, follow-tag.
285 /// Per-format default can be set via `prompt = '...'` in formats.toml.
286 /// Mutually exclusive with --hex.
287 #[arg(long = "prompt", value_name = "TEMPLATE", conflicts_with = "hex")]
288 pub prompt: Option<String>,
289
290 /// Style for `--prompt` output (and per-format `prompt_style`). Same
291 /// grammar as `--status-style`. Default: empty (no extra styling on top
292 /// of what the prompt template itself emits).
293 #[arg(long = "prompt-style", value_name = "SPEC", default_value = "")]
294 pub prompt_style: String,
295
296 /// Quit when the user tries to scroll forward past end-of-file for
297 /// the second time. Mirrors `less -e`. Mutually exclusive with `-E`.
298 #[arg(short = 'e', long = "quit-at-eof", conflicts_with = "QUIT_AT_EOF")]
299 pub quit_at_eof: bool,
300
301 /// Quit the first time end-of-file is reached. Mirrors `less -E`.
302 #[arg(short = 'E', long = "QUIT-AT-EOF")]
303 pub QUIT_AT_EOF: bool,
304
305 /// Exit immediately (without paging) if the entire source fits on
306 /// one screen. Ignored with piped stdin in follow mode. Mirrors
307 /// `less -F`.
308 #[arg(short = 'F', long = "quit-if-one-screen")]
309 pub quit_if_one_screen: bool,
310
311 /// Accepted for `less` compatibility. tess always exits on Ctrl-C
312 /// (Ctrl-C → Command::Quit in the input table), so this flag is a
313 /// no-op. Provided so existing `less` invocations work unchanged.
314 #[arg(short = 'K', long = "quit-on-intr")]
315 pub quit_on_intr: bool,
316
317 /// Pass every byte to the terminal raw, including cursor moves and
318 /// non-SGR escape sequences. Risky: scroll math may break on long lines.
319 /// Less-style -r. Mutually exclusive with --no-color.
320 #[arg(short = 'r', long = "raw-control-chars", conflicts_with = "no_color")]
321 pub raw_control_chars: bool,
322
323 /// Accept `less -R`: interpret SGR/OSC color escapes, strip other control
324 /// sequences — which is tess's default. Provided for drop-in `less -R`
325 /// compatibility. Distinct from `-r` (full raw) and `--no-color`.
326 #[arg(short = 'R', long = "RAW-CONTROL-CHARS",
327 conflicts_with_all = ["raw_control_chars", "no_color"])]
328 pub RAW_CONTROL_CHARS: bool,
329
330 /// Treat lines matching REGEX as record boundaries. Lines that don't
331 /// match are joined to the preceding record. Affects search, filter,
332 /// grep, and the status line — all operate on whole records when set.
333 /// Overrides the active --format's record_start if both are present.
334 /// Without --format, this is the only way to enable records mode for
335 /// plain text. Example: --record-start '^\['
336 #[arg(long = "record-start", value_name = "REGEX")]
337 pub record_start: Option<String>,
338
339 /// Character to show at the right edge of a chopped line (`-S` chop
340 /// mode) indicating "more content right". Default `>`. Pass an empty
341 /// string to disable. Mirrors `less --rscroll=c`.
342 #[arg(long = "rscroll", value_name = "CHAR", default_value = ">")]
343 pub rscroll: String,
344
345 /// Column count for the ←/→ horizontal-scroll commands (default: half
346 /// screen). `0` keeps the half-screen default. Mirrors `less -#`/`--shift`.
347 #[arg(short = '#', long = "shift", value_name = "N")]
348 pub shift: Option<u16>,
349
350 /// Collapse runs of two or more consecutive blank lines into a
351 /// single blank line at display time. Real line numbers, search,
352 /// and tag jumps are unaffected (they reference the original
353 /// count). Mirrors `less -s`.
354 #[arg(short = 's', long = "squeeze-blank-lines")]
355 pub squeeze_blanks: bool,
356
357 /// Show a 1-column status gutter at the far left: a mark letter on marked
358 /// lines, else `*` on lines containing a current-search match. Stays fixed
359 /// under horizontal scroll. No-op in --hex/-r/image modes. Mirrors `less -J`.
360 #[arg(short = 'J', long = "status-column")]
361 pub status_column: bool,
362
363 /// Style for the status row. Comma-separated tokens: `bold`, `dim`,
364 /// `italic`, `underline`, `reverse`, `fg=COLOR`, `bg=COLOR`. COLOR is a
365 /// named color (`black`..`white`, optional `bright-` prefix), `#RRGGBB`,
366 /// or an indexed value (0–255). Empty string disables theming.
367 /// Default: `reverse`.
368 #[arg(long = "status-style", value_name = "SPEC", default_value = "reverse")]
369 pub status_style: String,
370
371 /// Synonym for `--output -`: write the batch-mode output to stdout.
372 #[arg(long = "stdout", conflicts_with = "output")]
373 pub stdout: bool,
374
375 /// Tab stop width (default 8).
376 #[arg(long = "tab-width", default_value_t = 8)]
377 pub tab_width: u8,
378
379 /// Tab stops as a comma-separated column list, e.g. `-x4,8,16`. A single
380 /// value is equivalent to `--tab-width`. With multiple values, tabs advance
381 /// to the next listed column; past the last stop the final interval
382 /// repeats. Overrides `--tab-width`. Mirrors `less -x`.
383 #[arg(short = 'x', long = "tabs", value_name = "LIST")]
384 pub tabs: Option<String>,
385
386 /// Jump to the tag NAME at startup (requires a tags file).
387 #[arg(short = 't', long = "tag", value_name = "NAME")]
388 pub tag: Option<String>,
389
390 /// Path to the tags file. Default: walk up from CWD looking for `tags`.
391 #[arg(short = 'T', long = "tag-file", value_name = "PATH")]
392 pub tag_file: Option<std::path::PathBuf>,
393
394 /// Show only the last N lines of the source. For files this skips most of
395 /// the index work — useful for huge logs. Combine with `-f` for `tail -f`.
396 /// Mutually exclusive with --head. Streaming stdin is not supported.
397 #[arg(long = "tail", value_name = "N", conflicts_with = "head")]
398 pub tail: Option<usize>,
399
400 /// Batch sink: apply filters/head/tail/prettify and copy the result to the
401 /// system clipboard, then exit. Mutually exclusive with -o/--stdout.
402 #[arg(long = "to-clipboard", conflicts_with_all = ["output", "stdout"])]
403 pub to_clipboard: bool,
404
405 /// Truecolor (24-bit RGB) handling. `auto` (default) checks `$COLORTERM`
406 /// and downsamples when truecolor isn't advertised; `never` always
407 /// downsamples to the 256-color palette; `always` passes RGB through
408 /// regardless of terminal capability.
409 #[arg(long = "truecolor", value_name = "MODE", default_value = "auto")]
410 pub truecolor: String,
411
412 /// Body lines scrolled per mouse-wheel notch under `--mouse` (default 3).
413 #[arg(long = "wheel-lines", value_name = "N")]
414 pub wheel_lines: Option<u16>,
415
416 /// PageDown / PageUp step size in lines. Default: full screen
417 /// height (body rows). Half-page commands always advance by half
418 /// the screen regardless. Mirrors `less -zn` / `--window=n`.
419 #[arg(short = 'z', long = "window", value_name = "N")]
420 pub window: Option<u16>,
421
422 /// In wrap mode, break lines on whitespace boundaries instead of
423 /// mid-character when possible. Falls back to mid-character break
424 /// when no whitespace fits in the row. Mirrors `less --wordwrap`.
425 #[arg(long = "wordwrap")]
426 pub word_wrap: bool,
427
428 /// Files to view (only the first is opened in MVP).
429 pub files: Vec<PathBuf>,
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 #[test]
437 fn parses_no_flags_no_files() {
438 let a = Args::parse_from(["tess"]);
439 assert!(!a.line_numbers);
440 assert!(!a.chop);
441 assert_eq!(a.tab_width, 8);
442 assert!(a.files.is_empty());
443 }
444
445 #[test]
446 fn parses_raw_control_chars_alias() {
447 let a = Args::parse_from(["tess", "-R", "f"]);
448 assert!(a.RAW_CONTROL_CHARS);
449 }
450 #[test]
451 fn raw_control_chars_conflicts_with_raw_and_no_color() {
452 assert!(Args::try_parse_from(["tess", "-R", "-r", "f"]).is_err());
453 assert!(Args::try_parse_from(["tess", "-R", "--no-color", "f"]).is_err());
454 }
455 #[test]
456 fn parses_shift_and_wheel_lines() {
457 let a = Args::parse_from(["tess", "--shift", "12", "--wheel-lines", "5", "f"]);
458 assert_eq!(a.shift, Some(12));
459 assert_eq!(a.wheel_lines, Some(5));
460 }
461
462 #[test]
463 fn parses_short_flags_and_file() {
464 let a = Args::parse_from(["tess", "-N", "-S", "foo.txt"]);
465 assert!(a.line_numbers);
466 assert!(a.chop);
467 assert_eq!(a.files, vec![PathBuf::from("foo.txt")]);
468 }
469
470 #[test]
471 fn parses_tab_width() {
472 let a = Args::parse_from(["tess", "--tab-width", "4", "x"]);
473 assert_eq!(a.tab_width, 4);
474 }
475
476 #[test]
477 fn parses_tabs_list() {
478 let a = Args::parse_from(["tess", "--tabs", "4,8,16", "f"]);
479 assert_eq!(a.tabs.as_deref(), Some("4,8,16"));
480 let b = Args::parse_from(["tess", "-x", "4", "f"]);
481 assert_eq!(b.tabs.as_deref(), Some("4"));
482 }
483
484 #[test]
485 fn collects_multiple_files() {
486 let a = Args::parse_from(["tess", "a", "b", "c"]);
487 assert_eq!(a.files.len(), 3);
488 }
489
490 #[test]
491 fn parses_follow_short_flag() {
492 let a = Args::parse_from(["tess", "-f", "log.txt"]);
493 assert!(a.follow);
494 assert_eq!(a.files, vec![PathBuf::from("log.txt")]);
495 }
496
497 #[test]
498 fn parses_follow_long_flag() {
499 let a = Args::parse_from(["tess", "--follow"]);
500 assert!(a.follow);
501 }
502
503 #[test]
504 fn follow_defaults_off() {
505 let a = Args::parse_from(["tess", "x"]);
506 assert!(!a.follow);
507 }
508
509 #[test]
510 fn parses_head() {
511 let a = Args::parse_from(["tess", "--head", "100", "x"]);
512 assert_eq!(a.head, Some(100));
513 assert_eq!(a.tail, None);
514 }
515
516 #[test]
517 fn parses_tail() {
518 let a = Args::parse_from(["tess", "--tail", "50", "x"]);
519 assert_eq!(a.tail, Some(50));
520 assert_eq!(a.head, None);
521 }
522
523 #[test]
524 fn head_and_tail_are_mutually_exclusive() {
525 let r = Args::try_parse_from(["tess", "--head", "10", "--tail", "20", "x"]);
526 assert!(r.is_err(), "clap should reject combining --head and --tail");
527 }
528
529 #[test]
530 fn head_tail_default_to_none() {
531 let a = Args::parse_from(["tess", "x"]);
532 assert!(a.head.is_none());
533 assert!(a.tail.is_none());
534 }
535
536 #[test]
537 fn parses_grep_repeatable_and_no_format_required() {
538 let a = Args::parse_from([
539 "tess",
540 "--grep", "error",
541 "--grep", r"^\[",
542 "log",
543 ]);
544 assert_eq!(a.grep.len(), 2);
545 assert_eq!(a.grep[0], "error");
546 assert_eq!(a.grep[1], r"^\[");
547 assert_eq!(a.format, None);
548 }
549
550 #[test]
551 fn parses_format_and_filter() {
552 let a = Args::parse_from([
553 "tess", "--format", "apache-combined",
554 "--filter", "status=500",
555 "--filter", "ip~^10\\.",
556 "log",
557 ]);
558 assert_eq!(a.format.as_deref(), Some("apache-combined"));
559 assert_eq!(a.filter.len(), 2);
560 assert_eq!(a.filter[0], "status=500");
561 }
562
563 #[test]
564 fn parses_dim() {
565 let a = Args::parse_from(["tess", "--format", "x", "--filter", "y=z", "--dim", "f"]);
566 assert!(a.dim);
567 }
568
569 #[test]
570 fn parses_list_formats() {
571 let a = Args::parse_from(["tess", "--list-formats"]);
572 assert!(a.list_formats);
573 }
574
575 #[test]
576 fn parses_manual() {
577 let a = Args::parse_from(["tess", "--manual"]);
578 assert!(a.manual);
579 }
580
581 #[test]
582 fn parses_examples() {
583 let a = Args::parse_from(["tess", "--examples"]);
584 assert!(a.examples);
585 }
586
587 #[test]
588 fn parses_live() {
589 let a = Args::parse_from(["tess", "--live", "f"]);
590 assert!(a.live);
591 assert!(!a.follow);
592 }
593
594 #[test]
595 fn live_and_follow_are_mutually_exclusive() {
596 let r = Args::try_parse_from(["tess", "--live", "--follow", "f"]);
597 assert!(r.is_err(), "clap should reject combining --live and --follow");
598 }
599
600 #[test]
601 fn parses_prettify() {
602 let a = Args::parse_from(["tess", "--prettify", "f.json"]);
603 assert!(a.prettify);
604 assert_eq!(a.content_type, None);
605 }
606
607 #[test]
608 fn parses_content_type() {
609 let a = Args::parse_from(["tess", "--content-type", "json", "f"]);
610 assert_eq!(a.content_type.as_deref(), Some("json"));
611 }
612
613 #[test]
614 fn parses_output_long_and_short() {
615 let a = Args::parse_from(["tess", "-o", "/tmp/out.txt", "f"]);
616 assert_eq!(a.output.as_deref(), Some("/tmp/out.txt"));
617 let b = Args::parse_from(["tess", "--output", "/tmp/out.txt", "f"]);
618 assert_eq!(b.output.as_deref(), Some("/tmp/out.txt"));
619 }
620
621 #[test]
622 fn parses_status_column() {
623 let a = Args::parse_from(["tess", "-J", "f"]);
624 assert!(a.status_column);
625 let b = Args::parse_from(["tess", "--status-column", "f"]);
626 assert!(b.status_column);
627 let c = Args::parse_from(["tess", "f"]);
628 assert!(!c.status_column, "status_column defaults off");
629 }
630
631 #[test]
632 fn parses_stdout_flag() {
633 let a = Args::parse_from(["tess", "--stdout", "f"]);
634 assert!(a.stdout);
635 assert_eq!(a.output, None);
636 }
637
638 #[test]
639 fn output_and_stdout_are_mutually_exclusive() {
640 let r = Args::try_parse_from(["tess", "-o", "x", "--stdout", "f"]);
641 assert!(r.is_err(), "clap should reject combining --output and --stdout");
642 }
643
644 #[test]
645 fn parses_mouse_flag() {
646 let a = Args::parse_from(["tess", "--mouse", "f"]);
647 assert!(a.mouse);
648 }
649
650 #[test]
651 fn mouse_defaults_off() {
652 let a = Args::parse_from(["tess", "f"]);
653 assert!(!a.mouse);
654 }
655
656 #[test]
657 fn parses_no_image_flag() {
658 let a = Args::parse_from(["tess", "--no-image", "cat.png"]);
659 assert!(a.no_image);
660 }
661
662 #[test]
663 fn parses_blocks_flag() {
664 let a = Args::parse_from(["tess", "--blocks", "cat.png"]);
665 assert!(a.blocks);
666 }
667
668 #[test]
669 fn parses_image_width() {
670 let a = Args::parse_from(["tess", "--image-width", "120", "cat.png"]);
671 assert_eq!(a.image_width, Some(120));
672 }
673
674 #[test]
675 fn parses_incsearch() {
676 let a = Args::parse_from(["tess", "--incsearch", "f"]);
677 assert!(a.incsearch);
678 }
679
680 #[test]
681 fn incsearch_defaults_off() {
682 let a = Args::parse_from(["tess", "f"]);
683 assert!(!a.incsearch);
684 }
685
686 #[test]
687 fn image_flags_default_off() {
688 let a = Args::parse_from(["tess", "f"]);
689 assert!(!a.no_image);
690 assert!(!a.blocks);
691 assert_eq!(a.image_width, None);
692 }
693
694 #[test]
695 fn repeated_scalar_flag_takes_last_value() {
696 // args_override_self: a group can inject `--display X` and a later CLI
697 // `--display Y` wins instead of clap erroring "cannot be used multiple
698 // times". Also covers plain `less`-style last-wins.
699 let a = Args::parse_from(["tess", "--display", "X", "--display", "Y", "--format", "f"]);
700 assert_eq!(a.display.as_deref(), Some("Y"));
701 let b = Args::parse_from(["tess", "--tail", "5", "--tail", "1", "x"]);
702 assert_eq!(b.tail, Some(1));
703 }
704
705 #[test]
706 fn repeatable_flags_still_accumulate_with_override_self() {
707 // args_override_self must not collapse Append-action Vec flags.
708 let a = Args::parse_from(["tess", "--grep", "a", "--grep", "b", "x"]);
709 assert_eq!(a.grep, vec!["a".to_string(), "b".to_string()]);
710 }
711
712 #[test]
713 fn parses_or_flags_repeatable() {
714 let a = Args::parse_from([
715 "tess",
716 "--or-grep", "failed",
717 "--or-group", "svc",
718 "--or-filter", "lvl=ERROR",
719 "x",
720 ]);
721 assert_eq!(a.or_grep, vec!["failed".to_string()]);
722 assert_eq!(a.or_group, vec!["svc".to_string()]);
723 assert_eq!(a.or_filter, vec!["lvl=ERROR".to_string()]);
724 }
725
726 #[test]
727 fn or_flags_conflict_with_hex() {
728 let r = Args::try_parse_from(["tess", "--hex", "--or-grep", "x", "f"]);
729 assert!(r.is_err(), "clap should reject --hex with --or-grep");
730 }
731
732 #[test]
733 fn parses_clipboard_flags() {
734 assert!(Args::parse_from(["tess", "--clipboard", "f"]).clipboard);
735 assert!(Args::parse_from(["tess", "--from-clipboard"]).from_clipboard);
736 assert!(Args::parse_from(["tess", "--to-clipboard", "f"]).to_clipboard);
737 }
738 #[test]
739 fn clipboard_sink_conflicts() {
740 assert!(Args::try_parse_from(["tess", "--to-clipboard", "--stdout", "f"]).is_err());
741 assert!(Args::try_parse_from(["tess", "--to-clipboard", "-o", "x", "f"]).is_err());
742 }
743 #[test]
744 fn from_clipboard_conflicts_with_files() {
745 assert!(Args::try_parse_from(["tess", "--from-clipboard", "f"]).is_err());
746 }
747
748 #[test]
749 fn help_lists_flags_in_alphabetical_order() {
750 use clap::CommandFactory;
751 let mut cmd = Args::command();
752 let help = cmd.render_help().to_string();
753
754 // The full set of long flags, in the order we expect `--help` to list
755 // them: alphabetical by long name, case-insensitive. clap's auto-added
756 // --help / --version are excluded (they're not in this list, so the
757 // first-token scan below skips their lines).
758 let expected = [
759 "--blocks",
760 "--chop-long-lines",
761 "--clipboard",
762 "--content-type",
763 "--dim",
764 "--display",
765 "--examples",
766 "--exit-follow-on-close",
767 "--filter",
768 "--follow",
769 "--follow-name",
770 "--follow-suspend-on-motion",
771 "--format",
772 "--from-clipboard",
773 "--grep",
774 "--head",
775 "--header",
776 "--hex",
777 "--hex-group",
778 "--ignore-case",
779 "--IGNORE-CASE",
780 "--image-width",
781 "--incsearch",
782 "--LINE-NUMBERS",
783 "--list-formats",
784 "--live",
785 "--manual",
786 "--mouse",
787 "--no-color",
788 "--no-hilite-search",
789 "--no-image",
790 "--no-init",
791 "--no-preprocess",
792 "--or-filter",
793 "--or-grep",
794 "--or-group",
795 "--output",
796 "--preprocess",
797 "--prettify",
798 "--prompt",
799 "--prompt-style",
800 "--quit-at-eof",
801 "--QUIT-AT-EOF",
802 "--quit-if-one-screen",
803 "--quit-on-intr",
804 "--raw-control-chars",
805 "--RAW-CONTROL-CHARS",
806 "--record-start",
807 "--rscroll",
808 "--shift",
809 "--squeeze-blank-lines",
810 "--status-column",
811 "--status-style",
812 "--stdout",
813 "--tab-width",
814 "--tabs",
815 "--tag",
816 "--tag-file",
817 "--tail",
818 "--to-clipboard",
819 "--truecolor",
820 "--wheel-lines",
821 "--window",
822 "--wordwrap",
823 ];
824
825 // Confirm `expected` is itself sorted case-insensitively — this guards
826 // against a typo here masking a real ordering regression in the struct.
827 let mut sorted = expected.to_vec();
828 sorted.sort_by_key(|s| s.trim_start_matches('-').to_ascii_lowercase());
829 assert_eq!(
830 expected.to_vec(),
831 sorted,
832 "the `expected` list must itself be in case-insensitive alphabetical order"
833 );
834
835 // Walk the rendered help line by line. For each option line (after
836 // trimming, it starts with '-'), take the first `--long` token that is
837 // one of our flags. Because the flag name always precedes its own
838 // description on the line, embedded `--flag` references in descriptions
839 // are never matched first.
840 let listed: Vec<&str> = help
841 .lines()
842 .map(str::trim_start)
843 .filter(|l| l.starts_with('-'))
844 .filter_map(|l| {
845 l.split(|c: char| c.is_whitespace() || c == ',')
846 .find(|tok| expected.contains(tok))
847 })
848 .collect();
849 assert_eq!(listed, expected, "help long-flag order should be alphabetical");
850 }
851}