domain-check 0.9.0

A fast CLI tool for checking domain availability using RDAP with WHOIS fallback
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Display logic for domain-check CLI.
//!
//! This module handles all styled terminal output: colored result lines,
//! grouped batch output (--pretty), spinner animation, progress counters,
//! headers, and summaries. Uses only the `console` crate (already a dependency).
//!
//! Default mode: colored status words, progress counter, spinner, colored summary.
//! Pretty mode: everything above plus grouped layout, column alignment, styled header.

use console::{pad_str, style, Alignment, Term};
use domain_check_lib::{DomainInfo, DomainResult};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use crate::{Args, ErrorStats};

// ── Spinner ──────────────────────────────────────────────────────────────────

const SPINNER_FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];

/// An async braille-dot spinner that writes to stderr so stdout stays clean.
pub struct Spinner {
    running: Arc<AtomicBool>,
    handle: Option<tokio::task::JoinHandle<()>>,
}

impl Spinner {
    /// Start a new spinner with the given message (e.g. "Checking 8 domains...").
    ///
    /// Returns `None` if stderr is not a TTY (piped output, CI, etc.) to avoid
    /// polluting non-interactive streams with escape codes.
    /// Waits 500ms before showing to avoid a flash on fast operations.
    pub fn start(message: String) -> Option<Self> {
        let term = Term::stderr();
        if !term.is_term() {
            return None;
        }

        let running = Arc::new(AtomicBool::new(true));
        let running_clone = running.clone();

        let handle = tokio::spawn(async move {
            let term = Term::stderr();

            // Wait before showing — avoids spinner flash on fast operations
            tokio::time::sleep(Duration::from_millis(500)).await;

            let mut idx = 0usize;
            while running_clone.load(Ordering::Relaxed) {
                let frame = SPINNER_FRAMES[idx % SPINNER_FRAMES.len()];
                let _ = term.clear_line();
                let _ = term.write_str(&format!("{} {}", style(frame).cyan(), message));
                idx += 1;
                tokio::time::sleep(Duration::from_millis(80)).await;
            }
            let _ = term.clear_line();
        });

        Some(Self {
            running,
            handle: Some(handle),
        })
    }

    /// Stop the spinner and clear the line.
    pub async fn stop(self) {
        self.running.store(false, Ordering::Relaxed);
        if let Some(h) = self.handle {
            let _ = h.await;
        }
    }
}

// ── Header ───────────────────────────────────────────────────────────────────

/// Print a styled header at the start of a pretty run.
pub fn print_header(domain_count: usize, concurrency: usize, args: &Args) {
    println!(
        "{} {} {}",
        style("domain-check").bold(),
        style(format!("v{}", env!("CARGO_PKG_VERSION"))).dim(),
        style(format!(
            "— Checking {} domain{}",
            domain_count,
            if domain_count == 1 { "" } else { "s" }
        ))
        .dim(),
    );

    let mut meta_parts: Vec<String> = Vec::new();

    if let Some(preset) = &args.preset {
        meta_parts.push(format!("Preset: {}", preset));
    }
    if args.all_tlds {
        let tld_count = domain_check_lib::get_all_known_tlds().len();
        meta_parts.push(format!("All {} TLDs", tld_count));
    }
    meta_parts.push(format!("Concurrency: {}", concurrency));

    println!("{}", style(meta_parts.join(" | ")).dim());
    println!();
}

// ── Single result line ───────────────────────────────────────────────────────

