rs-rich-cli 0.0.20

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
//! `rich record TAPE…`: run scripted terminal sessions and render them
//! (rs-rich-record, #599). Not upstream: a CLI convenience over the
//! rs-rich-record library.
use super::*;

use std::path::{Path, PathBuf};

use rich_record::record::{self as recorder, Formats, Options};
use rich_record::render::raster::Fonts;
use rich_record::tape;

/// Whether the first word that is not an option is `record`, with no render
/// mode flag before it (`rich -p record` prints the word).
pub(super) fn requested(args: &[String]) -> bool {
    subcommand_word(args) == Some("record")
}

struct Args {
    tapes: Vec<PathBuf>,
    output: PathBuf,
    bin_dir: Option<PathBuf>,
    check: bool,
    formats: Formats,
    font: Option<PathBuf>,
    /// `--window-frame`, `--caption` and `--key-overlay`: over the tape's.
    window_frame: Option<bool>,
    caption: Option<String>,
    key_overlay: Option<bool>,
    /// `--fps`: video frames a second, over the tape's `Set Framerate`.
    fps: Option<f64>,
}

fn parse_formats(value: &str) -> Result<Formats, String> {
    let mut formats = Formats::NONE;
    for name in value.split(',').map(str::trim).filter(|n| !n.is_empty()) {
        match name {
            "all" => formats = Formats::ALL,
            other => match tape::Format::parse(other) {
                Some(format) => formats.set(format, true),
                None => {
                    return Err(format!(
                        "unknown --format {other:?} (choose from png, svg, cast, gif, apng, \
                         mp4, html, all)"
                    ))
                }
            },
        }
    }
    Ok(formats)
}

fn parse_switch(name: &str, value: &str) -> Result<bool, String> {
    match value {
        "on" | "true" => Ok(true),
        "off" | "false" => Ok(false),
        other => Err(format!("{name} takes on or off, not {other:?}")),
    }
}

fn parse_args(args: &[String]) -> Result<Args, String> {
    let mut parsed = Args {
        tapes: Vec::new(),
        output: PathBuf::from("recordings"),
        bin_dir: std::env::current_exe()
            .ok()
            .and_then(|exe| exe.parent().map(Path::to_path_buf)),
        check: false,
        formats: Formats::ALL,
        font: None,
        window_frame: None,
        caption: None,
        key_overlay: None,
        fps: None,
    };
    let mut seen_command = false;
    let mut iter = args.iter();
    let mut options_done = false;
    while let Some(arg) = iter.next() {
        if options_done || !arg.starts_with('-') || arg == "-" {
            if !seen_command && arg == "record" {
                seen_command = true;
            } else {
                parsed.tapes.push(fs_path(arg));
            }
            continue;
        }
        let (name, inline) = match arg.split_once('=') {
            Some((name, value)) if name.starts_with("--") => (name, Some(value.to_string())),
            _ => (arg.as_str(), None),
        };
        let mut value = || -> Result<String, String> {
            match inline.clone() {
                Some(value) => Ok(value),
                None => iter
                    .next()
                    .cloned()
                    .ok_or_else(|| format!("{name} needs a value")),
            }
        };
        match name {
            "--" => options_done = true,
            "--check" => parsed.check = true,
            "--no-video" => {
                parsed.formats.gif = false;
                parsed.formats.apng = false;
                parsed.formats.mp4 = false;
                parsed.formats.html = false;
            }
            "--fps" => {
                let text = value()?;
                let fps = text
                    .parse::<f64>()
                    .ok()
                    .filter(|fps| tape::FRAME_RATES.contains(fps))
                    .ok_or_else(|| format!("--fps takes frames a second, 1 to 60, not {text:?}"))?;
                parsed.fps = Some(fps);
            }
            "--output" | "-o" => parsed.output = fs_path(&value()?),
            "--bin-dir" => parsed.bin_dir = Some(fs_path(&value()?)),
            "--format" => parsed.formats = parse_formats(&value()?)?,
            "--font" => parsed.font = Some(fs_path(&value()?)),
            "--window-frame" => parsed.window_frame = Some(parse_switch(name, &value()?)?),
            "--key-overlay" => parsed.key_overlay = Some(parse_switch(name, &value()?)?),
            "--caption" => parsed.caption = Some(value()?),
            "--no-color" | "--no-config" => {}
            other => return Err(format!("unknown option {other} for `rich record`")),
        }
    }
    if parsed.tapes.is_empty() {
        return Err("`rich record` needs at least one TAPE".into());
    }
    Ok(parsed)
}

