use alloc::collections::VecDeque;
use core::fmt::{
self,
Write as _,
};
use pound::spec::{
ArgSpec,
Command,
CommandSpec,
Kind,
};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Page {
pub name: String,
pub content: String,
}
impl Page {
#[must_use]
pub fn file_name(&self) -> String {
format!("{}.1", self.name)
}
}
#[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(|arg| matches!(arg.kind, Kind::Flag | Kind::Count))
.collect::<Vec<_>>();
let bundle = switches
.iter()
.filter_map(|arg| arg.short)
.collect::<String>();
if !bundle.is_empty() {
page.line(format_args!("Op Fl {}", Word(&bundle)));
}
for arg in switches.iter().filter(|arg| arg.short.is_none()) {
page.line(format_args!("Op {}", Flag(arg)));
}
for arg in self.options.iter().filter(|arg| arg.kind == Kind::Opt) {
let op = if arg.required { "" } else { "Op " };
if arg.value_may_be_left_out() {
let attached = Attached {
arg,
long: arg.short.is_none(),
};
page.line(format_args!("{op}{}{attached}", Flag(arg)));
} else {
page.line(format_args!("{op}{} {}", Flag(arg), Values(arg)));
}
}
for arg in &self.positionals {
if arg.kind == Kind::Last {
page.line(format_args!("Op Fl - Ar {} ...", Meta(arg)));
continue;
}
let dots = if arg.multi || arg.kind == Kind::Trailing {
" ..."
} else {
""
};
let op = if arg.required { "" } else { "Op " };
page.line(format_args!("{op}Ar {}{dots}", Meta(arg)));
}
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, |doc, arg| {
doc.line(format_args!("It Ar {}", Meta(arg)));
doc.describe(arg);
});
}
if !self.options.is_empty() {
page.paragraph();
page.text("The options are as follows:");
page.list(&self.options, |doc, arg| {
doc.line(format_args!("It {}", Item(arg)));
doc.describe(arg);
});
}
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, |doc, (name, operands, about)| {
doc.line(format_args!("It Cm {}{operands}", Word(name)));
doc.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(|page_name| page_name.to_lowercase());
if pages.is_empty() {
return;
}
page.line("Sh SEE ALSO");
let last = pages.len() - 1;
for (index, page_name) in pages.iter().enumerate() {
let comma = if index == last { "" } else { " ," };
page.line(format_args!("Xr {} 1{comma}", Word(page_name)));
}
}
fn environment(&self, page: &mut Mdoc) {
let env = self
.options
.iter()
.chain(self.positionals.iter().copied())
.filter_map(|arg| Some((arg.env.filter(|_| !arg.hide_env)?, arg)))
.collect::<Vec<_>>();
if env.is_empty() {
return;
}
page.line("Sh ENVIRONMENT");
page.list(env, |doc, (var, arg)| {
doc.line(format_args!("It Ev {}", Word(var)));
doc.text("Default for");
match (arg.long, arg.short) {
_ if arg.is_positional() => doc.line(format_args!("Ar {} .", Meta(arg))),
(Some(long), _) => doc.line(format_args!("Fl \\-{} .", Word(long))),
(None, Some(short)) => {
doc.line(format_args!(
"Fl {} .",
Word(short.encode_utf8(&mut [0; 4]))
));
},
(None, None) => doc.line(format_args!("Ar {} .", Meta(arg))),
}
});
}
}
#[derive(Default)]
struct Mdoc {
out: String,
}
impl Mdoc {
fn line(&mut self, line: impl fmt::Display) {
let _write_result = writeln!(self.out, ".{line}");
}
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);
}
}
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(|chunk| chunk.trim_matches('\n'))
.filter(|chunk| !chunk.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 = margin.map_or_else(|| line.trim(), |width| line[width..].trim_end());
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, arg: &ArgSpec) {
self.text(arg.long_help.unwrap_or(arg.help));
let choices = arg
.possible
.filter(|_| !arg.hide_possible)
.unwrap_or_default()
.iter()
.filter(|choice| !choice.hidden)
.collect::<Vec<_>>();
if choices.iter().any(|choice| !choice.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) = arg
.default
.filter(|_| arg.kind != Kind::Flag && !arg.hide_default)
{
self.line("Pp");
self.text("Defaults to");
self.line(format_args!("Ql {} .", Word(default)));
}
}
}
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 ch in word.chars() {
match ch {
'\\' => f.write_str("\\e")?,
'"' => f.write_str("\\(dq")?,
_ => f.write_char(ch)?,
}
}
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(())
}
}
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 arg = self.0;
match (arg.short, arg.long) {
(Some(short), _) => write!(f, "Fl {}", Word(short.encode_utf8(&mut [0; 4]))),
(None, Some(long)) => write!(f, "Fl \\-{}", Word(long)),
(None, None) => write!(f, "Ar {}", Meta(arg)),
}
}
}
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 arg = self.0;
let shorts = arg.short.map(Spelling::Short);
let longs = arg.long.into_iter().chain(arg.negate).map(Spelling::Long);
for (i, spelling) in shorts.into_iter().chain(longs).enumerate() {
if i > 0 {
f.write_str(" , ")?;
}
match spelling {
Spelling::Short(short) => write!(f, "Fl {}", Word(short.encode_utf8(&mut [0; 4])))?,
Spelling::Long(long) => write!(f, "Fl \\-{}", Word(long))?,
}
match (arg.kind, spelling) {
(Kind::Opt, _) if arg.value_may_be_left_out() => {
let long = matches!(spelling, Spelling::Long(_));
write!(f, "{}", Attached { arg, long })?;
},
(Kind::Opt, Spelling::Long(_)) if arg.words_per_use().is_none() => {
write!(f, " Ns = Ns Ar {}", Meta(arg))?;
},
(Kind::Opt, _) => write!(f, " {}", Values(arg))?,
_ => {},
}
}
Ok(())
}
}