rs-rich-ext 0.0.13

Extensions for the `rich` Rust port: diagnostics, structured data, clap and tracing integration, diffs, workflow renderables and a plugin registry
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
//! Reference documentation (#408): Markdown and man pages from a
//! [`CommandSpec`]. Output is deterministic: a man page is dated only when a
//! date is given or `SOURCE_DATE_EPOCH` is set.

use super::paragraphs;
use super::spec::{ArgSpec, CommandSpec};
#[cfg(feature = "markdown")]
use rich::markdown::Markdown;

/// Markdown reference for `spec` and, under deeper headings, every visible
/// subcommand. Each option group is a two-column table; hints (default,
/// environment, config key, possible values) follow the help in its cell.
///
/// ```
/// use rich_ext::cli_doc::{to_markdown, ArgSpec, CommandSpec};
///
/// let spec = CommandSpec::new("tool")
///     .about("Does things.")
///     .arg(ArgSpec::option("mode").choices(["a|b", "c"]).help("The mode"));
/// assert_eq!(
///     to_markdown(&spec),
///     "# tool\n\nDoes things.\n\n## Usage\n\n```text\ntool [OPTIONS]\n```\n\n## Options\n\n\
///      | Option | Description |\n| --- | --- |\n\
///      | `--mode <MODE>` | The mode. Possible values: `a\\|b`, `c`. |\n"
/// );
/// ```
pub fn to_markdown(spec: &CommandSpec) -> String {
    let mut out = String::new();
    markdown_command(&mut out, spec, spec.display_name(), 1);
    let mut out = out.trim_end().to_string();
    out.push('\n');
    out
}

/// [`to_markdown`] as a core [`Markdown`] renderable, to print through rich.
#[cfg(feature = "markdown")]
pub fn markdown_view(spec: &CommandSpec) -> Markdown {
    Markdown::new(&to_markdown(spec))
}

/// Inline code, fenced with enough backticks for the content.
fn code(text: &str) -> String {
    if text.contains('`') {
        format!("`` {text} ``")
    } else {
        format!("`{text}`")
    }
}

/// A table cell: pipes escaped, line breaks as `<br>`.
fn cell(text: &str) -> String {
    text.trim()
        .replace('|', r"\|")
        .replace("\r\n", "\n")
        .replace("\n\n", "<br><br>")
        .replace('\n', " ")
}

/// Help text as a sentence: a full stop added when it has none.
fn sentence(text: &str) -> String {
    let text = text.trim();
    if text.is_empty() || text.ends_with(['.', '!', '?', ':', ')']) {
        text.to_string()
    } else {
        format!("{text}.")
    }
}

fn arg_description(arg: &ArgSpec) -> String {
    let mut parts = Vec::new();
    let help = arg.long_help.as_deref().unwrap_or(&arg.help);
    if !help.trim().is_empty() {
        parts.push(sentence(help));
    }
    if let Some(default) = &arg.default {
        parts.push(format!("Default: {}.", code(default)));
    }
    if let Some(env) = &arg.env {
        parts.push(format!("Environment: {}.", code(env)));
    }
    if let Some(key) = &arg.config_key {
        parts.push(format!("Config: {}.", code(key)));
    }
    let choices = arg.choice_list();
    if !choices.is_empty() {
        let values: Vec<String> = choices
            .iter()
            .map(|c| match c.help.trim() {
                "" => code(&c.value),
                help => format!("{} ({help})", code(&c.value)),
            })
            .collect();
        parts.push(format!("Possible values: {}.", values.join(", ")));
    }
    cell(&parts.join(" "))
}

