caress 0.1.0

shell completions and man pages for pound commands
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
// SPDX-License-Identifier: EUPL-1.2

//! mdoc manual pages, one per command
//!
//! the root command gets `<name>.1` and every visible subcommand gets
//! `<name>-<sub>.1`, the layout git and cargo use, so `man grab-fetch` works.

use core::fmt::{
    self,
    Write as _,
};
use std::collections::VecDeque;

use pound::spec::{
    ArgSpec,
    Command,
    CommandSpec,
    Kind,
};

/// one rendered manual page
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Page {
    /// the page name, `grab-fetch` for `grab fetch`
    pub name:    String,
    /// the mdoc source
    pub content: String,
}

impl Page {
    /// the file the page installs as, under `man1`
    #[must_use]
    pub fn file_name(&self) -> String {
        format!("{}.1", self.name)
    }
}

/// a page for `spec` and every visible subcommand below it. `date` goes on
/// each page as written, e.g. `October 11, 2026`, and is a parameter so a
/// reproducible build can pin it.
///
/// # Panics
///
/// when two commands would install the same page, such as `a b-c` and
/// `a b c`, which both name `a-b-c`
#[must_use]
pub fn pages(spec: &CommandSpec, date: &str) -> Vec<Page> {
    let mut out = Vec::new();
    let mut pending = VecDeque::from([Command::root(spec)]);
    while let Some(cmd) = pending.pop_front() {
        pending.extend(cmd.subcommands().filter(|sub| !sub.hidden()));
        let manual = Manual::new(cmd);
        let name = manual.name();
        assert!(
            out.iter().all(|page: &Page| page.name != name),
            "two commands would both install the man page {name}"
        );
        out.push(Page {
            content: manual.render(date),
            name,
        });
    }
    out
}

struct Manual<'m> {
    cmd:         Command<'m>,
    options:     Vec<ArgSpec>,
    positionals: Vec<&'static ArgSpec>,
}

impl<'m> Manual<'m> {
    fn new(cmd: Command<'m>) -> Self {
        Self {
            options: cmd.options(),
            positionals: cmd.positionals().collect(),
            cmd,
        }
    }

    fn words(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.cmd
            .path()
            .iter()
            .copied()
            .chain([self.cmd.spec().name])
    }

    fn name(&self) -> String {
        self.words().collect::<Vec<_>>().join("-")
    }

    fn render(&self, date: &str) -> String {
        let name = self.name();
        let mut page = Mdoc::default();

        page.line(format_args!("Dd {date}"));
        page.line(format_args!("Dt {} 1", name.to_uppercase()));
        page.line("Os");
        page.line("Sh NAME");
        page.line(format_args!("Nm {}", Word(&name)));
        let spec = self.cmd.spec();
        let about = [spec.about, spec.long_about]
            .into_iter()
            .find_map(|text| text.lines().find(|line| !line.trim().is_empty()))
            .unwrap_or_default()
            .trim_end_matches('.');
        page.line(format_args!("Nd {}", Word(about)));

        self.synopsis(&mut page);
        self.description(&mut page);
        self.commands(&mut page);
        self.environment(&mut page);
        self.see_also(&mut page, &name);
        page.out
    }

