rs-rich-cli 0.0.12

The `rich` executable: a Rust port of Python `rich-cli` 1.8.1
Documentation
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! `rich view`, `rich hex`, `rich unicode`, `rich env` and `rich capture`:
//! CLI glue over `rich_ext::source_view`, `rich_ext::hex`,
//! `rich_ext::unicode_inspect` and `rich_ext::env_inspect` (0.0.11 workstream
//! 11).
//!
//! None of these exists upstream. They compose public rich-ext renderables
//! and core's ANSI decoder, so they are binary-boundary conveniences like
//! `inspect.rs` and `tools.rs`.
use std::io::Read;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use rich::ansi::AnsiDecoder;
use rich::text::Text;
use rich::{Panel, Renderable, Style};
use rich_ext::data::Format;
use rich_ext::source_view::SourceView;

/// The widest `--bytes-per-line` `rich_ext::hex::HexView` draws.
const MAX_BYTES_PER_LINE: usize = 4096;

/// Options for the viewer commands.
#[derive(Clone, Debug, Default)]
pub(crate) struct ViewerOptions {
    search: Option<String>,
    no_line_numbers: bool,
    offset: Option<u64>,
    length: Option<usize>,
    bytes_per_line: Option<usize>,
    group: Option<usize>,
    limit: Option<usize>,
    show_secrets: bool,
    cast: Option<String>,
    redact_patterns: Vec<String>,
}

fn number<'a, T: std::str::FromStr>(
    flag: &str,
    rest: &mut impl Iterator<Item = &'a String>,
) -> Result<T, String> {
    let value = rest.next().ok_or(format!("{flag} requires a number"))?;
    let digits = value.replace('_', "");
    let parsed = match digits
        .strip_prefix("0x")
        .or_else(|| digits.strip_prefix("0X"))
    {
        Some(hex) => u64::from_str_radix(hex, 16)
            .ok()
            .and_then(|n| n.to_string().parse().ok()),
        None => digits.parse().ok(),
    };
    parsed.ok_or(format!("{flag} requires a number, got {value:?}"))
}