fn markdown_command(out: &mut String, spec: &CommandSpec, path: &str, level: usize) {
    let title = "#".repeat(level.min(6));
    let sub = "#".repeat((level + 1).min(6));
    out.push_str(&format!("{title} {path}\n\n"));
    let about = spec.long_about.as_deref().unwrap_or(&spec.about);
    for paragraph in paragraphs(about) {
        out.push_str(&paragraph);
        out.push_str("\n\n");
    }
    out.push_str(&format!("{sub} Usage\n\n```text\n"));
    for line in spec.usage_lines_as(path) {
        out.push_str(&line);
        out.push('\n');
    }
    out.push_str("```\n\n");
    for (heading, args) in spec.groups() {
        out.push_str(&format!("{sub} {heading}\n\n"));
        if let Some(note) = spec.note_for(&heading) {
            out.push_str(note.trim());
            out.push_str("\n\n");
        }
        let column = if args.iter().all(|a| a.positional) {
            "Argument"
        } else {
            "Option"
        };
        out.push_str(&format!("| {column} | Description |\n| --- | --- |\n"));
        for arg in args {
            let names = if arg.positional {
                code(&arg.names())
            } else {
                let mut switches: Vec<String> = arg.switches();
                if let (Some(last), Some(metavar)) = (switches.last_mut(), arg.metavar()) {
                    last.push(' ');
                    last.push_str(&metavar);
                }
                switches
                    .iter()
                    .map(|s| code(s))
                    .collect::<Vec<_>>()
                    .join(", ")
            };
            out.push_str(&format!(
                "| {} | {} |\n",
                cell(&names),
                arg_description(arg)
            ));
        }
        out.push('\n');
    }
    let commands: Vec<&CommandSpec> = spec.visible_subcommands().collect();
    if !commands.is_empty() {
        let heading = spec.subcommand_heading.as_deref().unwrap_or("Commands");
        out.push_str(&format!(
            "{sub} {heading}\n\n| Command | Description |\n| --- | --- |\n"
        ));
        for command in &commands {
            let mut names = code(&command.name);
            for alias in &command.aliases {
                names.push_str(", ");
                names.push_str(&code(alias));
            }
            let about = paragraphs(&command.about)
                .into_iter()
                .next()
                .unwrap_or_default();
            out.push_str(&format!("| {} | {} |\n", cell(&names), cell(&about)));
        }
        out.push('\n');
    }
    if !spec.examples.is_empty() {
        out.push_str(&format!("{sub} Examples\n\n"));
        for example in &spec.examples {
            if !example.description.trim().is_empty() {
                out.push_str(example.description.trim());
                out.push_str("\n\n");
            }
            out.push_str(&format!("```sh\n{}\n```\n\n", example.command));
        }
    }
    for section in &spec.sections {
        if !section.title.is_empty() {
            out.push_str(&format!("{sub} {}\n\n", section.title));
        }
        for paragraph in paragraphs(&section.body) {
            out.push_str(&paragraph);
            out.push_str("\n\n");
        }
    }
    for command in commands {
        markdown_command(out, command, &format!("{path} {}", command.name), level + 1);
    }
}

// ---------------------------------------------------------------- man

/// Escape one line of running text for roff. Line breaks become spaces (a
/// `.` after one would start a request), control characters are dropped,
/// and anything outside ASCII becomes a named or `\[uXXXX]` escape, which
/// groff and mandoc read whatever the input encoding.
fn roff(text: &str) -> String {
    let escaped = roff_keep(text.trim());
    let escaped = escaped.trim();
    if escaped.starts_with(['.', '\'']) {
        format!(r"\&{escaped}")
    } else {
        escaped.to_string()
    }
}

/// A quoted macro argument.
fn roff_arg(text: &str) -> String {
    format!("\"{}\"", roff(text).replace('"', r"\(dq"))
}

/// Paragraphs of running text, `.PP` between them.
fn roff_paragraphs(out: &mut String, text: &str) {
    roff_paragraphs_with(out, text, ".PP");
}

/// Paragraphs inside a `.TP` item, `.IP` between them to keep the indent.
fn roff_item(out: &mut String, text: &str) {
    roff_paragraphs_with(out, text, ".IP");
}

fn roff_paragraphs_with(out: &mut String, text: &str, separator: &str) {
    for (i, paragraph) in paragraphs(text).into_iter().enumerate() {
        if i > 0 {
            out.push_str(separator);
            out.push('\n');
        }
        for line in paragraph.lines() {
            out.push_str(&roff(line));
            out.push('\n');
        }
    }
}