/// Format and print a single domain result with colors and alignment.
///
/// If `counter` is Some((current, total)), a progress prefix like `[3/8]` is shown.
pub fn print_result(
    result: &DomainResult,
    show_info: bool,
    debug: bool,
    counter: Option<(usize, usize)>,
) {
    let domain_width = 30;
    let padded_domain = pad_str(&result.domain, domain_width, Alignment::Left, Some(".."));

    let prefix = match counter {
        Some((cur, total)) => {
            format!("{} ", style(format!("[{}/{}]", cur, total)).dim())
        }
        None => String::new(),
    };

    match result.available {
        Some(true) => {
            println!(
                "  {}{}  {}",
                prefix,
                style(&padded_domain).white(),
                style("AVAILABLE").green().bold(),
            );
        }
        Some(false) => {
            let info_str = if show_info {
                result
                    .info
                    .as_ref()
                    .map(|i| format!("  {}", style(format_domain_info(i)).dim()))
                    .unwrap_or_default()
            } else {
                String::new()
            };
            println!(
                "  {}{}  {}{}",
                prefix,
                style(&padded_domain).white(),
                style("TAKEN").red().bold(),
                info_str,
            );
        }
        None => {
            let reason = brief_error(result);
            println!(
                "  {}{}  {}  {}",
                prefix,
                style(&padded_domain).white(),
                style("UNKNOWN").yellow(),
                style(reason).dim(),
            );
        }
    }

    if debug {
        if let Some(duration) = result.check_duration {
            println!(
                "    {} Checked in {}ms via {}",
                style("└─").dim(),
                duration.as_millis(),
                result.method_used,
            );
        }
    }
}

// ── Default result line (colored, flat) ───────────────────────────────────────

/// Print a single domain result with colored status words but flat layout.
/// No padding or column alignment — just `domain STATUS` with color.
///
/// If `counter` is Some((current, total)), a progress prefix like `[3/8]` is shown.
pub fn print_result_default(
    result: &DomainResult,
    show_info: bool,
    debug: bool,
    counter: Option<(usize, usize)>,
) {
    let prefix = match counter {
        Some((cur, total)) => format!("{} ", style(format!("[{}/{}]", cur, total)).dim()),
        None => String::new(),
    };

    match result.available {
        Some(true) => {
            println!(
                "{}{} {}",
                prefix,
                result.domain,
                style("AVAILABLE").green().bold(),
            );
        }
        Some(false) => {
            let info_str = if show_info {
                result
                    .info
                    .as_ref()
                    .map(|i| format!(" ({})", style(format_domain_info(i)).dim()))
                    .unwrap_or_default()
            } else {
                String::new()
            };
            println!(
                "{}{} {}{}",
                prefix,
                result.domain,
                style("TAKEN").red().bold(),
                info_str,
            );
        }
        None => {
            let reason = brief_error(result);
            println!(
                "{}{} {} {}",
                prefix,
                result.domain,
                style("UNKNOWN").yellow(),
                style(reason).dim(),
            );
        }
    }

    if debug {
        if let Some(duration) = result.check_duration {
            println!(
                "    {} Checked in {}ms via {}",
                style("└─").dim(),
                duration.as_millis(),
                result.method_used,
            );
        }
    }
}

// ── Grouped batch output (Issue #17 core) ────────────────────────────────────

/// Print results grouped by status: Available, Taken, Unknown.
/// Empty sections are omitted entirely.
pub fn print_grouped_results(results: &[DomainResult], show_info: bool, debug: bool) {
    let mut available: Vec<&DomainResult> = Vec::new();
    let mut taken: Vec<&DomainResult> = Vec::new();
    let mut unknown: Vec<&DomainResult> = Vec::new();

    for r in results {
        match r.available {
            Some(true) => available.push(r),
            Some(false) => taken.push(r),
            None => unknown.push(r),
        }
    }

    if !available.is_empty() {
        println!(
            "  {} {}",
            style(format!("── Available ({}) ", available.len()))
                .green()
                .bold(),
            style("".repeat(40)).green().dim(),
        );
        for r in &available {
            print_grouped_line(r, show_info, debug);
        }
        println!();
    }

    if !taken.is_empty() {
        println!(
            "  {} {}",
            style(format!("── Taken ({}) ", taken.len())).red().bold(),
            style("".repeat(44)).red().dim(),
        );
        for r in &taken {
            print_grouped_line(r, show_info, debug);
        }
        println!();
    }

    if !unknown.is_empty() {
        println!(
            "  {} {}",
            style(format!("── Unknown ({}) ", unknown.len()))
                .yellow()
                .bold(),
            style("".repeat(40)).yellow().dim(),
        );
        for r in &unknown {
            print_grouped_line(r, show_info, debug);
        }
        println!();
    }
}