impl ViewerOptions {
    /// Consume one of these options; anything else stays with the main parser.
    pub(crate) fn parse_option<'a>(
        &mut self,
        arg: &str,
        rest: &mut impl Iterator<Item = &'a String>,
    ) -> Result<bool, String> {
        match arg {
            "--search" => {
                self.search = Some(rest.next().ok_or("--search requires a pattern")?.clone());
            }
            "--no-line-numbers" => self.no_line_numbers = true,
            "--offset" => self.offset = Some(number(arg, rest)?),
            "--length" => self.length = Some(number(arg, rest)?),
            "--bytes-per-line" => {
                let per_line: usize = number(arg, rest)?;
                if !(1..=MAX_BYTES_PER_LINE).contains(&per_line) {
                    return Err(format!(
                        "--bytes-per-line must be between 1 and {MAX_BYTES_PER_LINE}"
                    ));
                }
                self.bytes_per_line = Some(per_line);
            }
            "--group" => {
                let group: usize = number(arg, rest)?;
                if group == 0 {
                    return Err("--group must be at least 1".into());
                }
                self.group = Some(group);
            }
            "--limit" => self.limit = Some(number(arg, rest)?),
            "--show-secrets" => self.show_secrets = true,
            "--cast" => self.cast = Some(rest.next().ok_or("--cast requires a file")?.clone()),
            "--redact-pattern" => self.redact_patterns.push(
                rest.next()
                    .ok_or("--redact-pattern requires a regular expression")?
                    .clone(),
            ),
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// `--offset`, where `rich hex` starts.
    pub(crate) fn offset(&self) -> Option<u64> {
        self.offset
    }

    /// `--length`, the most bytes `rich hex` shows.
    pub(crate) fn length(&self) -> Option<usize> {
        self.length
    }

    /// Each option given with the commands it applies to, for the "only has
    /// an effect" check.
    pub(crate) fn given(&self) -> Vec<(&'static str, &'static [&'static str])> {
        [
            ("--search", self.search.is_some(), &["view", "hex"][..]),
            ("--no-line-numbers", self.no_line_numbers, &["view"]),
            ("--offset", self.offset.is_some(), &["hex"]),
            ("--length", self.length.is_some(), &["hex"]),
            ("--bytes-per-line", self.bytes_per_line.is_some(), &["hex"]),
            ("--group", self.group.is_some(), &["hex"]),
            ("--limit", self.limit.is_some(), &["unicode"]),
            ("--show-secrets", self.show_secrets, &["env"]),
            ("--cast", self.cast.is_some(), &["capture"]),
            (
                "--redact-pattern",
                !self.redact_patterns.is_empty(),
                &["capture"],
            ),
        ]
        .into_iter()
        .filter(|(_, given, _)| *given)
        .map(|(flag, _, commands)| (flag, commands))
        .collect()
    }
}

/// What `rich view` shows a resource as.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ViewAs {
    Markdown,
    Csv,
    Notebook,
    Image,
    Gif,
    /// JSON Lines logs, through the `log` renderer.
    Log,
    /// A unified diff or patch.
    Patch,
    /// Highlighted source (or plain text) with this lexer.
    Source(String),
    /// Not text: a hex dump.
    Binary,
}

/// Whether `bytes` look binary: a NUL byte, or not UTF-8, in the first 8 KiB.
pub(crate) fn looks_binary(bytes: &[u8]) -> bool {
    let head = &bytes[..bytes.len().min(8192)];
    if head.contains(&0) {
        return true;
    }
    match std::str::from_utf8(head) {
        Ok(_) => false,
        // A multi-byte character cut off at the 8 KiB boundary is still text.
        Err(error) => error.error_len().is_some(),
    }
}

/// Where `bytes` would be cut to keep `limit` lines: just after the newline
/// ending line `limit`, when anything follows it.
pub(crate) fn line_end(bytes: &[u8], limit: usize) -> Option<usize> {
    match limit {
        0 => Some(0),
        _ => bytes
            .iter()
            .enumerate()
            .filter(|(_, b)| **b == b'\n')
            .nth(limit - 1)
            .map(|(at, _)| at + 1),
    }
    .filter(|&end| end < bytes.len())
}

/// Tell the reader on stderr that only part of `name` is shown.
pub(crate) fn notice(name: &str, shown: &str, hint: &str) {
    eprintln!(
        "rich: showing the first {shown} of {}; {hint}",
        rich_ext::sanitize_terminal_controls(name)
    );
}

/// Decide how to view a resource from its extension, then its content.
pub(crate) fn detect(ext: Option<&str>, name: Option<&str>, bytes: &[u8]) -> ViewAs {
    match ext {
        Some("md" | "markdown") => return ViewAs::Markdown,
        Some("csv" | "tsv") => return ViewAs::Csv,
        Some("ipynb") => return ViewAs::Notebook,
        Some("gif") => return ViewAs::Gif,
        Some("png" | "jpg" | "jpeg" | "bmp" | "webp" | "tif" | "tiff" | "ico") => {
            return ViewAs::Image
        }
        Some("diff" | "patch") => return ViewAs::Patch,
        Some("jsonl" | "ndjson") => return ViewAs::Log,
        _ => {}
    }
    if looks_binary(bytes) {
        return ViewAs::Binary;
    }
    let text = String::from_utf8_lossy(bytes);
    let start = text.trim_start();
    if start.starts_with("diff --git ") || (start.starts_with("--- ") && text.contains("\n+++ ")) {
        return ViewAs::Patch;
    }
    if let Some(ext) = ext {
        return ViewAs::Source(ext.to_string());
    }
    let lexer = match Format::detect(&text, name) {
        Some(Format::Json) => "json",
        Some(Format::Yaml) => "yaml",
        Some(Format::Toml) => "toml",
        Some(Format::Xml) => "xml",
        Some(Format::Ini) => "ini",
        Some(Format::Dotenv) => "sh",
        None => "txt",
    };
    ViewAs::Source(lexer.to_string())
}

/// `rich view`'s source view, with a search summary line when searching.
pub(crate) fn source(options: &ViewerOptions, content: &str, lexer: &str) -> Box<dyn Renderable> {
    let mut view = SourceView::new(content, lexer).line_numbers(!options.no_line_numbers);
    if let Some(pattern) = &options.search {
        view = view.search(pattern.clone());
    }
    Box::new(view)
}

/// The one-line search summary `rich view --search` prints to stderr.
pub(crate) fn search_summary(options: &ViewerOptions, content: &str) -> Option<String> {
    let pattern = options.search.as_ref()?;
    let matches = SourceView::new(content, "txt")
        .search(pattern.clone())
        .matches();
    let total: usize = matches.iter().map(|(_, count)| count).sum();
    let lines: Vec<String> = matches
        .iter()
        .take(10)
        .map(|(line, _)| line.to_string())
        .collect();
    Some(match total {
        0 => format!("no matches for {pattern:?}"),
        _ => format!(
            "{total} match{} for {pattern:?} on line{} {}{}",
            if total == 1 { "" } else { "es" },
            if matches.len() == 1 { "" } else { "s" },
            lines.join(", "),
            if matches.len() > 10 { ", …" } else { "" }
        ),
    })
}

/// Output chunks with the time since the command started.
type Chunks = Vec<(Duration, Vec<u8>)>;

/// One command's captured output.
pub(crate) struct Captured {
    pub command: Vec<String>,
    /// Output chunks from stdout and stderr, in arrival order, with the time
    /// since the command started.
    pub chunks: Chunks,
    pub status: Option<i32>,
    /// The signal that killed the command, where the platform reports one.
    pub signal: Option<i32>,
    pub elapsed: Duration,
    /// Why reading stopped early, if it did: output past the limit, or a
    /// background process holding the output open after the command exited.
    pub notice: Option<String>,
}

impl Captured {
    /// The status `rich capture` exits with: the command's own, or
    /// 128 + the signal number when a signal killed it, as a shell reports.
    /// A status that does not fit a byte, or reads as 0 once truncated, is 1.
    pub fn exit_code(&self) -> u8 {
        match (self.status, self.signal) {
            (Some(0), _) => 0,
            (Some(code), _) => u8::try_from(code).ok().filter(|&c| c != 0).unwrap_or(1),
            (None, Some(signal)) => u8::try_from(128 + signal).unwrap_or(1),
            (None, None) => 1,
        }
    }

    /// Mask secrets in the output and the command line, before anything is
    /// shown, exported or recorded. The output is decoded once, so a
    /// character split between pipe reads stays whole; chunks keep their
    /// timing and, when nothing matched, their bytes. A secret split across
    /// chunks is masked where it starts. On the command line, the word after
    /// a secret-named flag (`--token X`) is masked too.
    pub fn redact(&mut self, redactor: &rich_ext::redact::Redactor) {
        let chunks: Vec<&[u8]> = self.chunks.iter().map(|(_, b)| b.as_slice()).collect();
        let redacted = redactor.redact_byte_chunks(&chunks);
        for ((_, bytes), new) in self.chunks.iter_mut().zip(redacted) {
            *bytes = new;
        }
        self.command = redactor.redact_args(&self.command);
    }

    /// `--sanitize`: neutralise terminal controls in the output, keeping the
    /// colours the panel shows, and in the command line, before anything is
    /// shown, exported or recorded. The output is processed a line at a time,
    /// as the ANSI decoder reads it, so a sequence split between pipe reads
    /// is still seen whole; a chunk that ends mid-line goes out with the
    /// chunk that finishes the line.
    pub fn sanitize(&mut self) {
        let neutralize = |bytes: &[u8]| {
            crate::controls::neutralize_for_decoder(&String::from_utf8_lossy(bytes)).into_bytes()
        };
        let mut pending: Vec<u8> = Vec::new();
        let mut chunks: Chunks = Vec::new();
        let mut last = Duration::ZERO;
        for (at, bytes) in std::mem::take(&mut self.chunks) {
            pending.extend_from_slice(&bytes);
            last = at;
            if let Some(end) = pending.iter().rposition(|&b| b == b'\n') {
                let rest = pending.split_off(end + 1);
                chunks.push((at, neutralize(&pending)));
                pending = rest;
            }
        }
        if !pending.is_empty() {
            chunks.push((last, neutralize(&pending)));
        }
        self.chunks = chunks;
        self.command = self
            .command
            .iter()
            .map(|word| rich_ext::sanitize_terminal_controls(word))
            .collect();
    }

    fn output(&self) -> Vec<u8> {
        self.chunks
            .iter()
            .flat_map(|(_, bytes)| bytes.clone())
            .collect()
    }
}

/// How long `capture` keeps reading after the command exits while its output
/// stays open (a background process it started can hold it forever).
/// Measured from the exit.
const GRACE: Duration = Duration::from_secs(1);

/// How often `capture` checks on the command while no output arrives.
const TICK: Duration = Duration::from_millis(10);

/// Run `command` with its output piped, as a colour-capable terminal `width`
/// columns wide would see it (`FORCE_COLOR`, `CLICOLOR_FORCE`, `COLUMNS`).
/// The command's own exit status is recorded, not returned as an error.
///
/// Reading stops [`GRACE`] after the command exits, even if a process it left
/// in the background still holds the output open, and output past
/// [`CAPTURE_LIMIT`](crate::controls::CAPTURE_LIMIT) or
/// [`LINE_LIMIT`](crate::controls::LINE_LIMIT) lines stops the command; either
/// is recorded in [`Captured::notice`].
pub(crate) fn capture(command: &[String], width: usize) -> Result<Captured, String> {
    use crate::controls::{CAPTURE_LIMIT, LINE_LIMIT};
    capture_with_limits(command, width, CAPTURE_LIMIT, LINE_LIMIT)
}

fn capture_with_limits(
    command: &[String],
    width: usize,
    limit: usize,
    line_limit: usize,
) -> Result<Captured, String> {
    use std::sync::mpsc::{channel, RecvTimeoutError};
    let (program, args) = command
        .split_first()
        .ok_or("capture needs a command after --")?;
    // stdout and stderr share one pipe, as they share a terminal, so their
    // output interleaves in the order it was written.
    let (mut reader, writer) = std::io::pipe().map_err(|e| format!("cannot capture: {e}"))?;
    let stderr = writer
        .try_clone()
        .map_err(|e| format!("cannot capture: {e}"))?;
    let started = Instant::now();
    let mut process = Command::new(program);
    process
        .args(args)
        .env("FORCE_COLOR", "1")
        .env("CLICOLOR_FORCE", "1")
        .env("COLUMNS", width.to_string())
        .env_remove("NO_COLOR")
        .stdin(Stdio::null())
        .stdout(writer)
        .stderr(stderr);
    let spawned = process.spawn();
    // Our copies of the write end must close, or the read never ends.
    drop(process);
    let mut child = spawned.map_err(|e| format!("cannot run {program}: {e}"))?;
    let (sender, receiver) = channel::<(Duration, Vec<u8>)>();
    // Not joined: a background process may keep the pipe open long after
    // we stop listening. Once the receiver is gone its next send fails.
    std::thread::spawn(move || {
        let mut buffer = [0u8; 8192];
        while let Ok(read) = reader.read(&mut buffer) {
            if read == 0
                || sender
                    .send((started.elapsed(), buffer[..read].to_vec()))
                    .is_err()
            {
                break;
            }
        }
    });
    let mut chunks: Chunks = Vec::new();
    let (mut kept, mut lines) = (0usize, 0usize);
    let mut notice = None;
    let mut exited: Option<(std::process::ExitStatus, Instant)> = None;
    let wait_error = |e: std::io::Error| format!("waiting for {program}: {e}");
    loop {
        match receiver.recv_timeout(TICK) {
            Ok((at, mut bytes)) if notice.is_none() => {
                let past = if kept + bytes.len() > limit {
                    bytes.truncate(limit - kept);
                    Some(crate::controls::size(limit as u64))
                } else {
                    None
                };
                let past = match line_end(&bytes, line_limit - lines) {
                    Some(end) => {
                        bytes.truncate(end);
                        Some(format!("{line_limit} lines"))
                    }
                    None => past,
                };
                lines += bytes.iter().filter(|b| **b == b'\n').count();
                if let Some(past) = past {
                    notice = Some(format!(
                        "the output passed {past}, the most rich capture keeps; stopped the command"
                    ));
                    if exited.is_none() {
                        let _ = child.kill();
                    }
                }
                kept += bytes.len();
                if !bytes.is_empty() {
                    chunks.push((at, bytes));
                }
            }
            Ok(_) | Err(RecvTimeoutError::Timeout) => {}
            // End of output: all that is left is the exit.
            Err(RecvTimeoutError::Disconnected) => {
                if exited.is_none() {
                    exited = Some((child.wait().map_err(wait_error)?, Instant::now()));
                }
                break;
            }
        }
        if exited.is_none() {
            if let Some(status) = child.try_wait().map_err(wait_error)? {
                exited = Some((status, Instant::now()));
            }
        }
        match exited {
            Some(_) if notice.is_some() => break,
            Some((_, at)) if at.elapsed() >= GRACE => {
                notice = Some(format!(
                    "{} exited but something it started still holds its output open; \
                     stopped reading {}s later",
                    rich_ext::sanitize_terminal_controls(program),
                    GRACE.as_secs()
                ));
                break;
            }
            _ => {}
        }
    }
    let (status, at) = exited.expect("the loop ends after the exit");
    Ok(Captured {
        command: command.to_vec(),
        chunks,
        status: status.code(),
        signal: exit_signal(&status),
        elapsed: at.duration_since(started),
        notice,
    })
}

#[cfg(unix)]
fn exit_signal(status: &std::process::ExitStatus) -> Option<i32> {
    std::os::unix::process::ExitStatusExt::signal(status)
}

#[cfg(not(unix))]
fn exit_signal(_status: &std::process::ExitStatus) -> Option<i32> {
    None
}

/// A command line as a shell would show it.
fn shell_words(words: &[String]) -> String {
    words
        .iter()
        .map(|word| {
            let plain = !word.is_empty()
                && word
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%".contains(c));
            if plain {
                word.clone()
            } else {
                format!("'{}'", word.replace('\'', r"'\''"))
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// The command line as the panel title and the cast header show it: our own
/// chrome, so any terminal controls in it are always made visible.
fn shown_command(words: &[String]) -> String {
    rich_ext::sanitize_terminal_controls(&shell_words(words))
}

fn format_elapsed(elapsed: Duration) -> String {
    let seconds = elapsed.as_secs_f64();
    if seconds < 1.0 {
        format!("{:.0}ms", seconds * 1000.0)
    } else {
        format!("{seconds:.2}s")
    }
}

/// The captured output in a panel titled with the command, its exit status
/// and duration below.
pub(crate) fn capture_view(captured: &Captured) -> Box<dyn Renderable> {
    let output = String::from_utf8_lossy(&captured.output()).into_owned();
    let mut lines = AnsiDecoder::new().decode(output.trim_end_matches('\n'));
    let mut text = Text::new("");
    for (index, line) in lines.drain(..).enumerate() {
        if index > 0 {
            text.append("\n", None);
        }
        text = text.append_text(&line);
    }
    let ok = captured.status == Some(0);
    let status = match captured.status {
        Some(code) => format!("exit {code}"),
        None => match captured.signal {
            Some(signal) => format!("killed by signal {signal}"),
            None => "killed by a signal".to_string(),
        },
    };
    let panel = Panel::new(Box::new(text))
        .title(format!(
            "$ {}",
            rich::markup::escape(&shown_command(&captured.command))
        ))
        .subtitle(format!("{status} · {}", format_elapsed(captured.elapsed)))
        .border_style(Style::parse(if ok { "green" } else { "red" }).unwrap_or_default());
    Box::new(panel)
}

/// The `--report json` envelope for a command that failed: `code` is
/// `"command"` and `exit_code` the status `rich capture` exits with.
pub(crate) fn capture_report(captured: &Captured) -> serde_json::Value {
    let message = match (captured.status, captured.signal) {
        (Some(code), _) => format!("command exited with status {code}"),
        (None, Some(signal)) => format!("command was killed by signal {signal}"),
        (None, None) => "command was killed by a signal".to_string(),
    };
    serde_json::json!({
        "ok": false,
        "code": "command",
        "exit_code": captured.exit_code(),
        "message": message,
        "error": { "message": message },
        "result": {
            "command": captured.command,
            "status": captured.status,
            "signal": captured.signal,
        },
    })
}

/// The capture as an asciicast v2 recording (`asciinema play FILE`).
pub(crate) fn asciicast(captured: &Captured, width: usize, height: usize) -> String {
    let header = serde_json::json!({
        "version": 2,
        "width": width,
        "height": height,
        "command": shown_command(&captured.command),
        "title": shown_command(&captured.command),
        "env": { "TERM": "xterm-256color" },
    });
    let mut out = header.to_string();
    out.push('\n');
    let mut event = |at: Duration, bytes: &[u8]| {
        // Terminals expect CRLF; piped output has bare LF.
        let data = String::from_utf8_lossy(bytes)
            .replace("\r\n", "\n")
            .replace('\n', "\r\n");
        out.push_str(&serde_json::json!([at.as_secs_f64(), "o", data]).to_string());
        out.push('\n');
    };
    // A character split between pipe reads goes out whole, in the event
    // where it ends, instead of as two replacement characters.
    let mut pending: Vec<u8> = Vec::new();
    let mut last = Duration::ZERO;
    for (at, bytes) in &captured.chunks {
        pending.extend_from_slice(bytes);
        let tail = pending.split_off(pending.len() - incomplete_utf8_tail(&pending));
        if !pending.is_empty() {
            event(*at, &pending);
        }
        pending = tail;
        last = *at;
    }
    if !pending.is_empty() {
        event(last, &pending);
    }
    out
}

/// How many bytes at the end of `bytes` are the start of a UTF-8
/// character that the next read will finish.
fn incomplete_utf8_tail(bytes: &[u8]) -> usize {
    let from = bytes.len().saturating_sub(3);
    for start in (from..bytes.len()).rev() {
        if bytes[start] & 0xc0 != 0x80 {
            return match std::str::from_utf8(&bytes[start..]) {
                Err(e) if e.error_len().is_none() => bytes.len() - start,
                _ => 0,
            };
        }
    }
    0
}

/// `rich hex`: `bytes`, already read from `start` (`--offset`) for at most
/// `--length` bytes, labelled from `start`.
pub(crate) fn hex(
    options: &ViewerOptions,
    bytes: Vec<u8>,
    start: u64,
) -> Result<Box<dyn Renderable>, String> {
    use rich_ext::hex::{parse_needle, HexView};
    let mut view = HexView::new(bytes).offset(start);
    if let Some(per_line) = options.bytes_per_line {
        view = view.bytes_per_line(Some(per_line));
    }
    if let Some(group) = options.group {
        view = view.group(group);
    }
    if let Some(needle) = &options.search {
        view = view.highlight(&parse_needle(needle)?);
    }
    Ok(Box::new(view))
}

/// `rich unicode`: every grapheme of the input, invalid UTF-8 included.
pub(crate) fn unicode(
    options: &ViewerOptions,
    bytes: &[u8],
) -> Result<Box<dyn Renderable>, String> {
    use rich_ext::unicode_inspect::UnicodeView;
    // A trailing newline from `echo` or a file end is not what was asked about.
    let bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes);
    let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes);
    let mut view = UnicodeView::from_bytes(bytes);
    if let Some(limit) = options.limit {
        view = view.limit(limit);
    }
    Ok(Box::new(view))
}

/// `rich env [PATTERN…]`: variables whose names match, redacted unless
/// `--show-secrets`; a single name of a PATH-like variable checks its entries.
pub(crate) fn env(options: &ViewerOptions, patterns: &[String]) -> Box<dyn Renderable> {
    use rich_ext::env_inspect::{is_path_like, name_matches, EnvView, PathView, OS_PATH_SEPARATOR};
    if let [name] = patterns {
        if let Ok(value) = std::env::var(name) {
            if is_path_like(name, &value, OS_PATH_SEPARATOR) {
                return Box::new(PathView::new(name.clone(), value, OS_PATH_SEPARATOR));
            }
        }
    }
    let vars = std::env::vars().filter(|(name, _)| {
        patterns.is_empty() || patterns.iter().any(|pattern| name_matches(pattern, name))
    });
    Box::new(EnvView::new(vars).redact(!options.show_secrets))
}

pub(crate) fn cast_path(options: &ViewerOptions) -> Option<&str> {
    options.cast.as_deref()
}

/// The redactor `--redact` (parsed with the `--inspect` options, which share
/// it) and `--redact-pattern` ask for, if any: the built-in detectors, then
/// each pattern. Masks keep their width, so the captured screen keeps its
/// layout.
pub(crate) fn capture_redactor(
    options: &ViewerOptions,
    redact: bool,
) -> Result<Option<rich_ext::redact::Redactor>, String> {
    use rich_ext::redact::Redactor;
    if !redact && options.redact_patterns.is_empty() {
        return Ok(None);
    }
    let mut redactor = if redact {
        Redactor::secrets()
    } else {
        Redactor::new()
    };
    for pattern in &options.redact_patterns {
        redactor = redactor
            .pattern(pattern)
            .map_err(|e| format!("--redact-pattern: {e}"))?;
    }
    Ok(Some(redactor.preserve_width(true)))
}

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

    #[test]
    fn detection_prefers_extensions_then_content() {
        assert_eq!(detect(Some("md"), None, b"# x"), ViewAs::Markdown);
        assert_eq!(detect(Some("patch"), None, b"x"), ViewAs::Patch);
        assert_eq!(detect(Some("png"), None, b"\x89PNG"), ViewAs::Image);
        assert_eq!(
            detect(Some("rs"), None, b"fn main() {}"),
            ViewAs::Source("rs".into())
        );
        assert_eq!(detect(Some("bin"), None, b"\x00\x01"), ViewAs::Binary);
        assert_eq!(detect(None, None, b"\xff\xfe\x00"), ViewAs::Binary);
        assert_eq!(
            detect(None, None, b"diff --git a/x b/x\n--- a/x\n+++ b/x\n"),
            ViewAs::Patch
        );
        assert_eq!(
            detect(None, None, b"{\"a\": 1}\n"),
            ViewAs::Source("json".into())
        );
        assert_eq!(
            detect(None, None, b"just words\n"),
            ViewAs::Source("txt".into())
        );
        // A multi-byte character cut at the sniffing boundary is still text.
        let mut long = vec![b'a'; 8191];
        long.extend("é".as_bytes());
        assert!(!looks_binary(&long));
    }

    #[test]
    fn options_parse_numbers_and_report_their_command() {
        let args: Vec<String> = ["0x20", "1_000"].iter().map(|s| s.to_string()).collect();
        let mut rest = args.iter();
        let mut options = ViewerOptions::default();
        assert!(options.parse_option("--offset", &mut rest).unwrap());
        assert!(options.parse_option("--length", &mut rest).unwrap());
        assert_eq!((options.offset, options.length), (Some(32), Some(1000)));
        assert!(!options.parse_option("--width", &mut rest).unwrap());
        assert_eq!(
            options.given(),
            [("--offset", &["hex"][..]), ("--length", &["hex"][..])]
        );
        let mut empty = [].iter();
        assert!(ViewerOptions::default()
            .parse_option("--group", &mut empty)
            .is_err());
    }

    #[test]
    fn search_summaries_count_matches_and_lines() {
        let options = ViewerOptions {
            search: Some("x".into()),
            ..Default::default()
        };
        assert_eq!(
            search_summary(&options, "x\ny\nxx\n").unwrap(),
            "3 matches for \"x\" on lines 1, 3"
        );
        assert_eq!(
            search_summary(&options, "y\n").unwrap(),
            "no matches for \"x\""
        );
        assert!(search_summary(&ViewerOptions::default(), "x").is_none());
    }

    #[test]
    fn shell_words_quote_only_when_needed() {
        let words: Vec<String> = ["ls", "-la", "my file", "it's"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(shell_words(&words), r"ls -la 'my file' 'it'\''s'");
    }

    fn captured(command: &[&str], chunks: &[&[u8]]) -> Captured {
        Captured {
            command: command.iter().map(|s| s.to_string()).collect(),
            chunks: chunks
                .iter()
                .enumerate()
                .map(|(i, bytes)| (Duration::from_millis(i as u64), bytes.to_vec()))
                .collect(),
            status: Some(1),
            signal: None,
            elapsed: Duration::from_millis(chunks.len() as u64),
            notice: None,
        }
    }

    fn redactor() -> rich_ext::redact::Redactor {
        capture_redactor(&ViewerOptions::default(), true)
            .unwrap()
            .unwrap()
    }

    #[test]
    fn redaction_keeps_characters_split_between_reads() {
        let text = format!("x{}\n", "é".repeat(10_000));
        let chunks: Vec<&[u8]> = text.as_bytes().chunks(8192).collect();
        let mut capture = captured(&["cat", "big.txt"], &chunks);
        capture.redact(&redactor());
        // Nothing to mask: the bytes are untouched, so nothing is lost.
        let after: Vec<&[u8]> = capture.chunks.iter().map(|(_, b)| b.as_slice()).collect();
        assert_eq!(after, chunks);
        assert_eq!(capture.output(), text.as_bytes());
        // Invalid bytes are not multiplied, and a secret is still masked.
        let mut capture = captured(&["x"], &[b"\xc3", b"\xa9\xff token=ab", b"c\n"]);
        capture.redact(&redactor());
        assert_eq!(capture.output(), b"\xc3\xa9\xff token=***\n");
    }

    #[test]
    fn casts_keep_characters_split_between_reads() {
        let text = format!("x{}\n", "é".repeat(10_000));
        let chunks: Vec<&[u8]> = text.as_bytes().chunks(8192).collect();
        let cast = asciicast(&captured(&["cat"], &chunks), 80, 24);
        assert!(!cast.contains('\u{fffd}'), "a split character was mangled");
        let data: String = cast
            .lines()
            .skip(1)
            .map(|line| {
                let event: serde_json::Value = serde_json::from_str(line).unwrap();
                event[2].as_str().unwrap().to_string()
            })
            .collect();
        assert_eq!(data, text.replace('\n', "\r\n"));
    }

    #[test]
    fn redaction_masks_secret_flag_values_on_the_command_line() {
        let mut capture = captured(
            &[
                "deploy",
                "--token",
                "hunter2",
                "--api-key=abc123",
                "-p",
                "80",
            ],
            &[b"ok\n"],
        );
        capture.redact(&redactor());
        let masked = [
            "deploy",
            "--token",
            "*******",
            "--api-key=******",
            "-p",
            "80",
        ];
        assert_eq!(capture.command, masked);
        let report = capture_report(&capture).to_string();
        assert!(
            !report.contains("hunter2") && !report.contains("abc123"),
            "{report}"
        );
        let cast = asciicast(&capture, 80, 24);
        let header = cast.lines().next().unwrap();
        assert!(
            !header.contains("hunter2") && !header.contains("abc123"),
            "{header}"
        );
    }

    #[test]
    fn line_ends_cut_after_the_last_line_kept() {
        assert_eq!(line_end(b"a\nb\nc\n", 2), Some(4));
        assert_eq!(line_end(b"a\nb\n", 2), None);
        assert_eq!(line_end(b"a\nb", 2), None);
        assert_eq!(line_end(b"a\nb\nc", 2), Some(4));
        assert_eq!(line_end(b"x", 0), Some(0));
        assert_eq!(line_end(b"", 0), None);
    }

    #[test]
    fn sanitizing_a_capture_sees_sequences_split_between_reads() {
        let mut capture = captured(
            &["x\u{1b}]0;T\u{7}"],
            &[b"a\x1b]0;ti", b"tle\x07b\xc2", b"\x9b2J\n\x1b[31mred\n"],
        );
        capture.sanitize();
        let output = String::from_utf8(capture.output()).unwrap();
        assert_eq!(output, "ab\\u{009B}2J\n\u{1b}[31mred\n");
        assert_eq!(capture.command, ["x␛]0;T␇"]);
        // The line ending in the middle of the first chunks goes out with
        // the chunk that finishes it.
        assert_eq!(capture.chunks.len(), 1);
    }

    #[cfg(unix)]
    #[test]
    fn capture_limits_bytes_and_lines() {
        let command = |script: &str| -> Vec<String> {
            ["sh", "-c", script].iter().map(|s| s.to_string()).collect()
        };
        let lines = capture_with_limits(&command("yes | head -n 50"), 40, 1 << 20, 10).unwrap();
        assert_eq!(String::from_utf8(lines.output()).unwrap(), "y\n".repeat(10));
        assert!(lines.notice.unwrap().contains("10 lines"));
        let bytes = capture_with_limits(&command("yes"), 40, 7, 1000).unwrap();
        assert_eq!(bytes.output(), b"y\ny\ny\ny");
        assert!(bytes.notice.as_deref().unwrap().contains("7 bytes"));
        assert_ne!(bytes.exit_code(), 0);
        let exact = capture_with_limits(&command("printf 'a\\nb\\n'"), 40, 4, 2).unwrap();
        assert_eq!(exact.output(), b"a\nb\n");
        assert!(exact.notice.is_none());
    }

    #[cfg(unix)]
    #[test]
    fn capture_records_output_status_and_a_cast() {
        let command: Vec<String> = ["sh", "-c", "printf 'a\\n'; printf 'b\\n' >&2; exit 3"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let captured = capture(&command, 40).unwrap();
        assert_eq!(captured.status, Some(3));
        assert_eq!(captured.exit_code(), 3);
        // One pipe keeps stdout and stderr in the order they were written.
        assert_eq!(String::from_utf8(captured.output()).unwrap(), "a\nb\n");
        let cast = asciicast(&captured, 40, 10);
        let mut lines = cast.lines();
        let header: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
        assert_eq!(header["version"], 2);
        assert_eq!(header["width"], 40);
        for line in lines {
            let event: serde_json::Value = serde_json::from_str(line).unwrap();
            assert_eq!(event[1], "o");
            assert!(event[2].as_str().unwrap().ends_with("\r\n"));
        }
        let console = rich::Console::builder()
            .width(40)
            .color_system(None)
            .build();
        let out = console.render_to_string(capture_view(&captured).as_ref());
        assert!(out.contains("$ sh -c"), "{out}");
        assert!(out.contains("exit 3"), "{out}");
        assert!(capture(&["definitely-not-a-command-xyz".to_string()], 40).is_err());
    }
}