    fn synopsis(&self, page: &mut Mdoc) {
        page.line("Sh SYNOPSIS");
        let mut words = self.words();
        page.line(format_args!(
            "Nm {}",
            Word(words.next().unwrap_or_default())
        ));
        for word in words {
            page.line(format_args!("Cm {}", Word(word)));
        }

        let switches = self
            .options
            .iter()
            .filter(|a| matches!(a.kind, Kind::Flag | Kind::Count))
            .collect::<Vec<_>>();
        let bundle = switches.iter().filter_map(|a| a.short).collect::<String>();
        if !bundle.is_empty() {
            page.line(format_args!("Op Fl {}", Word(&bundle)));
        }
        for a in switches.iter().filter(|a| a.short.is_none()) {
            page.line(format_args!("Op {}", Flag(a)));
        }

        for a in self.options.iter().filter(|a| a.kind == Kind::Opt) {
            let op = if a.required { "" } else { "Op " };
            if a.value_may_be_left_out() {
                let attached = Attached {
                    arg:  a,
                    long: a.short.is_none(),
                };
                page.line(format_args!("{op}{}{attached}", Flag(a)));
            } else {
                page.line(format_args!("{op}{} {}", Flag(a), Values(a)));
            }
        }
        for a in &self.positionals {
            let dots = if a.multi || a.kind == Kind::Trailing {
                " ..."
            } else {
                ""
            };
            let op = if a.required { "" } else { "Op " };
            page.line(format_args!("{op}Ar {}{dots}", Meta(a)));
        }
        if self.cmd.spec().has_subs() {
            let op = if self.cmd.spec().subcommand_optional() {
                "Op "
            } else {
                ""
            };
            page.line(format_args!("{op}Ar command"));
        }
    }

    fn description(&self, page: &mut Mdoc) {
        page.line("Sh DESCRIPTION");
        let spec = self.cmd.spec();
        let about = if spec.long_about.is_empty() {
            spec.about
        } else {
            spec.long_about
        };
        page.block(spec.before_help);
        page.block(about);

        if !self.positionals.is_empty() {
            page.paragraph();
            page.text("The arguments are as follows:");
            page.list(&self.positionals, |page, a| {
                page.line(format_args!("It Ar {}", Meta(a)));
                page.describe(a);
            });
        }

        if !self.options.is_empty() {
            page.paragraph();
            page.text("The options are as follows:");
            page.list(&self.options, |page, a| {
                page.line(format_args!("It {}", Item(a)));
                page.describe(a);
            });
        }

        page.block(spec.after_help);
    }

    fn commands(&self, page: &mut Mdoc) {
        let mut subs = self
            .cmd
            .subcommands()
            .filter(|sub| !sub.hidden())
            .map(|sub| (sub.spec().name, "", sub.spec().about))
            .collect::<Vec<_>>();
        if subs.is_empty() {
            return;
        }
        if let Some(help) = self.cmd.help_command() {
            subs.push((help.name, " Op Ar command ...", help.about));
        }

        page.line("Sh COMMANDS");
        page.list(subs, |page, (name, operands, about)| {
            page.line(format_args!("It Cm {}{operands}", Word(name)));
            page.text(about);
        });
    }

    fn see_also(&self, page: &mut Mdoc, name: &str) {
        let parent = self.cmd.path().join("-");
        let children = self
            .cmd
            .subcommands()
            .filter(|sub| !sub.hidden())
            .map(|sub| format!("{name}-{}", sub.spec().name));
        let mut pages = (!parent.is_empty())
            .then_some(parent)
            .into_iter()
            .chain(children)
            .collect::<Vec<_>>();
        pages.sort_by_cached_key(|name| name.to_lowercase());
        if pages.is_empty() {
            return;
        }

        page.line("Sh SEE ALSO");
        let last = pages.len() - 1;
        for (i, name) in pages.iter().enumerate() {
            let comma = if i == last { "" } else { " ," };
            page.line(format_args!("Xr {} 1{comma}", Word(name)));
        }
    }

    fn environment(&self, page: &mut Mdoc) {
        let env = self
            .options
            .iter()
            .chain(self.positionals.iter().copied())
            .filter_map(|a| Some((a.env.filter(|_| !a.hide_env)?, a)))
            .collect::<Vec<_>>();
        if env.is_empty() {
            return;
        }

        page.line("Sh ENVIRONMENT");
        page.list(env, |page, (var, a)| {
            page.line(format_args!("It Ev {}", Word(var)));
            page.text("Default for");
            match (a.long, a.short) {
                _ if a.is_positional() => page.line(format_args!("Ar {} .", Meta(a))),
                (Some(long), _) => page.line(format_args!("Fl \\-{} .", Word(long))),
                (None, Some(short)) => {
                    page.line(format_args!(
                        "Fl {} .",
                        Word(short.encode_utf8(&mut [0; 4]))
                    ));
                },
                (None, None) => page.line(format_args!("Ar {} .", Meta(a))),
            }
        });
    }
}

