rs-rich-cli 0.0.15

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
//! A self-contained tour of the public CLI and renderable APIs.
use super::*;
use std::sync::{Arc, Mutex};
use std::time::Duration;

type WatchChild = Arc<Mutex<Option<std::process::Child>>>;

/// Recognize a flag only in option position, never as an option's value.
pub(super) fn requested(args: &[String]) -> bool {
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        if arg == "--" {
            break;
        }
        if VALUE_OPTIONS.contains(&arg.as_str()) {
            iter.next();
            continue;
        }
        if matches!(arg.as_str(), "--demo" | "--demo-list") {
            return true;
        }
    }
    false
}

pub(super) fn dispatch(args: &[String]) -> ExitCode {
    let options = match options(args) {
        Ok(options) => options,
        Err(message) => return emit_error(false, ExitClass::Usage, &message),
    };
    if options.list {
        println!("core       Core renderables and extensions");
        println!("workflows  Configuration, batch, exports, watch, inspectors and capture");
        println!(
            "art        {}",
            if cfg!(feature = "art") {
                "Banners, images, image diff and GIF"
            } else {
                "unavailable (build without art feature)"
            }
        );
        return ExitCode::SUCCESS;
    }
    match tour(options.no_color, options.delay, options.group.as_deref()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => emit_error(false, ExitClass::Input, &format!("demo: {error}")),
    }
}

struct Options {
    no_color: bool,
    delay: Duration,
    group: Option<String>,
    list: bool,
}

fn options(args: &[String]) -> Result<Options, String> {
    let mut no_color = std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty());
    let mut seconds = 3.0;
    let mut group = None;
    let mut list = false;
    let mut play = false;
    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--demo" => play = true,
            "--demo-list" => list = true,
            "--no-config" => {}
            "--no-color" => no_color = true,
            "--demo-section" => {
                let value = iter.next().ok_or("--demo-section requires core, workflows, art")?;
                if !matches!(value.as_str(), "core" | "workflows" | "art") {
                    return Err(format!("unknown demo section {value:?}; choose core, workflows, art"));
                }
                group = Some(value.clone());
            }
            "--demo-delay" => {
                seconds = iter.next().and_then(|value| value.parse::<f64>().ok())
                    .filter(|value| value.is_finite() && (0.0..=60.0).contains(value))
                    .ok_or("--demo-delay expects seconds between 0 and 60")?;
            }
            _ => return Err(format!("demo accepts only --demo, --demo-list, --demo-section NAME, --demo-delay SECONDS, --no-color and --no-config; unexpected {arg}")),
        }
    }
    if list && (play || group.is_some()) {
        return Err("--demo-list cannot be combined with --demo or --demo-section".into());
    }
    if !list && !play {
        return Err("--demo-section requires --demo".into());
    }
    if group.as_deref() == Some("art") && !cfg!(feature = "art") {
        return Err("art demo is unavailable in this build; rebuild with the art feature".into());
    }
    // A pipe gets a finite transcript, without terminal pauses or controls.
    Ok(Options {
        no_color,
        delay: if std::io::stdout().is_terminal() {
            Duration::from_secs_f64(seconds)
        } else {
            Duration::ZERO
        },
        group,
        list,
    })
}

pub(super) fn section(console: &Console, delay: Duration, title: &str) {
    if !delay.is_zero() {
        let _ = std::io::stdout().flush();
        std::thread::sleep(delay);
    }
    console.print(&Rule::new(title));
}

fn command(
    console: &Console,
    no_color: bool,
    label: &str,
    args: Vec<String>,
) -> std::io::Result<()> {
    console.print(&Text::new(format!("$ rich {label}")));
    let mut full = vec!["--no-pager".to_owned()];
    if !args.iter().any(|arg| arg == "--config") {
        full.push("--no-config".into());
    }
    if no_color {
        full.push("--no-color".into());
    }
    full.extend(args);
    let cli = parse(&full).map_err(std::io::Error::other)?;
    if let Some(cli) = cli {
        if run_cli(cli) != ExitCode::SUCCESS {
            return Err(std::io::Error::other(format!("example failed: {label}")));
        }
    }
    Ok(())
}

fn strings(args: &[&str]) -> Vec<String> {
    args.iter().map(|arg| (*arg).to_owned()).collect()
}

