seer-cli 0.52.1

Interactive CLI for Seer domain name utilities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Parser for the `:` command line. Pure — returns a `CmdOutcome` the App
//! interprets. Mirrors the CLI/REPL command surface.

use seer_core::RecordType;

use crate::dig_args::{self, DigFlags};
use crate::tui::lenses;
use crate::tui::theme::Theme;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CmdOutcome {
    Noop,
    Quit,
    Help,
    Copy,
    SetFormat(String),
    BadFormat,
    /// `theme <name>` with a name `Theme::from_name` accepts.
    SetTheme(String),
    /// `theme` with a missing or unknown name.
    BadTheme,
    /// Switch to a lens (by cmd alias / key), optionally looking up a target.
    Lens {
        lens: String,
        target: Option<String>,
    },
    /// `lookup <domain>` or a bare domain.
    Lookup(String),
    /// `diff a.com b.com` — compare two domains.
    Diff {
        a: String,
        b: String,
    },
    /// `compare domain.com ns-a ns-b` — compare DNS between two nameservers.
    Compare {
        domain: String,
        a: String,
        b: String,
    },
    /// `dig [@server] <domain> [type] [+trace]` — the CLI/REPL dig syntax,
    /// for the one record type (default `A`) the DNS lens shows.
    Dig {
        domain: String,
        record_type: RecordType,
        /// `@server`; `None` keeps the lens's current nameserver.
        server: Option<String>,
        /// `+trace`: open the Trace tab rather than Records.
        trace: bool,
    },
    /// `watch add <domain>` / `watch remove <domain>` — edit the watchlist.
    WatchMutate {
        add: Option<String>,
        remove: Option<String>,
    },
    /// A recognized command with bad arguments; the message is shown as-is.
    Invalid(String),
    Unknown(String),
}

pub fn parse(raw: &str) -> CmdOutcome {
    let line = raw.trim();
    if line.is_empty() {
        return CmdOutcome::Noop;
    }
    let parts: Vec<&str> = line.split_whitespace().collect();
    let head = parts[0].to_lowercase();

    match head.as_str() {
        "q" | "quit" | "exit" => return CmdOutcome::Quit,
        "help" | "h" | "?" => return CmdOutcome::Help,
        "copy" | "yank" | "y" => return CmdOutcome::Copy,
        "set" => {
            let what = parts.get(1).map(|s| s.to_lowercase()).unwrap_or_default();
            let val = parts.get(2).map(|s| s.to_lowercase()).unwrap_or_default();
            if what == "output" || what == "format" {
                if matches!(val.as_str(), "human" | "json" | "yaml" | "markdown") {
                    return CmdOutcome::SetFormat(val);
                }
                return CmdOutcome::BadFormat;
            }
            return CmdOutcome::Unknown(line.to_string());
        }
        "theme" => {
            let val = parts.get(1).map(|s| s.to_lowercase()).unwrap_or_default();
            if Theme::from_name(&val).is_some() {
                return CmdOutcome::SetTheme(val);
            }
            return CmdOutcome::BadTheme;
        }
        "lookup" | "info" => {
            return match parts.get(1) {
                Some(t) => CmdOutcome::Lookup((*t).to_string()),
                None => CmdOutcome::Unknown(line.to_string()),
            };
        }
        _ => {}
    }

    if head == "diff" {
        return match (parts.get(1), parts.get(2)) {
            (Some(a), Some(b)) => CmdOutcome::Diff {
                a: a.to_string(),
                b: b.to_string(),
            },
            _ => CmdOutcome::Unknown(line.to_string()),
        };
    }
    if head == "compare" {
        return match (parts.get(1), parts.get(2), parts.get(3)) {
            (Some(d), Some(a), Some(b)) => CmdOutcome::Compare {
                domain: d.to_string(),
                a: a.to_string(),
                b: b.to_string(),
            },
            _ => CmdOutcome::Unknown(line.to_string()),
        };
    }
    if head == "dig" || head == "dns" {
        if parts.len() == 1 {
            return CmdOutcome::Lens {
                lens: head,
                target: None,
            };
        }
        return dig(&parts[1..]);
    }

    // Global lenses (no target domain): their arguments are subcommands, and
    // must never be mistaken for a domain — that would clobber the session
    // target with e.g. "add".
    if head == "watch" {
        let sub = parts.get(1).map(|s| s.to_lowercase());
        return match (sub.as_deref(), parts.get(2), parts.len()) {
            (None, _, _) | (Some("list"), None, 2) => CmdOutcome::Lens {
                lens: head,
                target: None,
            },
            (Some("add"), Some(d), 3) => CmdOutcome::WatchMutate {
                add: Some(d.to_string()),
                remove: None,
            },
            (Some("remove" | "rm"), Some(d), 3) => CmdOutcome::WatchMutate {
                add: None,
                remove: Some(d.to_string()),
            },
            _ => CmdOutcome::Invalid("usage: watch [list] · watch add|remove <domain>".to_string()),
        };
    }
    if head == "history" || head == "bulk" {
        if parts.len() > 1 {
            let usage = if head == "history" {
                "usage: history (in the pane: ↵ replay · c twice clears all)"
            } else {
                "usage: bulk (in the pane: d domains · f file · r run)"
            };
            return CmdOutcome::Invalid(usage.to_string());
        }
        return CmdOutcome::Lens {
            lens: head,
            target: None,
        };
    }

    // A known lens command (whois, ssl, status, prop, rdap, ...).
    if lenses::find_by_cmd_or_key(&head).is_some() {
        return CmdOutcome::Lens {
            lens: head,
            target: parts.get(1).map(|s| s.to_string()),
        };
    }

    // A bare domain (contains a dot).
    if head.contains('.') {
        return CmdOutcome::Lookup(head);
    }

    CmdOutcome::Unknown(line.to_string())
}