/// A tape's name: its file name without the extension.
fn stem(path: &Path) -> String {
    path.file_stem()
        .map_or_else(|| "tape".into(), |s| s.to_string_lossy().into_owned())
}

pub(super) fn dispatch(args: &[String]) -> ExitCode {
    let json = wants_json_report(args);
    if args
        .iter()
        .take_while(|arg| *arg != "--")
        .any(|arg| arg == "--help")
    {
        let no_color = cli_spec::no_color_requested(args);
        if let Some(help) = cli_spec::subcommand_help(&["record"], no_color) {
            authoring::out(&format!("{help}\n"));
        }
        return ExitCode::SUCCESS;
    }
    let args = match parse_args(args) {
        Ok(args) => args,
        Err(message) => {
            return emit_error(
                json,
                ExitClass::Usage,
                &format!("{message} (try `rich record --help`)"),
            )
        }
    };
    let fonts = match &args.font {
        Some(path) => match std::fs::read(path)
            .map_err(|e| e.to_string())
            .and_then(Fonts::load)
        {
            Ok(fonts) => fonts,
            Err(error) => {
                return emit_error(
                    json,
                    ExitClass::Input,
                    &format!("cannot load --font {}: {error}", path.display()),
                )
            }
        },
        None => Fonts::embedded(),
    };
    let options = Options {
        bin_dir: args.bin_dir.clone(),
        repo: std::env::current_dir().ok(),
        frame_rate: args.fps,
        ..Options::default()
    };
    // A tape's name picks its output directory (`--output/<stem>`), which
    // `write` fills and prunes: `...tape` would name `..`, the directory
    // above. Refused, for every tape, before anything runs.
    for path in &args.tapes {
        let stem = stem(path);
        if !recorder::stem_allowed(&stem) {
            return emit_error(
                json,
                ExitClass::Input,
                &format!(
                    "{}: the tape's name {stem:?} cannot name a recording directory; \
                     rename the tape",
                    path.display()
                ),
            );
        }
    }
    let mut failures = 0;
    // Each warning about the machine once, not once per tape.
    let mut warned = std::collections::BTreeSet::new();
    for path in &args.tapes {
        let stem = stem(path);
        let shown = path.display();
        let source = match std::fs::read(path) {
            Ok(source) => source,
            Err(error) => {
                return emit_error(
                    json,
                    ExitClass::Input,
                    &format!("cannot read {shown}: {error}"),
                )
            }
        };
        let parsed = match tape::parse(&String::from_utf8_lossy(&source)) {
            Ok(parsed) => parsed,
            Err(error) => return emit_error(json, ExitClass::Input, &format!("{shown}: {error}")),
        };
        eprintln!("{shown}");
        for warning in recorder::warnings(&parsed) {
            if warned.insert(warning.clone()) {
                eprintln!("  warning: {warning}");
            }
        }
        if let Some(warning) = no_shared_format(&parsed.outputs, args.formats) {
            eprintln!("  warning: {warning}");
        }
        let mut recording = match recorder::record(&parsed, &stem, &options) {
            Ok(recording) => recording,
            Err(error) => {
                eprintln!("  FAILED: {error}");
                failures += 1;
                continue;
            }
        };
        let dir = args.output.join(&stem);
        if args.check {
            let problems = recorder::check(&recording, &dir);
            for (name, _) in &recording.shots {
                let bad = problems
                    .iter()
                    .any(|p| matches!(p, recorder::Problem::Differs { name: n, .. } if n == name));
                eprintln!("  {name}: {}", if bad { "DIFFERS" } else { "ok" });
            }
            for problem in &problems {
                if let recorder::Problem::Orphaned { name } = problem {
                    eprintln!("  {name}: ORPHANED");
                }
            }
            for problem in &problems {
                eprintln!("{stem}: {problem}");
            }
            failures += problems.len();
            continue;
        }
        let presentation = &mut recording.presentation;
        if let Some(window) = args.window_frame {
            presentation.window = window;
        }
        if let Some(caption) = &args.caption {
            presentation.caption = Some(caption.clone()).filter(|c| !c.is_empty());
        }
        if let Some(keys) = args.key_overlay {
            presentation.key_overlay = keys;
        }
        match recorder::write_selected(
            &recording,
            &dir,
            &stem,
            args.formats,
            &fonts,
            &options.theme,
            Some((path, &source)),
        ) {
            Ok(written) => {
                for file in &written.paths {
                    eprintln!("  {}", file.display());
                }
                for skipped in &written.skipped {
                    let file = skipped.path.strip_prefix(&dir).unwrap_or(&skipped.path);
                    eprintln!("  {}: skipped {}", skipped.reason, file.display());
                }
            }
            Err(error) => {
                return emit_error(
                    json,
                    ExitClass::Data,
                    &format!("cannot write {}: {error}", dir.display()),
                )
            }
        }
    }
    if failures > 0 {
        return emit_error(
            json,
            ExitClass::Data,
            &format!("{failures} tape problem(s)"),
        );
    }
    ExitCode::SUCCESS
}