/// Print a single line inside a grouped section.
fn print_grouped_line(result: &DomainResult, show_info: bool, debug: bool) {
    let domain_width = 30;
    let padded = pad_str(&result.domain, domain_width, Alignment::Left, Some(".."));

    match result.available {
        Some(true) => {
            println!("    {}", style(&padded).white());
        }
        Some(false) => {
            let info_str = if show_info {
                result
                    .info
                    .as_ref()
                    .map(|i| format!("  {}", style(format_domain_info(i)).dim()))
                    .unwrap_or_default()
            } else {
                String::new()
            };
            println!("    {}{}", style(&padded).white(), info_str);
        }
        None => {
            let reason = brief_error(result);
            println!("    {}  {}", style(&padded).white(), style(reason).dim());
        }
    }

    if debug {
        if let Some(duration) = result.check_duration {
            println!(
                "      {} Checked in {}ms via {}",
                style("└─").dim(),
                duration.as_millis(),
                result.method_used,
            );
        }
    }
}

// ── Summary ──────────────────────────────────────────────────────────────────

/// Print the final summary bar with colored counts.
pub fn print_summary(
    total: usize,
    available: usize,
    taken: usize,
    unknown: usize,
    duration: Duration,
) {
    println!(
        "  {}",
        style("────────────────────────────────────────────────────").dim()
    );
    println!(
        "  {} domain{} in {:.1}s  {}  {}  {}  {}  {}  {}",
        style(total).bold(),
        if total == 1 { "" } else { "s" },
        duration.as_secs_f64(),
        style("|").dim(),
        style(format!("{} available", available)).green(),
        style("|").dim(),
        style(format!("{} taken", taken)).red(),
        style("|").dim(),
        style(format!("{} unknown", unknown)).yellow(),
    );
}

// ── Error summary ────────────────────────────────────────────────────────────