fn man_names(arg: &ArgSpec) -> String {
    let metavar = arg.value_name.as_deref().map(|name| {
        let name = name.trim_matches(['<', '>', '[', ']']);
        let dots = if arg.multiple { "..." } else { "" };
        format!(r"\fI{}\fR{dots}", roff(name))
    });
    if arg.positional {
        return metavar.unwrap_or_else(|| roff(&arg.id));
    }
    let mut out = arg
        .switches()
        .iter()
        .map(|s| format!(r"\fB{}\fR", roff(s)))
        .collect::<Vec<_>>()
        .join(", ");
    if let Some(metavar) = metavar {
        out.push(' ');
        out.push_str(&metavar);
    }
    out
}

/// A man page for `spec`. `section` is the manual section (`"1"`); `date`
/// goes in the header when given, else the `SOURCE_DATE_EPOCH` date when
/// that is set (reproducible builds), else none. Subcommands are listed under
/// COMMANDS and SEE ALSO; [`to_man_pages`] writes their own pages.
///
/// ```
/// use rich_ext::cli_doc::{to_man, ArgSpec, CommandSpec};
///
/// let spec = CommandSpec::new("tool")
///     .about("Does things")
///     .arg(ArgSpec::option("out-dir").short('o').help("Where to write"));
/// let page = to_man(&spec, "1", Some("2026-01-01"));
/// assert!(page.starts_with(".TH \"TOOL\" \"1\" \"2026-01-01\" \"tool\" \"User Commands\"\n"));
/// assert!(page.contains(".TP\n\\fB\\-o\\fR, \\fB\\-\\-out\\-dir\\fR \\fIOUT_DIR\\fR\nWhere to write\n"));
/// ```
pub fn to_man(spec: &CommandSpec, section: &str, date: Option<&str>) -> String {
    man_page(spec, spec.display_name(), None, section, date)
}

/// Man pages for `spec` and every visible subcommand, as
/// `(file name, page)`: `rich.1`, `rich-config.1`, …
pub fn to_man_pages(
    spec: &CommandSpec,
    section: &str,
    date: Option<&str>,
) -> Vec<(String, String)> {
    let mut pages = Vec::new();
    collect_pages(&mut pages, spec, spec.display_name(), None, section, date);
    pages
}

fn collect_pages(
    pages: &mut Vec<(String, String)>,
    spec: &CommandSpec,
    path: &str,
    parent: Option<&str>,
    section: &str,
    date: Option<&str>,
) {
    let page = page_name(path);
    pages.push((
        format!("{page}.{section}"),
        man_page(spec, path, parent, section, date),
    ));
    for command in spec.visible_subcommands() {
        let child = format!("{path} {}", command.name);
        collect_pages(pages, command, &child, Some(path), section, date);
    }
}

fn page_name(path: &str) -> String {
    path.split(' ').collect::<Vec<_>>().join("-")
}