/// `dig …` through the grammar the CLI and REPL share ([`dig_args`]),
/// so the same line means the same query everywhere, then narrowed to what
/// the DNS lens shows: one record type, as a full answer.
fn dig(args: &[&str]) -> CmdOutcome {
    let args = match dig_args::parse(args, DigFlags::default()) {
        Ok(args) => args,
        Err(message) => return CmdOutcome::Invalid(message),
    };
    if args.short {
        return CmdOutcome::Invalid(
            "+short prints bare values on the command line; the lens shows the whole answer"
                .to_string(),
        );
    }
    let &[record_type] = args.types.as_slice() else {
        let types: Vec<&str> = args.types.iter().map(|t| t.as_str()).collect();
        return CmdOutcome::Invalid(format!(
            "the DNS lens shows one record type at a time, got {}",
            types.join(" ")
        ));
    };
    CmdOutcome::Dig {
        domain: args.name,
        record_type,
        server: args.server,
        trace: args.trace,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_quit() {
        assert_eq!(parse("q"), CmdOutcome::Quit);
        assert_eq!(parse("quit"), CmdOutcome::Quit);
        assert_eq!(parse("exit"), CmdOutcome::Quit);
    }

    #[test]
    fn parses_help_and_copy() {
        assert_eq!(parse("help"), CmdOutcome::Help);
        assert_eq!(parse("?"), CmdOutcome::Help);
        assert_eq!(parse("copy"), CmdOutcome::Copy);
        assert_eq!(parse("yank"), CmdOutcome::Copy);
    }

    #[test]
    fn parses_set_output() {
        assert_eq!(
            parse("set output json"),
            CmdOutcome::SetFormat("json".into())
        );
        assert_eq!(
            parse("set format yaml"),
            CmdOutcome::SetFormat("yaml".into())
        );
        assert_eq!(parse("set output bogus"), CmdOutcome::BadFormat);
    }

    #[test]
    fn parses_theme_command() {
        assert_eq!(parse("theme latte"), CmdOutcome::SetTheme("latte".into()));
        assert_eq!(parse("theme frappe"), CmdOutcome::SetTheme("frappe".into()));
        // Args are lowercased before validation, so mixed case parses.
        assert_eq!(parse("theme LATTE"), CmdOutcome::SetTheme("latte".into()));
        assert_eq!(parse("theme Frappé"), CmdOutcome::SetTheme("frappé".into()));
        // Missing or unknown names both surface the standard error.
        assert_eq!(parse("theme"), CmdOutcome::BadTheme);
        assert_eq!(parse("theme mocha"), CmdOutcome::BadTheme);
    }

    #[test]
    fn parses_lens_with_and_without_target() {
        assert_eq!(
            parse("whois"),
            CmdOutcome::Lens {
                lens: "whois".into(),
                target: None
            }
        );
        assert_eq!(
            parse("ssl example.com"),
            CmdOutcome::Lens {
                lens: "ssl".into(),
                target: Some("example.com".into())
            }
        );
    }

    fn dig_of(domain: &str, record_type: RecordType) -> CmdOutcome {
        CmdOutcome::Dig {
            domain: domain.into(),
            record_type,
            server: None,
            trace: false,
        }
    }

    #[test]
    fn dig_parses_an_optional_record_type() {
        assert_eq!(
            parse("dig"),
            CmdOutcome::Lens {
                lens: "dig".into(),
                target: None
            }
        );
        assert_eq!(
            parse("dig example.com"),
            dig_of("example.com", RecordType::A)
        );
        // The type was previously dropped silently (always A).
        assert_eq!(
            parse("dig example.com mx"),
            dig_of("example.com", RecordType::MX)
        );
        assert!(
            matches!(parse("dig example.com BOGUS"), CmdOutcome::Invalid(m) if m.contains("BOGUS"))
        );
        assert!(matches!(
            parse("dig example.com MX extra"),
            CmdOutcome::Invalid(_)
        ));
    }

    /// The CLI/REPL grammar: any token order, `@server`, `+trace`, `-x`,
    /// and every type in `RecordType::ALL` (HTTPS, SVCB, CDS, CDNSKEY …).
    #[test]
    fn dig_shares_the_cli_grammar() {
        assert_eq!(
            parse("dig MX example.com"),
            dig_of("example.com", RecordType::MX)
        );
        assert_eq!(
            parse("dns @1.1.1.1 example.com https"),
            CmdOutcome::Dig {
                domain: "example.com".into(),
                record_type: RecordType::HTTPS,
                server: Some("1.1.1.1".into()),
                trace: false,
            }
        );
        assert_eq!(
            parse("dig example.com AAAA +trace"),
            CmdOutcome::Dig {
                domain: "example.com".into(),
                record_type: RecordType::AAAA,
                server: None,
                trace: true,
            }
        );
        assert_eq!(
            parse("dig -x 192.0.2.7"),
            dig_of("192.0.2.7", RecordType::PTR)
        );
        for name in RecordType::ALL_NAMES {
            let CmdOutcome::Dig { record_type, .. } = parse(&format!("dig example.com {name}"))
            else {
                panic!("{name} must parse as a record type");
            };
            assert_eq!(record_type.as_str(), *name);
        }
    }

    #[test]
    fn dig_rejects_what_the_lens_cannot_show() {
        let invalid = |line: &str| match parse(line) {
            CmdOutcome::Invalid(message) => message,
            other => panic!("{line}: expected Invalid, got {other:?}"),
        };
        assert!(invalid("dig example.com A MX").contains("one record type at a time, got A MX"));
        assert!(invalid("dig example.com +short").contains("+short"));
        // The shared parser's own errors come through verbatim.
        assert!(invalid("dig example.com +tcp").contains("unknown dig option '+tcp'"));
        assert!(invalid("dig @8.8.8.8 example.com +trace").contains("root servers"));
    }

    #[test]
    fn global_lens_arguments_are_subcommands_not_domains() {
        assert_eq!(
            parse("watch add example.org"),
            CmdOutcome::WatchMutate {
                add: Some("example.org".into()),
                remove: None
            }
        );
        assert_eq!(
            parse("watch remove example.org"),
            CmdOutcome::WatchMutate {
                add: None,
                remove: Some("example.org".into())
            }
        );
        for line in ["watch", "watch list"] {
            assert_eq!(
                parse(line),
                CmdOutcome::Lens {
                    lens: "watch".into(),
                    target: None
                },
                "{line}"
            );
        }
        for line in [
            "watch add",
            "watch frob x.com",
            "history clear",
            "bulk file.txt",
        ] {
            assert!(
                matches!(parse(line), CmdOutcome::Invalid(_)),
                "{line} must be rejected, not treated as a domain"
            );
        }
        assert_eq!(
            parse("history"),
            CmdOutcome::Lens {
                lens: "history".into(),
                target: None
            }
        );
    }

    #[test]
    fn parses_bare_domain_and_lookup() {
        assert_eq!(
            parse("example.com"),
            CmdOutcome::Lookup("example.com".into())
        );
        assert_eq!(
            parse("lookup acme.io"),
            CmdOutcome::Lookup("acme.io".into())
        );
    }

    #[test]
    fn empty_is_noop_unknown_is_error() {
        assert_eq!(parse("   "), CmdOutcome::Noop);
        assert_eq!(
            parse("frobnicate"),
            CmdOutcome::Unknown("frobnicate".into())
        );
    }

    #[test]
    fn parses_new_lens_commands() {
        assert_eq!(
            parse("reverse 8.8.8.8"),
            CmdOutcome::Lens {
                lens: "reverse".into(),
                target: Some("8.8.8.8".into())
            }
        );
        assert_eq!(
            parse("tld .com"),
            CmdOutcome::Lens {
                lens: "tld".into(),
                target: Some(".com".into())
            }
        );
        assert_eq!(
            parse("diff a.com b.com"),
            CmdOutcome::Diff {
                a: "a.com".into(),
                b: "b.com".into()
            }
        );
        assert_eq!(
            parse("compare ex.com 8.8.8.8 1.1.1.1"),
            CmdOutcome::Compare {
                domain: "ex.com".into(),
                a: "8.8.8.8".into(),
                b: "1.1.1.1".into()
            }
        );
    }
}