fn tour(no_color: bool, delay: Duration, group: Option<&str>) -> std::io::Result<()> {
    println!("rich --demo: guided suite tour (3 seconds per section by default). Ctrl+C to stop.");
    println!("Examples are offline; exports use a temporary directory. Configuration is ignored.");
    let root = tempfile::tempdir()?;
    let watch_child: WatchChild = Arc::new(Mutex::new(None));
    // GIF playback owns Rust's stdout lock. Duplicate the OS handle so
    // terminal restoration never waits for that lock; pipes need no controls.
    let mut terminal = if std::io::stdout().is_terminal() {
        #[cfg(unix)]
        let terminal = {
            use std::os::fd::AsFd;
            std::fs::File::from(std::io::stdout().as_fd().try_clone_to_owned()?)
        };
        #[cfg(windows)]
        let terminal = {
            use std::os::windows::io::AsHandle;
            std::fs::File::from(std::io::stdout().as_handle().try_clone_to_owned()?)
        };
        Some(terminal)
    } else {
        None
    };
    let cleanup = root.path().to_owned();
    let child = Arc::clone(&watch_child);
    ctrlc::set_handler(move || {
        if let Ok(mut slot) = child.lock() {
            if let Some(mut child) = slot.take() {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
        let _ = std::fs::remove_dir_all(&cleanup);
        if let Some(terminal) = terminal.as_mut() {
            let _ = terminal.write_all(b"\x1b[?25h\x1b[0m\n");
            let _ = terminal.flush();
        }
        std::process::exit(130);
    })
    .map_err(std::io::Error::other)?;
    let console = if group.is_none() || group == Some("core") {
        run_demo(no_color, delay)
    } else {
        build_demo_console(no_color)
    };
    if group.is_none() || group == Some("workflows") {
        let file = |name: &str| root.path().join(name).to_string_lossy().into_owned();
        let release_json = format!(
            "{{\"release\":\"{}\",\"ready\":true}}",
            env!("CARGO_PKG_VERSION")
        );
        for (name, contents) in [
        ("first.json", release_json.as_str()),
        ("second.json", "{\"features\":[\"config\",\"batch\",\"art\"]}"),
        ("events.jsonl", "{\"event\":\"start\",\"count\":1}\n{\"event\":\"finish\",\"count\":2}\n"),
        ("logs.jsonl", "{\"level\":\"info\",\"message\":\"Tour started\"}\n{\"level\":\"warn\",\"message\":\"Example warning\"}\n"),
        ("notes.ipynb", r##"{"nbformat":4,"nbformat_minor":5,"metadata":{},"cells":[{"cell_type":"markdown","metadata":{},"source":["# Notebook\n","Rich renders notebook cells."]},{"cell_type":"code","metadata":{},"execution_count":1,"source":["print('vroom vroom')"],"outputs":[{"output_type":"stream","name":"stdout","text":["vroom vroom\n"]}]}]}"##),
        ("demo.toml", "[defaults]\nwidth = 60\n[profiles.preview]\npanel = 'rounded'\n"),
    ] { std::fs::write(file(name), contents)?; }

        for (title, mode, name) in [
            ("JSON Lines", "--jsonl", "events.jsonl"),
            ("Structured logs", "--log", "logs.jsonl"),
            ("Notebook", "--ipynb", "notes.ipynb"),
        ] {
            section(&console, delay, title);
            command(
                &console,
                no_color,
                &format!("{mode} {name}"),
                vec![mode.into(), file(name)],
            )?;
        }
        section(&console, delay, "Typed event presentation");
        command(
            &console,
            no_color,
            "--log logs.jsonl --log-presentation rich",
            vec![
                "--log".into(),
                file("logs.jsonl"),
                "--log-presentation".into(),
                "rich".into(),
            ],
        )?;
        section(&console, delay, "Configuration profiles");
        console.print(&Text::new(
            "$ rich --config demo.toml --profile preview config show",
        ));
        let args = vec![
            "--config".into(),
            file("demo.toml"),
            "--profile".into(),
            "preview".into(),
            "config".into(),
            "show".into(),
        ];
        let output = config::inspect(&args, &ConfigRoots::default())
            .map_err(std::io::Error::other)?
            .ok_or_else(|| std::io::Error::other("config example produced no result"))?;
        console.print(&Json::new(&output).map_err(std::io::Error::other)?);
        command(
            &console,
            no_color,
            "--config demo.toml --profile preview first.json",
            vec![
                "--config".into(),
                file("demo.toml"),
                "--profile".into(),
                "preview".into(),
                file("first.json"),
            ],
        )?;

        section(&console, delay, "Batch planning");
        let exports = root.path().join("exports");
        std::fs::create_dir(&exports)?;
        let export = exports.join("out.html").to_string_lossy().into_owned();
        command(
            &console,
            no_color,
            "--batch --dry-run --export-html exports/out.html first.json second.json",
            vec![
                "--batch".into(),
                "--dry-run".into(),
                "--export-html".into(),
                export.clone(),
                file("first.json"),
                file("second.json"),
            ],
        )?;
        section(&console, delay, "Parallel exports");
        command(
            &console,
            no_color,
            "--batch --jobs 2 --export-html exports/out.html first.json second.json",
            vec![
                "--batch".into(),
                "--jobs".into(),
                "2".into(),
                "--export-html".into(),
                export,
                file("first.json"),
                file("second.json"),
            ],
        )?;
        console.print(&Text::new(
            "Created first.html and second.html in the temporary demo directory.",
        ));
        command(
            &console,
            no_color,
            "--json first.json --export-svg preview.svg",
            vec![
                "--json".into(),
                file("first.json"),
                "--export-svg".into(),
                file("preview.svg"),
            ],
        )?;
        console.print(&Text::new(
            "Created preview.svg; all demo exports are removed when the tour finishes.",
        ));

        section(&console, delay, "Watch updates");
        watch(
            &console,
            no_color,
            [&file("first.json"), &file("second.json")],
            &watch_child,
        )?;
        tools(&console, no_color, delay, root.path())?;
        additions_012(&console, no_color, delay, root.path())?;
        additions_013(&console, no_color, delay, root.path())?;
        section(&console, delay, "Pager, input and confidence controls");
        console.print(&Text::new("--auto-pager opens a pager for tall TTY output; --no-pager opts out.\nURL fetch, encoding, sanitization and JSON reports support scripts and CI.\nThe tour stays offline and does not open an external pager."));
        command(
            &console,
            no_color,
            "--print --sanitize '<ESC>[31m visible controls'",
            strings(&["--print", "--sanitize", "\x1b[31m visible controls"]),
        )?;
    }

    if group.is_none() || group == Some("art") {
        #[cfg(feature = "art")]
        art(&console, no_color, delay, root.path())?;
        #[cfg(not(feature = "art"))]
        {
            section(&console, delay, "Rich art");
            console.print(&Text::new("The art feature is disabled in this build; enable it for FIGlet, images, GIF and image diff."));
        }
    }
    section(&console, delay, "Tour complete");
    console.print(&Text::new(
        "Try rich --help for every option. Run rich --demo again to replay the tour.",
    ));
    Ok(())
}

/// The 0.0.11 inspectors and viewers: structured data, text diffs, the
/// universal viewer, byte/grapheme/escape inspectors, theme files and a
/// redacted capture. Every input is written into the tour's temporary
/// directory, and the captured command is a shell one-liner, so it stays
/// offline and portable.
fn tools(console: &Console, no_color: bool, delay: Duration, root: &Path) -> std::io::Result<()> {
    let file = |name: &str| root.join(name).to_string_lossy().into_owned();
    for (name, contents) in [
        (
            "deploy.yaml",
            "service: api\nreplicas: 3\nimage:\n  name: rs-rich\n  tag: \"0.0.11\"\nports: [8080, 8443]\n",
        ),
        ("old.toml", "retries = 2\ntimeout = 30\nmode = \"fast\"\n"),
        ("new.toml", "retries = 3\ntimeout = 30\nmode = \"safe\"\nlog = true\n"),
        ("text.txt", "café 👩‍👩‍👧\n"),
        ("codes.txt", "\x1b[1;31mError\x1b[0m done\n"),
        ("demo.theme", "[styles]\nrelease = bold magenta\n"),
    ] {
        std::fs::write(file(name), contents)?;
    }
    let run = |label: &str, args: &[&str]| {
        let args = args
            .iter()
            .map(|arg| match *arg {
                "deploy.yaml" | "old.toml" | "new.toml" | "text.txt" | "codes.txt"
                | "demo.theme" => file(arg),
                other => other.to_owned(),
            })
            .collect();
        command(console, no_color, label, args)
    };

    section(console, delay, "Inspect structured data");
    run("inspect deploy.yaml", &["inspect", "deploy.yaml"])?;
    section(console, delay, "Text diffs");
    run("diff old.toml new.toml", &["diff", "old.toml", "new.toml"])?;
    section(console, delay, "View any file");
    run("view deploy.yaml", &["view", "deploy.yaml"])?;
    section(console, delay, "Bytes, graphemes and escape sequences");
    run("hex text.txt", &["hex", "text.txt"])?;
    run("unicode text.txt", &["unicode", "text.txt"])?;
    run("ansi explain codes.txt", &["ansi", "explain", "codes.txt"])?;
    section(console, delay, "Upstream theme files");
    run(
        "--theme-file demo.theme --print '[release]0.0.11[/] adds inspectors'",
        &[
            "--theme-file",
            "demo.theme",
            "--print",
            "[release]0.0.11[/] adds inspectors",
        ],
    )?;
    section(console, delay, "Capture a command, with redaction");
    console.print(&Text::new(
        "Redaction is experimental and best effort: check captures before sharing them.",
    ));
    let secret = "echo deploy token=ghp_0123456789abcdefghijklmnopqrstuvwxyzAB";
    #[cfg(windows)]
    let shell = ["cmd", "/C"];
    #[cfg(not(windows))]
    let shell = ["sh", "-c"];
    run(
        &format!("capture --redact -- {} {} '{secret}'", shell[0], shell[1]),
        &["capture", "--redact", "--", shell[0], shell[1], secret],
    )
}

/// The 0.0.12 additions: a Mermaid flowchart drawn as text, code in the
/// terminal's own palette, and filtering and highlighting matching lines.
/// Every input is written into the tour's temporary directory.
fn additions_012(
    console: &Console,
    no_color: bool,
    delay: Duration,
    root: &Path,
) -> std::io::Result<()> {
    let file = |name: &str| root.join(name).to_string_lossy().into_owned();
    for (name, contents) in [
        (
            "flow.mmd",
            "flowchart LR\n    core[rs-rich] --> api[plugin API]\n    api --> mermaid[Mermaid]\n    api --> lumis[lumis]\n    mermaid --> cli([rich])\n",
        ),
        (
            "worker.rs",
            "fn retry(job: &Job, attempts: u32) -> Result<(), Error> {\n    for n in 0..attempts {\n        if job.run().is_ok() {\n            return Ok(());\n        }\n    }\n    Err(Error::GaveUp(attempts))\n}\n",
        ),
        (
            "service.log",
            "INFO  api listening on :8080\nERROR upstream timeout after 30s\nINFO  retrying upstream\nERROR connection refused by db:5432\nINFO  recovered\n",
        ),
    ] {
        std::fs::write(file(name), contents)?;
    }
    #[cfg(feature = "mermaid")]
    {
        section(console, delay, "Mermaid flowcharts");
        command(
            console,
            no_color,
            "mermaid flow.mmd",
            vec!["mermaid".into(), file("flow.mmd")],
        )?;
    }
    section(console, delay, "Code themes");
    command(
        console,
        no_color,
        "--syntax worker.rs --code-theme ansi_dark",
        vec![
            "--syntax".into(),
            file("worker.rs"),
            "--code-theme".into(),
            "ansi_dark".into(),
        ],
    )?;
    section(console, delay, "Filter and highlight");
    command(
        console,
        no_color,
        "service.log --filter ERROR --highlight 'timeout|refused'",
        vec![
            file("service.log"),
            "--filter".into(),
            "ERROR".into(),
            "--highlight".into(),
            "timeout|refused".into(),
        ],
    )
}

/// The 0.0.13 additions: rich-cli's own options (line numbers, guides,
/// `--head`), reStructuredText, and a `rich choose` picker. The tour runs
/// unattended, so the picker is drawn headless, with the keys a user would
/// press, rather than waiting on the terminal.
fn additions_013(
    console: &Console,
    no_color: bool,
    delay: Duration,
    root: &Path,
) -> std::io::Result<()> {
    let file = |name: &str| root.join(name).to_string_lossy().into_owned();
    std::fs::write(
        file("release.rst"),
        "Release 0.0.13\n==============\n\nAsk, choose and browse from a script:\n\n* ``rich choose`` picks one item\n* ``rich filter`` narrows a list as you type\n* ``rich confirm`` answers with its exit code\n\n.. note:: Keys come from the terminal even when stdin is the list.\n",
    )?;
    section(console, delay, "rich-cli options");
    command(
        console,
        no_color,
        "--syntax worker.rs -n --guides --head 5",
        vec![
            "--syntax".into(),
            file("worker.rs"),
            "-n".into(),
            "--guides".into(),
            "--head".into(),
            "5".into(),
        ],
    )?;
    section(console, delay, "reStructuredText");
    command(
        console,
        no_color,
        "--rst release.rst",
        vec!["--rst".into(), file("release.rst")],
    )?;
    #[cfg(feature = "interact")]
    {
        use rich_interact::{headless, Select};
        section(console, delay, "Ask in a script");
        console.print(&Text::new(
            "$ fruit=$(rich choose apple banana cherry)   # ↓ then Enter",
        ));
        let select = Select::new("Pick a fruit", ["apple", "banana", "cherry"]);
        let (_, record) = headless::run(select, headless::Script::new().keys("down"), 60, 6);
        console.print(
            &Panel::new(Box::new(Text::new(
                record.last_frame().trim_end().to_owned(),
            )))
            .title("drawn headless: the keys a user would press"),
        );
        console.print(&Text::new(
            "$ echo \"$fruit\"\nbanana\n$ ls | rich filter --value toml    # without a terminal: a fuzzy grep\n$ rich confirm 'Deploy?' && deploy  # exit 0 for yes, 1 for no",
        ));
    }
    Ok(())
}

/// Watch two files, each in its own Live region. The tour cannot deliver a
/// portable Ctrl+C to the child, so the last edit writes invalid JSON and
/// `--watch-exit-on-error` ends the watch, restoring the terminal itself.
fn watch(
    console: &Console,
    no_color: bool,
    [first, second]: [&str; 2],
    slot: &WatchChild,
) -> std::io::Result<()> {
    if !std::io::stdout().is_terminal() {
        for value in [1, 2] {
            std::fs::write(first, format!("{{\"live_update\":{value}}}"))?;
            command(
                console,
                no_color,
                "--watch first.json second.json (one snapshot each when redirected)",
                vec!["--watch".into(), first.into(), second.into()],
            )?;
        }
        return Ok(());
    }
    console.print(&Text::new(
        "$ rich --watch --watch-exit-on-error first.json second.json\n  \
         (two edits to first.json repaint only its region; invalid JSON then ends the watch)",
    ));
    // Run beside the files and pass bare names, so the region headers read
    // `first.json` rather than a temporary path.
    let (first_path, second_path) = (Path::new(first), Path::new(second));
    let mut cmd = super::self_command()?;
    if let Some(directory) = first_path.parent() {
        cmd.current_dir(directory);
    }
    cmd.args([
        "--no-config",
        "--no-pager",
        "--watch",
        "--watch-debounce",
        "0.1",
    ]);
    cmd.arg("--watch-exit-on-error");
    cmd.args(
        [first_path.file_name(), second_path.file_name()]
            .into_iter()
            .flatten(),
    );
    if no_color {
        cmd.arg("--no-color");
    }
    *slot.lock().unwrap() = Some(cmd.spawn()?);
    let result = (|| {
        for value in [1, 2] {
            std::thread::sleep(Duration::from_millis(700));
            std::fs::write(first, format!("{{\"live_update\":{value}}}"))?;
        }
        std::thread::sleep(Duration::from_millis(700));
        if let Some(status) = slot.lock().unwrap().as_mut().unwrap().try_wait()? {
            return Err(std::io::Error::other(format!(
                "watch stopped early: {status}"
            )));
        }
        std::fs::write(first, "{\"live_update\": ")?;
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        loop {
            if let Some(status) = slot.lock().unwrap().as_mut().unwrap().try_wait()? {
                return if status.success() {
                    Err(std::io::Error::other("watch ignored the invalid edit"))
                } else {
                    Ok(())
                };
            }
            if std::time::Instant::now() >= deadline {
                return Err(std::io::Error::other(
                    "watch did not stop on the invalid edit",
                ));
            }
            std::thread::sleep(Duration::from_millis(50));
        }
    })();
    if let Some(mut child) = slot.lock().unwrap().take() {
        let _ = child.kill();
        let _ = child.wait();
    }
    result
}

#[cfg(feature = "art")]
fn art(console: &Console, no_color: bool, delay: Duration, root: &Path) -> std::io::Result<()> {
    use rich_art::image::{Rgba, RgbaImage};
    section(console, delay, "FIGlet banners");
    console.print(&rich_art::Figlet::new("RICH"));
    let image = RgbaImage::from_fn(120, 60, |x, y| {
        let inside = (x as i32 - 38).pow(2) + (y as i32 - 30).pow(2) < 24 * 24;
        if inside {
            Rgba([255, 110, 190, 255])
        } else if x > 78 && y > 12 && y < 48 {
            Rgba([70, 220, 255, 210])
        } else {
            Rgba([0, 0, 0, 0])
        }
    });
    let source = root.join("art.png");
    image.save(&source).map_err(std::io::Error::other)?;
    let source = source.to_string_lossy().into_owned();
    let width = console.width().clamp(1, 48).to_string();
    for (label, mode) in [
        ("Braille", "braille"),
        ("Half-block", "blocks"),
        ("ASCII", "ascii"),
    ] {
        section(console, delay, label);
        command(console, no_color, &format!("--image art.png --image-mode {mode} --width {width} --height 12 --image-background '#142032'"), vec!["--image".into(), source.clone(), "--image-mode".into(), mode.into(), "--width".into(), width.clone(), "--height".into(), "12".into(), "--image-background".into(), "#142032".into()])?;
    }
    section(console, delay, "Rotation, grayscale and Bayer dithering");
    command(console, no_color, "--image art.png --image-rotate 90 --image-grayscale --image-color ansi256 --image-dither bayer4x4", vec!["--image".into(), source.clone(), "--image-mode".into(), "blocks".into(), "--width".into(), width.clone(), "--image-rotate".into(), "90".into(), "--image-grayscale".into(), "--image-color".into(), "ansi256".into(), "--image-dither".into(), "bayer4x4".into()])?;
    section(
        console,
        delay,
        "Quadrant blocks, ANSI16 and tone adjustments",
    );
    for (shown, extra) in [
        ("--image-mode quadrants", vec![]),
        (
            "--image-mode quadrants --image-color ansi16 --image-dither floyd-steinberg",
            vec![
                "--image-color",
                "ansi16",
                "--image-dither",
                "floyd-steinberg",
            ],
        ),
        (
            "--image-mode quadrants --image-brightness 1.3 --image-contrast 1.6 --image-gamma 0.7",
            vec![
                "--image-brightness",
                "1.3",
                "--image-contrast",
                "1.6",
                "--image-gamma",
                "0.7",
            ],
        ),
    ] {
        let mut args: Vec<String> = [
            "--image",
            &source,
            "--image-mode",
            "quadrants",
            "--width",
            &width,
            "--height",
            "12",
            "--image-background",
            "#142032",
        ]
        .iter()
        .map(|arg| arg.to_string())
        .collect();
        args.extend(extra.iter().map(|arg| arg.to_string()));
        command(
            console,
            no_color,
            &format!("--image art.png {shown} --width {width} --height 12"),
            args,
        )?;
    }
    section(
        console,
        delay,
        "Atkinson dithering, OKLab colours and alpha backgrounds",
    );
    for (shown, extra) in [
        (
            "--image-color ansi16 --image-dither atkinson --image-color-distance oklab",
            &[
                "--image-color",
                "ansi16",
                "--image-dither",
                "atkinson",
                "--image-color-distance",
                "oklab",
            ][..],
        ),
        (
            "--image-background checkerboard",
            &["--image-background", "checkerboard"][..],
        ),
        (
            "--image-background default",
            &["--image-background", "default"][..],
        ),
    ] {
        let mut args: Vec<String> = [
            "--image",
            &source,
            "--image-mode",
            "quadrants",
            "--width",
            &width,
            "--height",
            "12",
        ]
        .iter()
        .map(|arg| arg.to_string())
        .collect();
        args.extend(extra.iter().map(|arg| arg.to_string()));
        command(
            console,
            no_color,
            &format!("--image art.png --image-mode quadrants {shown} --width {width} --height 12"),
            args,
        )?;
    }
    section(console, delay, "Crop anchors and transparent backgrounds");
    for anchor in ["left", "center", "right"] {
        command(
            console,
            no_color,
            &format!(
                "--image art.png --image-fit cover --image-anchor {anchor} --width 20 --height 12"
            ),
            vec![
                "--image".into(),
                source.clone(),
                "--image-mode".into(),
                "ascii".into(),
                "--image-fit".into(),
                "cover".into(),
                "--image-anchor".into(),
                anchor.into(),
                "--width".into(),
                "20".into(),
                "--height".into(),
                "12".into(),
                "--image-background".into(),
                "#142032".into(),
            ],
        )?;
    }
    command(
        console,
        no_color,
        "--image art.png --image-mode blocks --image-fit contain --width 40 --height 10",
        vec![
            "--image".into(),
            source.clone(),
            "--image-mode".into(),
            "blocks".into(),
            "--image-fit".into(),
            "contain".into(),
            "--width".into(),
            "40".into(),
            "--height".into(),
            "10".into(),
        ],
    )?;
    section(console, delay, "Native image size");
    let sprite = RgbaImage::from_fn(24, 16, |x, y| {
        if (x as i32 - 12).pow(2) + (y as i32 - 8).pow(2) < 7 * 7 {
            Rgba([255, 196, 0, 255])
        } else if y > 13 {
            Rgba([60, 170, 90, 255])
        } else {
            Rgba([40, 60, 120, 255])
        }
    });
    let sprite_path = root.join("sprite.png");
    sprite.save(&sprite_path).map_err(std::io::Error::other)?;
    command(
        console,
        no_color,
        "--image sprite.png --image-fit native --image-mode quadrants",
        vec![
            "--image".into(),
            sprite_path.to_string_lossy().into_owned(),
            "--image-fit".into(),
            "native".into(),
            "--image-mode".into(),
            "quadrants".into(),
        ],
    )?;
    section(console, delay, "Image diff");
    let mut changed = image.clone();
    for y in 20..30 {
        for x in 30..40 {
            changed.put_pixel(x, y, Rgba([255, 255, 255, 255]));
        }
    }
    let after = root.join("after.png");
    changed.save(&after).map_err(std::io::Error::other)?;
    command(
        console,
        no_color,
        "--diff art.png after.png --image-mode ascii --width 40",
        vec![
            "--diff".into(),
            source,
            after.to_string_lossy().into_owned(),
            "--image-mode".into(),
            "ascii".into(),
            "--width".into(),
            "40".into(),
        ],
    )?;
    section(console, delay, "GIF animation");
    let mut bytes = Vec::new();
    {
        let mut encoder = rich_art::image::codecs::gif::GifEncoder::new(&mut bytes);
        for frame in [image, changed] {
            encoder
                .encode_frame(rich_art::image::Frame::from_parts(
                    frame,
                    0,
                    0,
                    rich_art::image::Delay::from_numer_denom_ms(500, 1),
                ))
                .map_err(std::io::Error::other)?;
        }
    }
    let animation = rich_art::AnimatedArt::from_bytes(&bytes)
        .map_err(std::io::Error::other)?
        .width(40)
        .height(10);
    if std::io::stdout().is_terminal() {
        let path = root.join("demo.gif");
        std::fs::write(&path, bytes)?;
        command(
            console,
            no_color,
            "--gif demo.gif --loop 1 --width 40",
            vec![
                "--gif".into(),
                path.to_string_lossy().into_owned(),
                "--loop".into(),
                "1".into(),
                "--width".into(),
                "40".into(),
            ],
        )?;
    } else {
        console.print(&Text::new("GIF frames (animation plays in a terminal):"));
        for index in 0..animation.frame_count() {
            if let Some(frame) = animation.frame(index) {
                console.print(&frame);
            }
        }
    }
    console.print(&Text::new(
        "Sixel is available on compatible terminals; this tour uses portable image modes.",
    ));
    Ok(())
}