#[derive(Default)]
struct Mdoc {
    out: String,
}

impl Mdoc {
    /// its words must already be escaped
    fn line(&mut self, line: impl fmt::Display) {
        let _ = writeln!(self.out, ".{line}");
    }

    /// mandoc warns on a `Pp` straight after `Sh`
    fn paragraph(&mut self) {
        let fresh = self
            .out
            .lines()
            .last()
            .is_none_or(|last| last.starts_with(".Sh "));
        if !fresh {
            self.line("Pp");
        }
    }

    fn block(&mut self, text: &str) {
        if !text.trim().is_empty() {
            self.paragraph();
            self.text(text);
        }
    }

    /// guards a line starting with `.` or `'`, which mdoc reads as a request
    fn text(&mut self, text: &str) {
        let indent = |line: &str| line.len() - line.trim_start_matches([' ', '\t']).len();
        let flat = text
            .lines()
            .map(|line| if line.trim().is_empty() { "" } else { line })
            .collect::<Vec<_>>()
            .join("\n");
        let paragraphs = flat
            .split("\n\n")
            .map(|p| p.trim_matches('\n'))
            .filter(|p| !p.is_empty());
        for (nth, paragraph) in paragraphs.enumerate() {
            let lines = paragraph.lines().collect::<Vec<_>>();
            let mut margin = None;
            for (at, line) in lines.iter().enumerate() {
                match (margin, indent(line) > 0) {
                    (None, true) => {
                        self.line("Bd -literal -offset indent");
                        let run = lines[at..].iter().take_while(|next| indent(next) > 0);
                        margin = run.map(|next| indent(next)).min();
                    },
                    (Some(_), false) => {
                        self.line("Ed");
                        margin = None;
                    },
                    (None, false) if at == 0 && nth > 0 => self.line("Pp"),
                    _ => {},
                }

                let shown = match margin {
                    Some(width) => line[width..].trim_end(),
                    None => line.trim(),
                };
                if shown.starts_with(['.', '\'']) {
                    self.out.push_str("\\&");
                }
                self.out.push_str(&shown.replace('\\', "\\e"));
                self.out.push('\n');
            }
            if margin.is_some() {
                self.line("Ed");
            }
        }
    }

    fn list<T>(&mut self, items: impl IntoIterator<Item = T>, mut entry: impl FnMut(&mut Self, T)) {
        self.line("Bl -tag -width Ds");
        for item in items {
            entry(self, item);
        }
        self.line("El");
    }

    fn describe(&mut self, a: &ArgSpec) {
        self.text(a.long_help.unwrap_or(a.help));
        let choices = a
            .possible
            .filter(|_| !a.hide_possible)
            .unwrap_or_default()
            .iter()
            .filter(|c| !c.hidden)
            .collect::<Vec<_>>();
        if choices.iter().any(|c| !c.help.is_empty()) {
            self.line("Pp");
            self.text("One of");
            self.list(&choices, |page, choice| {
                page.line(format_args!("It Cm {}", Word(choice.name)));
                page.text(choice.help);
            });
        } else if let Some(last) = choices.len().checked_sub(1) {
            self.line("Pp");
            self.text("One of");
            for (i, choice) in choices.iter().enumerate() {
                let punct = if i == last { " ." } else { " ," };
                self.line(format_args!("Cm {}{punct}", Word(choice.name)));
            }
        }
        if let Some(default) = a
            .default
            .filter(|_| a.kind != Kind::Flag && !a.hide_default)
        {
            self.line("Pp");
            self.text("Defaults to");
            self.line(format_args!("Ql {} .", Word(default)));
        }
    }
}

