Skip to main content

tess/
cli.rs

1use std::path::PathBuf;
2use clap::Parser;
3
4#[derive(Parser, Debug, Clone)]
5#[command(name = "tess", version, about = "A less-style terminal pager.")]
6pub struct Args {
7    /// Chop long lines instead of wrapping.
8    #[arg(short = 'S', long = "chop-long-lines", display_order = 1)]
9    pub chop: bool,
10
11    /// Force the content type for `--prettify` (otherwise auto-detected from
12    /// the filename extension and the first bytes). Values:
13    /// `auto`, `raw`, `json`, `yaml`, `toml`, `xml`, `html`, `csv`.
14    /// Setting this implies `--prettify` (unless the value is `raw`/`auto`).
15    #[arg(long = "content-type", value_name = "TYPE", display_order = 2)]
16    pub content_type: Option<String>,
17
18    /// With `--filter`, dim non-matching lines instead of hiding them. Keeps
19    /// surrounding context visible.
20    #[arg(long = "dim", display_order = 3)]
21    pub dim: bool,
22
23    /// Render each parsed line through this template instead of showing the
24    /// raw line. Syntax: `<fieldname>` placeholders, `\<` for literal `<`,
25    /// `\\` for literal `\`. Example: `--display '[<time>] <status> <msg>'`.
26    /// Overrides the format's `display` key (if set). Requires `--format`.
27    /// Search still matches against the raw line.
28    #[arg(long = "display", value_name = "TEMPLATE", display_order = 4)]
29    pub display: Option<String>,
30
31    /// Print a curated list of usage examples and exit.
32    #[arg(long = "examples", display_order = 5)]
33    pub examples: bool,
34
35    /// Filter visible lines by parsed field. Repeatable; multiple filters AND.
36    /// Operators: `=` (exact), `!=` (exact ≠), `~` (regex), `!~` (regex ≠),
37    /// `<`, `<=`, `>`, `>=` (numeric if both sides parse as numbers, else
38    /// lexicographic). Examples: `--filter status=500`, `--filter ip~^10\.`,
39    /// `--filter 'status>=500'` (quote `<` and `>` to avoid shell redirection).
40    /// Requires `--format`.
41    #[arg(long = "filter", value_name = "FIELD<op>VALUE", display_order = 6)]
42    pub filter: Vec<String>,
43
44    /// Follow mode: keep watching the source for new bytes (like `tail -f`).
45    /// Jumps to the bottom on startup. Toggle with Shift-F at runtime.
46    #[arg(short = 'f', long = "follow", display_order = 7)]
47    pub follow: bool,
48
49    /// Apply a named log format (built-in or user-defined in
50    /// ~/.config/tess/formats.toml). Required by `--filter`.
51    #[arg(long = "format", value_name = "NAME", display_order = 8)]
52    pub format: Option<String>,
53
54    /// Filter visible lines by regex against the raw line. Repeatable;
55    /// multiple `--grep` arguments AND. Works on any input — no `--format`
56    /// required. Composes with `--filter` (both must match) and with
57    /// `--dim` (non-matches stay visible but faded).
58    /// Example: `--grep error --grep '^\['`.
59    #[arg(long = "grep", value_name = "PATTERN", display_order = 9)]
60    pub grep: Vec<String>,
61
62    /// Show only the first N lines of the source. Mutually exclusive with --tail.
63    #[arg(long = "head", value_name = "N", conflicts_with = "tail", display_order = 10)]
64    pub head: Option<usize>,
65
66    /// Render the source as an xxd-style hex dump instead of byte-faithful
67    /// text. 16 bytes per row, offset prefix, ASCII gutter. Mutually
68    /// exclusive with parsing- and rendering-oriented flags.
69    #[arg(
70        long = "hex",
71        display_order = 11,
72        conflicts_with_all = ["filter", "grep", "prettify", "format", "display", "record_start", "prompt", "preprocess"],
73    )]
74    pub hex: bool,
75
76    /// Show line numbers.
77    #[arg(short = 'N', long = "LINE-NUMBERS", display_order = 12)]
78    pub line_numbers: bool,
79
80    /// Print available log formats and their named fields, then exit.
81    #[arg(long = "list-formats", display_order = 13)]
82    pub list_formats: bool,
83
84    /// Live mode: re-read the file when its on-disk content changes (mtime,
85    /// size, or inode). Use this for files rewritten in place — source files
86    /// being edited, files saved by an editor or AI agent. Different from
87    /// `--follow` (which watches for *appended* bytes); the two are mutually
88    /// exclusive. Press `R` inside the pager to force a reload.
89    #[arg(long = "live", conflicts_with = "follow", display_order = 14)]
90    pub live: bool,
91
92    /// Print the full user manual and exit.
93    #[arg(long = "manual", display_order = 15)]
94    pub manual: bool,
95
96    /// Ignore $LESSOPEN. Useful when LESSOPEN is exported but not wanted
97    /// for one invocation.
98    #[arg(long = "no-preprocess", conflicts_with = "preprocess", display_order = 16)]
99    pub no_preprocess: bool,
100
101    /// Non-interactive batch mode: apply --filter / --grep / --head / --tail / --prettify
102    /// to the source and write the resulting raw bytes to FILE, then exit.
103    /// Use `-` for stdout (`--stdout` is a synonym). Skips the alt-screen and
104    /// raw mode entirely. With `--follow`, doesn't exit — keeps appending
105    /// matching new bytes to FILE as they arrive (Ctrl-C to stop). Not
106    /// compatible with `--live`.
107    #[arg(short = 'o', long = "output", value_name = "FILE", display_order = 17)]
108    pub output: Option<String>,
109
110    /// Pipe the source file through this command before rendering.
111    /// Must start with `|`; `%s` is substituted with the file path.
112    /// Example: `--preprocess '|pdftotext %s -'`. Overrides $LESSOPEN.
113    #[arg(
114        long = "preprocess",
115        value_name = "CMD",
116        conflicts_with_all = ["no_preprocess", "hex", "follow", "live"],
117        display_order = 18,
118    )]
119    pub preprocess: Option<String>,
120
121    /// Pretty-print structured content (JSON, YAML, TOML, XML, HTML, CSV).
122    /// Detects the type from the filename extension or the first bytes; use
123    /// `--content-type=NAME` to override. Static files only — not allowed
124    /// with `--follow`, `--live`, or `--filter`. Toggle interactively with
125    /// `Shift-P`; force a type with `-P` then a letter (j/y/t/x/h/c).
126    #[arg(long = "prettify", display_order = 19)]
127    pub prettify: bool,
128
129    /// Replace the hardcoded status format with a templated string.
130    /// Uses the same `<field>` syntax as `--display`. Available fields:
131    /// label, top, bottom, total, pct, rec-top, rec-bottom, rec-total,
132    /// rec-block, wrap-offset, format-tag, filter-tag, grep-tag,
133    /// hide-tag, search-tag, pretty-tag, live-tag, follow-tag.
134    /// Per-format default can be set via `prompt = '...'` in formats.toml.
135    /// Mutually exclusive with --hex.
136    #[arg(long = "prompt", value_name = "TEMPLATE", conflicts_with = "hex", display_order = 20)]
137    pub prompt: Option<String>,
138
139    /// Treat lines matching REGEX as record boundaries. Lines that don't
140    /// match are joined to the preceding record. Affects search, filter,
141    /// grep, and the status line — all operate on whole records when set.
142    /// Overrides the active --format's record_start if both are present.
143    /// Without --format, this is the only way to enable records mode for
144    /// plain text. Example: --record-start '^\['
145    #[arg(long = "record-start", value_name = "REGEX", display_order = 21)]
146    pub record_start: Option<String>,
147
148    /// Synonym for `--output -`: write the batch-mode output to stdout.
149    #[arg(long = "stdout", conflicts_with = "output", display_order = 22)]
150    pub stdout: bool,
151
152    /// Tab stop width (default 8).
153    #[arg(long = "tab-width", default_value_t = 8, display_order = 23)]
154    pub tab_width: u8,
155
156    /// Show only the last N lines of the source. For files this skips most of
157    /// the index work — useful for huge logs. Combine with `-f` for `tail -f`.
158    /// Mutually exclusive with --head. Streaming stdin is not supported.
159    #[arg(long = "tail", value_name = "N", conflicts_with = "head", display_order = 24)]
160    pub tail: Option<usize>,
161
162    /// Files to view (only the first is opened in MVP).
163    pub files: Vec<PathBuf>,
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn parses_no_flags_no_files() {
172        let a = Args::parse_from(["tess"]);
173        assert!(!a.line_numbers);
174        assert!(!a.chop);
175        assert_eq!(a.tab_width, 8);
176        assert!(a.files.is_empty());
177    }
178
179    #[test]
180    fn parses_short_flags_and_file() {
181        let a = Args::parse_from(["tess", "-N", "-S", "foo.txt"]);
182        assert!(a.line_numbers);
183        assert!(a.chop);
184        assert_eq!(a.files, vec![PathBuf::from("foo.txt")]);
185    }
186
187    #[test]
188    fn parses_tab_width() {
189        let a = Args::parse_from(["tess", "--tab-width", "4", "x"]);
190        assert_eq!(a.tab_width, 4);
191    }
192
193    #[test]
194    fn collects_multiple_files() {
195        let a = Args::parse_from(["tess", "a", "b", "c"]);
196        assert_eq!(a.files.len(), 3);
197    }
198
199    #[test]
200    fn parses_follow_short_flag() {
201        let a = Args::parse_from(["tess", "-f", "log.txt"]);
202        assert!(a.follow);
203        assert_eq!(a.files, vec![PathBuf::from("log.txt")]);
204    }
205
206    #[test]
207    fn parses_follow_long_flag() {
208        let a = Args::parse_from(["tess", "--follow"]);
209        assert!(a.follow);
210    }
211
212    #[test]
213    fn follow_defaults_off() {
214        let a = Args::parse_from(["tess", "x"]);
215        assert!(!a.follow);
216    }
217
218    #[test]
219    fn parses_head() {
220        let a = Args::parse_from(["tess", "--head", "100", "x"]);
221        assert_eq!(a.head, Some(100));
222        assert_eq!(a.tail, None);
223    }
224
225    #[test]
226    fn parses_tail() {
227        let a = Args::parse_from(["tess", "--tail", "50", "x"]);
228        assert_eq!(a.tail, Some(50));
229        assert_eq!(a.head, None);
230    }
231
232    #[test]
233    fn head_and_tail_are_mutually_exclusive() {
234        let r = Args::try_parse_from(["tess", "--head", "10", "--tail", "20", "x"]);
235        assert!(r.is_err(), "clap should reject combining --head and --tail");
236    }
237
238    #[test]
239    fn head_tail_default_to_none() {
240        let a = Args::parse_from(["tess", "x"]);
241        assert!(a.head.is_none());
242        assert!(a.tail.is_none());
243    }
244
245    #[test]
246    fn parses_grep_repeatable_and_no_format_required() {
247        let a = Args::parse_from([
248            "tess",
249            "--grep", "error",
250            "--grep", r"^\[",
251            "log",
252        ]);
253        assert_eq!(a.grep.len(), 2);
254        assert_eq!(a.grep[0], "error");
255        assert_eq!(a.grep[1], r"^\[");
256        assert_eq!(a.format, None);
257    }
258
259    #[test]
260    fn parses_format_and_filter() {
261        let a = Args::parse_from([
262            "tess", "--format", "apache-combined",
263            "--filter", "status=500",
264            "--filter", "ip~^10\\.",
265            "log",
266        ]);
267        assert_eq!(a.format.as_deref(), Some("apache-combined"));
268        assert_eq!(a.filter.len(), 2);
269        assert_eq!(a.filter[0], "status=500");
270    }
271
272    #[test]
273    fn parses_dim() {
274        let a = Args::parse_from(["tess", "--format", "x", "--filter", "y=z", "--dim", "f"]);
275        assert!(a.dim);
276    }
277
278    #[test]
279    fn parses_list_formats() {
280        let a = Args::parse_from(["tess", "--list-formats"]);
281        assert!(a.list_formats);
282    }
283
284    #[test]
285    fn parses_manual() {
286        let a = Args::parse_from(["tess", "--manual"]);
287        assert!(a.manual);
288    }
289
290    #[test]
291    fn parses_examples() {
292        let a = Args::parse_from(["tess", "--examples"]);
293        assert!(a.examples);
294    }
295
296    #[test]
297    fn parses_live() {
298        let a = Args::parse_from(["tess", "--live", "f"]);
299        assert!(a.live);
300        assert!(!a.follow);
301    }
302
303    #[test]
304    fn live_and_follow_are_mutually_exclusive() {
305        let r = Args::try_parse_from(["tess", "--live", "--follow", "f"]);
306        assert!(r.is_err(), "clap should reject combining --live and --follow");
307    }
308
309    #[test]
310    fn parses_prettify() {
311        let a = Args::parse_from(["tess", "--prettify", "f.json"]);
312        assert!(a.prettify);
313        assert_eq!(a.content_type, None);
314    }
315
316    #[test]
317    fn parses_content_type() {
318        let a = Args::parse_from(["tess", "--content-type", "json", "f"]);
319        assert_eq!(a.content_type.as_deref(), Some("json"));
320    }
321
322    #[test]
323    fn parses_output_long_and_short() {
324        let a = Args::parse_from(["tess", "-o", "/tmp/out.txt", "f"]);
325        assert_eq!(a.output.as_deref(), Some("/tmp/out.txt"));
326        let b = Args::parse_from(["tess", "--output", "/tmp/out.txt", "f"]);
327        assert_eq!(b.output.as_deref(), Some("/tmp/out.txt"));
328    }
329
330    #[test]
331    fn parses_stdout_flag() {
332        let a = Args::parse_from(["tess", "--stdout", "f"]);
333        assert!(a.stdout);
334        assert_eq!(a.output, None);
335    }
336
337    #[test]
338    fn output_and_stdout_are_mutually_exclusive() {
339        let r = Args::try_parse_from(["tess", "-o", "x", "--stdout", "f"]);
340        assert!(r.is_err(), "clap should reject combining --output and --stdout");
341    }
342
343    #[test]
344    fn help_lists_flags_in_alphabetical_order() {
345        use clap::CommandFactory;
346        let mut cmd = Args::command();
347        let help = cmd.render_help().to_string();
348
349        let expected = [
350            "--chop-long-lines",
351            "--content-type",
352            "--dim",
353            "--display",
354            "--examples",
355            "--filter",
356            "--follow",
357            "--format",
358            "--grep",
359            "--head",
360            "--hex",
361            "--LINE-NUMBERS",
362            "--list-formats",
363            "--live",
364            "--manual",
365            "--no-preprocess",
366            "--output",
367            "--preprocess",
368            "--prettify",
369            "--prompt",
370            "--record-start",
371            "--stdout",
372            "--tab-width",
373            "--tail",
374        ];
375        let listed: Vec<&str> = help
376            .lines()
377            .map(str::trim_start)
378            .filter(|l| l.starts_with('-'))
379            .filter_map(|l| {
380                l.split(|c: char| c.is_whitespace() || c == ',')
381                    .find(|tok| expected.contains(tok))
382            })
383            .collect();
384        assert_eq!(listed, expected, "help long-flag order should be alphabetical");
385    }
386}