fn man_page(
    spec: &CommandSpec,
    path: &str,
    parent: Option<&str>,
    section: &str,
    date: Option<&str>,
) -> String {
    let page = page_name(path);
    let mut out = String::new();
    let source = match &spec.version {
        Some(version) => format!("{path} {version}"),
        None => path.to_string(),
    };
    let manual = if section.starts_with('1') {
        "User Commands"
    } else {
        ""
    };
    // The date stays unescaped: mandoc parses `YYYY-MM-DD` only without `\-`.
    let date = date.map(str::to_string).or_else(source_date);
    out.push_str(&format!(
        ".TH {} {} \"{}\" {} {}\n",
        roff_arg(&page.to_uppercase()),
        roff_arg(section),
        roff_date(date.as_deref().unwrap_or("")),
        roff_arg(&source),
        roff_arg(manual)
    ));

    out.push_str(".SH NAME\n");
    let summary = paragraphs(&spec.about)
        .into_iter()
        .next()
        .unwrap_or_default();
    if summary.is_empty() {
        out.push_str(&format!("{}\n", roff(&page)));
    } else {
        out.push_str(&format!(
            "{} \\- {}\n",
            roff(&page),
            roff(&summary.replace('\n', " "))
        ));
    }

    out.push_str(".SH SYNOPSIS\n.nf\n");
    for line in spec.usage_lines_as(path) {
        match line.strip_prefix(path) {
            Some(rest) => out.push_str(&format!("\\fB{}\\fR{}\n", roff(path), roff_keep(rest))),
            None => out.push_str(&format!("{}\n", roff(&line))),
        }
    }
    out.push_str(".fi\n");

    let about = spec.long_about.as_deref().unwrap_or(&spec.about);
    if !paragraphs(about).is_empty() {
        out.push_str(".SH DESCRIPTION\n");
        roff_paragraphs(&mut out, about);
    }

    let groups = spec.groups();
    if !groups.is_empty() {
        out.push_str(".SH OPTIONS\n");
        let titled = groups.len() > 1 || groups[0].0 != "Options";
        for (heading, args) in &groups {
            if titled {
                out.push_str(&format!(".SS {}\n", roff_arg(heading)));
            }
            if let Some(note) = spec.note_for(heading) {
                roff_paragraphs(&mut out, note);
            }
            for arg in args {
                out.push_str(".TP\n");
                out.push_str(&man_names(arg));
                out.push('\n');
                let help = arg.long_help.as_deref().unwrap_or(&arg.help);
                roff_item(&mut out, help);
                let mut hints = Vec::new();
                if let Some(default) = &arg.default {
                    hints.push(format!("[default: {default}]"));
                }
                if let Some(env) = &arg.env {
                    hints.push(format!("[env: {env}]"));
                }
                if let Some(key) = &arg.config_key {
                    hints.push(format!("[config: {key}]"));
                }
                let choices = arg.choice_list();
                let described = choices.iter().any(|c| !c.help.trim().is_empty());
                if !choices.is_empty() && !described {
                    let values: Vec<&str> = choices.iter().map(|c| c.value.as_str()).collect();
                    hints.push(format!("[possible values: {}]", values.join(", ")));
                }
                if !hints.is_empty() {
                    if !paragraphs(help).is_empty() {
                        out.push_str(".br\n");
                    }
                    out.push_str(&roff(&hints.join(" ")));
                    out.push('\n');
                }
                if described {
                    out.push_str(".RS\n");
                    for choice in choices {
                        out.push_str(&format!(".TP\n\\fB{}\\fR\n", roff(&choice.value)));
                        roff_item(&mut out, &choice.help);
                    }
                    out.push_str(".RE\n");
                }
            }
        }
    }

    let commands: Vec<&CommandSpec> = spec.visible_subcommands().collect();
    if !commands.is_empty() {
        out.push_str(".SH COMMANDS\n");
        for command in &commands {
            let mut names = format!(r"\fB{}\fR", roff(&command.name));
            for alias in &command.aliases {
                names.push_str(&format!(r", \fB{}\fR", roff(alias)));
            }
            out.push_str(&format!(".TP\n{names}\n"));
            let about = paragraphs(&command.about)
                .into_iter()
                .next()
                .unwrap_or_default();
            roff_item(&mut out, &sentence(&about));
            out.push_str(&format!(
                "See \\fB{}\\fR({}).\n",
                roff(&page_name(&format!("{path} {}", command.name))),
                roff(section)
            ));
        }
    }

    let env: Vec<&ArgSpec> = spec.visible_args().filter(|a| a.env.is_some()).collect();
    if !env.is_empty() {
        out.push_str(".SH ENVIRONMENT\n");
        for arg in env {
            let name = arg.env.as_deref().unwrap_or_default();
            out.push_str(&format!(".TP\n\\fB{}\\fR\n", roff(name)));
            let target = if arg.positional {
                format!(
                    r"\fI{}\fR",
                    roff(arg.value_name.as_deref().unwrap_or(&arg.id))
                )
            } else {
                format!(r"\fB{}\fR", roff(&arg.primary()))
            };
            out.push_str(&format!("Sets {target}.\n"));
        }
    }

    if !spec.examples.is_empty() {
        out.push_str(".SH EXAMPLES\n");
        for example in &spec.examples {
            if example.description.trim().is_empty() {
                out.push_str(&format!(".PP\n\\fB{}\\fR\n", roff(&example.command)));
            } else {
                out.push_str(&format!(".TP\n\\fB{}\\fR\n", roff(&example.command)));
                roff_item(&mut out, &example.description);
            }
        }
    }

    for section_spec in &spec.sections {
        let title = if section_spec.title.is_empty() {
            "NOTES".to_string()
        } else {
            section_spec.title.to_uppercase()
        };
        out.push_str(&format!(".SH {}\n", roff_arg(&title)));
        roff_paragraphs(&mut out, &section_spec.body);
    }

    let mut see_also: Vec<String> = Vec::new();
    if let Some(parent) = parent {
        see_also.push(format!(
            r"\fB{}\fR({})",
            roff(&page_name(parent)),
            roff(section)
        ));
    }
    for command in &commands {
        let name = page_name(&format!("{path} {}", command.name));
        see_also.push(format!(r"\fB{}\fR({})", roff(&name), roff(section)));
    }
    if !see_also.is_empty() {
        out.push_str(".SH \"SEE ALSO\"\n");
        out.push_str(&see_also.join(",\n"));
        out.push('\n');
    }
    out
}