/// one macro argument. quoting keeps spaces in one argument, and the `\&`
/// keeps a word that spells a macro name, like `Ar`, from being read as one.
struct Word<'w>(&'w str);

impl fmt::Display for Word<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let word = self.0;
        let quoted = word.contains(' ');
        let delimiter = matches!(
            word,
            "" | "(" | "[" | "." | "," | ":" | ";" | ")" | "]" | "?" | "!" | "|"
        );
        if quoted {
            f.write_char('"')?;
        } else if delimiter || word.len() <= 3 && word.starts_with(char::is_uppercase) {
            f.write_str("\\&")?;
        }
        for c in word.chars() {
            match c {
                '\\' => f.write_str("\\e")?,
                '"' => f.write_str("\\(dq")?,
                c => f.write_char(c)?,
            }
        }
        if quoted {
            f.write_char('"')?;
        }
        Ok(())
    }
}

struct Meta<'a>(&'a ArgSpec);

impl fmt::Display for Meta<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Word(&self.0.metavar().to_lowercase()).fmt(f)
    }
}

struct Values<'a>(&'a ArgSpec);

impl fmt::Display for Values<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Some(arity) = self.0.words_per_use() else {
            return write!(f, "Ar {}", Meta(self.0));
        };

        for nth in 0..arity.min() {
            let gap = if nth > 0 { " " } else { "" };
            write!(f, "{gap}Ar {}", Meta(self.0))?;
        }
        if arity.max() != Some(arity.min()) {
            f.write_str(" No ...")?;
        }
        Ok(())
    }
}

/// a value that may be left out, which then has to be attached to its option,
/// as in `-c[color]` or `--color[=color]`
struct Attached<'a> {
    arg:  &'a ArgSpec,
    long: bool,
}

impl fmt::Display for Attached<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let equals = if self.long { "Ns = Ns " } else { "" };
        write!(f, " Ns Oo {equals}Ar {} Oc", Meta(self.arg))
    }
}

struct Flag<'a>(&'a ArgSpec);

impl fmt::Display for Flag<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let a = self.0;
        match (a.short, a.long) {
            (Some(c), _) => write!(f, "Fl {}", Word(c.encode_utf8(&mut [0; 4]))),
            (None, Some(long)) => write!(f, "Fl \\-{}", Word(long)),
            (None, None) => write!(f, "Ar {}", Meta(a)),
        }
    }
}

struct Item<'a>(&'a ArgSpec);

impl fmt::Display for Item<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[derive(Clone, Copy)]
        enum Spelling<'s> {
            Short(char),
            Long(&'s str),
        }

        let a = self.0;
        let shorts = a.short.map(Spelling::Short);
        let longs = a.long.into_iter().chain(a.negate).map(Spelling::Long);
        for (i, spelling) in shorts.into_iter().chain(longs).enumerate() {
            if i > 0 {
                f.write_str(" , ")?;
            }
            match spelling {
                Spelling::Short(c) => write!(f, "Fl {}", Word(c.encode_utf8(&mut [0; 4])))?,
                Spelling::Long(long) => write!(f, "Fl \\-{}", Word(long))?,
            }
            match (a.kind, spelling) {
                (Kind::Opt, _) if a.value_may_be_left_out() => {
                    let long = matches!(spelling, Spelling::Long(_));
                    write!(f, "{}", Attached { arg: a, long })?;
                },
                (Kind::Opt, Spelling::Long(_)) if a.words_per_use().is_none() => {
                    write!(f, " Ns = Ns Ar {}", Meta(a))?;
                },
                (Kind::Opt, _) => write!(f, " {}", Values(a))?,
                _ => {},
            }
        }
        Ok(())
    }
}