/// A tape whose `Output` shares no format with `--format` (or
/// `--no-video`) writes only its text screenshots: say so, rather than
/// write nothing else in silence.
fn no_shared_format(outputs: &[tape::Output], requested: Formats) -> Option<String> {
    if outputs.is_empty() {
        return None;
    }
    let mut chosen = Formats::NONE;
    for output in outputs {
        chosen.set(output.format, true);
    }
    (chosen.intersect(requested) == Formats::NONE).then(|| {
        let names: Vec<&str> = outputs.iter().map(|o| o.format.extension()).collect();
        format!(
            "its Output ({}) and --format share no format, so only text screenshots are \
             written",
            names.join(", ")
        )
    })
}

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

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

    #[test]
    fn an_output_that_shares_no_format_is_reported() {
        let outputs = tape::parse("Output gif html\nScreenshot x\n")
            .unwrap()
            .outputs;
        let svg_only = parse_formats("svg").unwrap();
        let warning = no_shared_format(&outputs, svg_only).unwrap();
        assert!(warning.contains("gif, html"), "{warning}");
        assert_eq!(no_shared_format(&outputs, Formats::ALL), None);
        assert_eq!(no_shared_format(&[], svg_only), None);
    }

    #[test]
    fn routes_and_parses() {
        assert!(requested(&strings(&["record", "a.tape"])));
        assert!(requested(&strings(&["--no-color", "record"])));
        assert!(!requested(&strings(&["notes.md"])));
        let args = parse_args(&strings(&[
            "record",
            "--check",
            "--output=media",
            "--format",
            "png,cast",
            "a.tape",
        ]))
        .unwrap_or_else(|e| panic!("{e}"));
        assert!(args.check);
        assert_eq!(args.output, PathBuf::from("media"));
        assert!(args.formats.png && args.formats.cast && !args.formats.gif);
        assert_eq!(args.tapes, [PathBuf::from("a.tape")]);
        assert!(parse_args(&strings(&["record"])).is_err());
        assert!(parse_args(&strings(&["record", "--format", "webm", "a"])).is_err());
        let args = parse_args(&strings(&[
            "record",
            "--format=html,gif",
            "--window-frame",
            "off",
            "--caption=Saved",
            "--key-overlay=off",
            "a.tape",
        ]))
        .unwrap_or_else(|e| panic!("{e}"));
        assert!(args.formats.html && args.formats.gif && !args.formats.png);
        assert_eq!(args.window_frame, Some(false));
        assert_eq!(args.key_overlay, Some(false));
        assert_eq!(args.caption.as_deref(), Some("Saved"));
        let args = parse_args(&strings(&[
            "record",
            "--fps",
            "35",
            "--format=apng",
            "a.tape",
        ]))
        .unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(args.fps, Some(35.0));
        assert!(args.formats.apng && !args.formats.gif);
        for bad in ["0", "61", "fast"] {
            let Err(error) = parse_args(&strings(&["record", "--fps", bad, "a"])) else {
                panic!("--fps {bad} was accepted");
            };
            assert!(error.contains("--fps"), "{error}");
        }
        let args = parse_args(&strings(&["record", "--no-video", "a"])).unwrap();
        assert!(!args.formats.apng && !args.formats.gif && args.formats.png);
        let Err(error) = parse_args(&strings(&["record", "--window-frame=maybe", "a"])) else {
            panic!("--window-frame=maybe was accepted");
        };
        assert!(error.contains("on or off"), "{error}");
    }

    #[test]
    fn stems_come_from_the_file_name() {
        assert_eq!(stem(Path::new("docs/tapes/hero.tape")), "hero");
        assert_eq!(stem(Path::new("...tape")), "..");
        assert_eq!(stem(Path::new("..tape")), ".");
        assert!(!recorder::stem_allowed(&stem(Path::new("x/...tape"))));
        assert!(recorder::stem_allowed(&stem(Path::new("x/a.b.tape"))));
    }
}