/// Print a categorized error summary using colors.
pub fn print_error_summary(error_stats: &ErrorStats, args: &Args) {
    if !error_stats.has_errors() {
        return;
    }

    println!("  {}", style("Some domains could not be checked:").yellow());

    let format_list = |domains: &[String], max_show: usize| -> String {
        if domains.len() <= max_show {
            domains.join(", ")
        } else {
            let shown = &domains[..max_show];
            let remaining = domains.len() - max_show;
            format!("{}, ... and {} more", shown.join(", "), remaining)
        }
    };

    if !error_stats.timeouts.is_empty() {
        println!(
            "  {} {} timeout{}: {}",
            style("").dim(),
            error_stats.timeouts.len(),
            if error_stats.timeouts.len() == 1 {
                ""
            } else {
                "s"
            },
            format_list(&error_stats.timeouts, 5),
        );
    }
    if !error_stats.network_errors.is_empty() {
        println!(
            "  {} {} network error{}: {}",
            style("").dim(),
            error_stats.network_errors.len(),
            if error_stats.network_errors.len() == 1 {
                ""
            } else {
                "s"
            },
            format_list(&error_stats.network_errors, 5),
        );
    }
    if !error_stats.parsing_errors.is_empty() {
        println!(
            "  {} {} parsing error{}: {}",
            style("").dim(),
            error_stats.parsing_errors.len(),
            if error_stats.parsing_errors.len() == 1 {
                ""
            } else {
                "s"
            },
            format_list(&error_stats.parsing_errors, 5),
        );
    }
    if !error_stats.unknown_tld_errors.is_empty() {
        println!(
            "  {} {} unknown TLD error{}: {}",
            style("").dim(),
            error_stats.unknown_tld_errors.len(),
            if error_stats.unknown_tld_errors.len() == 1 {
                ""
            } else {
                "s"
            },
            format_list(&error_stats.unknown_tld_errors, 5),
        );
    }
    if !error_stats.other_errors.is_empty() {
        println!(
            "  {} {} other error{}: {}",
            style("").dim(),
            error_stats.other_errors.len(),
            if error_stats.other_errors.len() == 1 {
                ""
            } else {
                "s"
            },
            format_list(&error_stats.other_errors, 5),
        );
    }

    if args.debug && error_stats.has_errors() {
        println!(
            "  {} {}",
            style("").dim(),
            style("All errors attempted WHOIS fallback where possible").dim(),
        );
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Format domain info (registrar, dates) into a concise string.
pub fn format_domain_info(info: &DomainInfo) -> String {
    let mut parts = Vec::new();
    if let Some(registrar) = &info.registrar {
        parts.push(format!("Registrar: {}", registrar));
    }
    if let Some(created) = &info.creation_date {
        parts.push(format!("Created: {}", created));
    }
    if let Some(expires) = &info.expiration_date {
        parts.push(format!("Expires: {}", expires));
    }
    if parts.is_empty() {
        "No info available".to_string()
    } else {
        parts.join(", ")
    }
}

/// Extract a brief error reason from a DomainResult with unknown status.
fn brief_error(result: &DomainResult) -> &str {
    match &result.error_message {
        Some(msg) => {
            let m = msg.to_lowercase();
            if m.contains("timeout") || m.contains("timed out") {
                "(timeout)"
            } else if m.contains("network") || m.contains("dns") || m.contains("connect") {
                "(network error)"
            } else if m.contains("parse") || m.contains("json") {
                "(parsing error)"
            } else if m.contains("unknown") || m.contains("tld") || m.contains("bootstrap") {
                "(unknown TLD)"
            } else {
                "(error)"
            }
        }
        None => "(unknown status)",
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    fn make_result(domain: &str, available: Option<bool>) -> DomainResult {
        DomainResult {
            domain: domain.to_string(),
            available,
            info: None,
            check_duration: None,
            method_used: CheckMethod::Rdap,
            error_message: if available.is_none() {
                Some("timeout".to_string())
            } else {
                None
            },
        }
    }

    #[test]
    fn test_brief_error_timeout() {
        let r = make_result("a.com", None);
        assert_eq!(brief_error(&r), "(timeout)");
    }

    #[test]
    fn test_brief_error_network() {
        let r = DomainResult {
            error_message: Some("dns lookup failed".to_string()),
            ..make_result("a.com", None)
        };
        assert_eq!(brief_error(&r), "(network error)");
    }

    #[test]
    fn test_brief_error_unknown_status() {
        let r = DomainResult {
            error_message: None,
            ..make_result("a.com", None)
        };
        assert_eq!(brief_error(&r), "(unknown status)");
    }

    #[test]
    fn test_format_domain_info_all_fields() {
        let info = DomainInfo {
            registrar: Some("GoDaddy".to_string()),
            creation_date: Some("2020-01-01".to_string()),
            expiration_date: Some("2025-01-01".to_string()),
            ..Default::default()
        };
        let formatted = format_domain_info(&info);
        assert!(formatted.contains("Registrar: GoDaddy"));
        assert!(formatted.contains("Created: 2020-01-01"));
        assert!(formatted.contains("Expires: 2025-01-01"));
    }

    #[test]
    fn test_format_domain_info_empty() {
        let info = DomainInfo::default();
        assert_eq!(format_domain_info(&info), "No info available");
    }

    #[test]
    fn test_format_domain_info_partial() {
        let info = DomainInfo {
            registrar: Some("Namecheap".to_string()),
            ..Default::default()
        };
        assert_eq!(format_domain_info(&info), "Registrar: Namecheap");
    }
}