/// [`roff`] without trimming or the control-line guard, for the tail of a
/// line.
fn roff_keep(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '\\' => out.push_str(r"\e"),
            '-' => out.push_str(r"\-"),
            '\n' | '\r' | '\t' => out.push(' '),
            c if c.is_control() => {}
            c if c.is_ascii() => out.push(c),
            '\u{2014}' => out.push_str(r"\(em"),
            '\u{2013}' => out.push_str(r"\(en"),
            '\u{2018}' => out.push_str(r"\(oq"),
            '\u{2019}' => out.push_str(r"\(cq"),
            '\u{201c}' => out.push_str(r"\(lq"),
            '\u{201d}' => out.push_str(r"\(rq"),
            c => out.push_str(&format!(r"\[u{:04X}]", c as u32)),
        }
    }
    out
}

/// A `.TH` date: quotes, backslashes and control characters dropped.
fn roff_date(date: &str) -> String {
    let date: String = date
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .filter(|c| !matches!(c, '"' | '\\') && c.is_ascii())
        .collect();
    date.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// `SOURCE_DATE_EPOCH` (seconds since 1970, UTC) as `YYYY-MM-DD`, the
/// reproducible-builds date for undated pages.
fn source_date() -> Option<String> {
    let seconds: i64 = std::env::var("SOURCE_DATE_EPOCH")
        .ok()?
        .trim()
        .parse()
        .ok()?;
    Some(civil_date(seconds.div_euclid(86_400)))
}

/// Days since 1970-01-01 as `YYYY-MM-DD` (proleptic Gregorian).
fn civil_date(days: i64) -> String {
    // Howard Hinnant's `civil_from_days`.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!("{year:04}-{month:02}-{day:02}")
}

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

    #[test]
    fn roff_escapes_control_lines_and_dashes() {
        assert_eq!(roff(".hidden"), r"\&.hidden");
        assert_eq!(roff("'quote"), r"\&'quote");
        assert_eq!(roff(r"a-b\c"), r"a\-b\ec");
        assert_eq!(roff_arg("say \"hi\""), r#""say \(dqhi\(dq""#);
        assert_eq!(roff("a\n.so x"), r"a .so x");
        assert_eq!(roff("\n.so x"), r"\&.so x");
        assert_eq!(roff("é — …\u{1b}"), r"\[u00E9] \(em \[u2026]");
        assert_eq!(roff_date("2026-01-01\"\n.so x\\"), "2026-01-01 .so x");
    }

    #[test]
    fn civil_dates() {
        assert_eq!(civil_date(0), "1970-01-01");
        assert_eq!(civil_date(-1), "1969-12-31");
        assert_eq!(civil_date(19_723), "2024-01-01");
        assert_eq!(civil_date(19_782), "2024-02-29");
        assert_eq!(civil_date(20_719), "2026-09-23");
    }

    #[test]
    fn code_spans_fence_backticks() {
        assert_eq!(code("a`b"), "`` a`b ``");
        assert_eq!(cell("a | b\nc"), r"a \| b c");
    }
}