Skip to main content

argument_mangen/
lib.rs

1//! Man page generation for [`argument`] based command line interfaces.
2//!
3//! This renders a man page in roff format from a [`Cli`](argument::Cli)
4//! description.  Subcommands get their own pages (eg: `cargo-install.1`).
5//!
6//! ```
7//! use argument::{Cli, Opt};
8//! use argument_mangen::Man;
9//!
10//! #[derive(Copy, Clone)]
11//! enum Arg {
12//!     Verbose,
13//! }
14//!
15//! static CLI: Cli<Arg> = Cli::new("demo")
16//!     .version("1.0")
17//!     .about("A demo tool")
18//!     .opts(&[Opt::new(Arg::Verbose).short('v').long("verbose").help("Be verbose")]);
19//!
20//! let page = Man::new(&CLI).render();
21//! assert!(page.contains(".SH NAME\ndemo \\- A demo tool"));
22//! ```
23use std::fmt::Write;
24use std::fs;
25use std::io;
26use std::path::{Path, PathBuf};
27
28use argument::{ArgumentInfo, CommandInfo, OptionInfo, PossibleValue};
29
30/// A man page for a command.
31pub struct Man<'a> {
32    cmd: &'a dyn CommandInfo,
33    name: String,
34    invocation: String,
35    section: String,
36    date: Option<String>,
37    source: Option<String>,
38    manual: Option<String>,
39}
40
41impl<'a> Man<'a> {
42    /// Creates a man page for the given command.
43    pub fn new(cmd: &'a dyn CommandInfo) -> Man<'a> {
44        Man {
45            cmd,
46            name: cmd.name().to_string(),
47            invocation: cmd.name().to_string(),
48            section: "1".into(),
49            date: None,
50            source: None,
51            manual: None,
52        }
53    }
54
55    /// Overrides the name of the command (defaults to the name of the [`Cli`](argument::Cli)).
56    pub fn name(mut self, name: impl Into<String>) -> Man<'a> {
57        self.name = name.into();
58        self.invocation = self.name.clone();
59        self
60    }
61
62    /// Sets the manual section (defaults to `1`).
63    pub fn section(mut self, section: impl Into<String>) -> Man<'a> {
64        self.section = section.into();
65        self
66    }
67
68    /// Sets the date shown in the footer.
69    pub fn date(mut self, date: impl Into<String>) -> Man<'a> {
70        self.date = Some(date.into());
71        self
72    }
73
74    /// Sets the source shown in the footer (defaults to name and version).
75    pub fn source(mut self, source: impl Into<String>) -> Man<'a> {
76        self.source = Some(source.into());
77        self
78    }
79
80    /// Sets the title of the manual shown in the header.
81    pub fn manual(mut self, manual: impl Into<String>) -> Man<'a> {
82        self.manual = Some(manual.into());
83        self
84    }
85
86    /// The file name of the man page (eg: `demo.1`).
87    pub fn file_name(&self) -> String {
88        format!("{}.{}", self.name, self.section)
89    }
90
91    /// Renders the man page.
92    pub fn render(&self) -> String {
93        let mut out = Roff::default();
94        let source = match (&self.source, self.cmd.version()) {
95            (Some(source), _) => source.clone(),
96            (None, Some(version)) => format!("{} {}", self.name, version),
97            (None, None) => self.name.clone(),
98        };
99        out.control_raw(".ie \\n(.g .ds Aq \\(aq\n.el .ds Aq '");
100        out.control(
101            "TH",
102            &[
103                &self.name,
104                &self.section,
105                self.date.as_deref().unwrap_or(""),
106                &source,
107                self.manual.as_deref().unwrap_or(""),
108            ],
109        );
110
111        out.control("SH", &["NAME"]);
112        match self.cmd.about() {
113            Some(about) => out.text(&format!("{} - {}", self.name, first_line(about))),
114            None => out.text(&self.name),
115        }
116
117        out.control("SH", &["SYNOPSIS"]);
118        out.line(&self.synopsis());
119
120        let description = self.cmd.long_about().or(self.cmd.about());
121        if self.cmd.before_help().is_some() || description.is_some() {
122            out.control("SH", &["DESCRIPTION"]);
123            let mut first = true;
124            for text in [self.cmd.before_help(), description].into_iter().flatten() {
125                if !first {
126                    out.control("PP", &[]);
127                }
128                first = false;
129                out.paragraphs(text, "PP");
130            }
131        }
132
133        let options = self
134            .cmd
135            .options()
136            .into_iter()
137            .filter(|x| !x.is_hidden())
138            .collect::<Vec<_>>();
139        let mut sections: Vec<(Option<&str>, Vec<&OptionInfo>)> = Vec::new();
140        for opt in &options {
141            match sections.iter_mut().find(|x| x.0 == opt.section()) {
142                Some(section) => section.1.push(opt),
143                None => sections.push((opt.section(), vec![opt])),
144            }
145        }
146        for (title, opts) in sections {
147            let title = title.unwrap_or("Options").to_uppercase();
148            out.control("SH", &[&title]);
149            for opt in opts {
150                out.control("TP", &[]);
151                out.line(&option_term(opt));
152                item_body(
153                    &mut out,
154                    opt.long_help().unwrap_or(opt.help()),
155                    opt.default_value(),
156                    &opt.possible_values(),
157                );
158            }
159        }
160
161        let args = self.cmd.arguments();
162        if !args.is_empty() {
163            out.control("SH", &["ARGUMENTS"]);
164            for arg in &args {
165                out.control("TP", &[]);
166                out.line(&argument_term(arg));
167                item_body(
168                    &mut out,
169                    arg.long_help().unwrap_or(arg.help()),
170                    arg.default_value(),
171                    &arg.possible_values(),
172                );
173            }
174        }
175
176        let commands = self.cmd.commands();
177        if !commands.is_empty() {
178            out.control("SH", &["SUBCOMMANDS"]);
179            for cmd in &commands {
180                out.control("TP", &[]);
181                out.line(&format!(
182                    "{}({})",
183                    escape(&format!("{}-{}", self.name, cmd.name())),
184                    escape(&self.section)
185                ));
186                if let Some(about) = cmd.about() {
187                    out.paragraphs(about, "sp");
188                }
189            }
190        }
191
192        if let Some(after_help) = self.cmd.after_help() {
193            out.control("SH", &["EXTRA"]);
194            out.paragraphs(after_help, "PP");
195        }
196
197        if let Some(version) = self.cmd.version() {
198            out.control("SH", &["VERSION"]);
199            out.text(&format!("v{}", version));
200        }
201
202        out.0
203    }
204
205    /// Writes the man page and the pages of all subcommands into a directory.
206    ///
207    /// Returns the paths of all written files.
208    pub fn generate_to(&self, dir: &Path) -> io::Result<Vec<PathBuf>> {
209        let mut rv = Vec::new();
210        let path = dir.join(self.file_name());
211        fs::write(&path, self.render())?;
212        rv.push(path);
213        for cmd in self.cmd.commands() {
214            let mut sub = Man::new(cmd)
215                .name(format!("{}-{}", self.name, cmd.name()))
216                .section(self.section.clone());
217            sub.invocation = format!("{} {}", self.invocation, cmd.name());
218            sub.date = self.date.clone();
219            sub.source = self.source.clone();
220            sub.manual = self.manual.clone();
221            if sub.source.is_none() {
222                if let Some(version) = self.cmd.version() {
223                    sub.source = Some(format!("{} {}", self.name, version));
224                }
225            }
226            rv.extend(sub.generate_to(dir)?);
227        }
228        Ok(rv)
229    }
230
231    fn synopsis(&self) -> String {
232        let mut rv = bold(&self.invocation);
233        if let Some(usage) = self.cmd.usage_override() {
234            rv.push(' ');
235            rv.push_str(&escape(usage));
236            return rv;
237        }
238        for opt in self.cmd.options().iter().filter(|x| !x.is_hidden()) {
239            let names = match (opt.short(), opt.long()) {
240                (Some(s), Some(l)) => {
241                    format!("{}|{}", bold(&format!("-{}", s)), bold(&format!("--{}", l)))
242                }
243                (Some(s), None) => bold(&format!("-{}", s)),
244                (None, Some(l)) => bold(&format!("--{}", l)),
245                (None, None) => continue,
246            };
247            write!(rv, " [{}]", names).unwrap();
248        }
249        for arg in self.cmd.arguments() {
250            let name = italic(arg.name());
251            let mut piece = if arg.is_required() {
252                format!("<{}>", name)
253            } else {
254                format!("[{}]", name)
255            };
256            if arg.is_multiple() {
257                piece.push_str("...");
258            }
259            rv.push(' ');
260            rv.push_str(&piece);
261        }
262        if !self.cmd.commands().is_empty() {
263            write!(rv, " [{}]", italic("COMMAND")).unwrap();
264        }
265        rv
266    }
267}
268
269fn option_term(opt: &OptionInfo) -> String {
270    let mut rv = match (opt.short(), opt.long()) {
271        (Some(s), Some(l)) => format!(
272            "{}, {}",
273            bold(&format!("-{}", s)),
274            bold(&format!("--{}", l))
275        ),
276        (Some(s), None) => bold(&format!("-{}", s)),
277        (None, Some(l)) => bold(&format!("--{}", l)),
278        (None, None) => String::new(),
279    };
280    if let Some(value) = opt.value_name() {
281        if opt.has_optional_value() {
282            write!(rv, "[={}]", italic(value)).unwrap();
283        } else {
284            write!(rv, "={}", italic(value)).unwrap();
285        }
286    }
287    rv
288}
289
290fn argument_term(arg: &ArgumentInfo) -> String {
291    let name = italic(arg.name());
292    let mut rv = if arg.is_required() {
293        format!("<{}>", name)
294    } else {
295        format!("[{}]", name)
296    };
297    if arg.is_multiple() {
298        rv.push_str("...");
299    }
300    rv
301}
302
303fn item_body(out: &mut Roff, help: &str, default: Option<&str>, values: &[PossibleValue]) {
304    out.paragraphs(help, "sp");
305    if let Some(default) = default {
306        out.control("sp", &[]);
307        out.text(&format!("[default: {}]", default));
308    }
309    if values.iter().any(|x| x.help().is_some()) {
310        out.control("sp", &[]);
311        out.text("Possible values:");
312        out.control("RS", &[]);
313        out.control("PD", &["0"]);
314        for value in values {
315            out.control_raw(".IP \\(bu 2");
316            match value.help() {
317                Some(help) => out.text(&format!("{}: {}", value.name(), help)),
318                None => out.text(value.name()),
319            }
320        }
321        out.control("PD", &[]);
322        out.control("RE", &[]);
323    } else if !values.is_empty() {
324        let names = values.iter().map(|x| x.name()).collect::<Vec<_>>();
325        out.control("sp", &[]);
326        out.text(&format!("[possible values: {}]", names.join(", ")));
327    }
328}
329
330fn first_line(s: &str) -> &str {
331    s.lines().next().unwrap_or("").trim()
332}
333
334/// Escapes text for roff.
335fn escape(s: &str) -> String {
336    let mut rv = String::with_capacity(s.len());
337    for c in s.chars() {
338        match c {
339            '\\' => rv.push_str("\\e"),
340            '-' => rv.push_str("\\-"),
341            '\'' => rv.push_str("\\*(Aq"),
342            c => rv.push(c),
343        }
344    }
345    rv
346}
347
348fn bold(s: &str) -> String {
349    format!("\\fB{}\\fR", escape(s))
350}
351
352fn italic(s: &str) -> String {
353    format!("\\fI{}\\fR", escape(s))
354}
355
356/// A minimal roff writer.
357#[derive(Default)]
358struct Roff(String);
359
360impl Roff {
361    fn control_raw(&mut self, s: &str) {
362        self.0.push_str(s);
363        self.0.push('\n');
364    }
365
366    fn control(&mut self, name: &str, args: &[&str]) {
367        self.0.push('.');
368        self.0.push_str(name);
369        for arg in args {
370            self.0.push(' ');
371            if arg.is_empty() || arg.contains(' ') {
372                write!(self.0, "\"{}\"", escape(arg).replace('"', "\\(dq")).unwrap();
373            } else {
374                self.0.push_str(&escape(arg));
375            }
376        }
377        self.0.push('\n');
378    }
379
380    /// Writes an already escaped line.
381    fn line(&mut self, s: &str) {
382        if s.starts_with('.') || s.starts_with('\'') {
383            self.0.push_str("\\&");
384        }
385        self.0.push_str(s);
386        self.0.push('\n');
387    }
388
389    /// Writes a line of text.
390    fn text(&mut self, s: &str) {
391        self.line(&escape(s));
392    }
393
394    /// Writes text with paragraphs.  Line breaks are preserved and empty
395    /// lines are separated with the given request (eg: `PP` or `sp`).
396    fn paragraphs(&mut self, text: &str, separator: &str) {
397        let lines = text.trim_end().lines().collect::<Vec<_>>();
398        for (idx, line) in lines.iter().enumerate() {
399            if line.trim().is_empty() {
400                self.control(separator, &[]);
401                continue;
402            }
403            self.text(line);
404            if lines.get(idx + 1).is_some_and(|x| !x.trim().is_empty()) {
405                self.control("br", &[]);
406            }
407        }
408    }
409}
410
411// the examples of the readme are tested
412#[cfg(doctest)]
413#[doc = include_str!("../README.md")]
414struct ReadmeDoctests;