use std::fmt::Write as _;
use conf::{Conf, introspection::ProgramOptionMeta};
pub struct Reference<'a> {
pub preamble: &'a str,
pub toml_path: &'a dyn Fn(&str) -> Option<String>,
pub credential_file_flags: &'a [&'a str],
pub tables: &'a [(&'a str, &'a [TableKey<'a>])],
}
pub struct TableKey<'a> {
pub suffix: &'a str,
pub default: &'a str,
pub description: &'a str,
}
pub fn reference_markdown<T: Conf>(reference: &Reference<'_>) -> String {
let cell = |text: String| text.replace('|', "\\|");
let code =
|value: Option<String>| value.map_or_else(|| "—".to_owned(), |value| format!("`{value}`"));
let mut output = reference.preamble.to_owned();
let mut section = None;
for option in T::program_options() {
let Some(path) = (reference.toml_path)(&option.id().to_string()) else {
continue;
};
let table_keys = reference
.tables
.iter()
.find(|(table, _)| *table == path)
.map(|(_, keys)| *keys);
let top = match path.split_once('.') {
Some((top, _)) => top.to_owned(),
None if table_keys.is_some() => path.clone(),
None => "(top level)".to_owned(),
};
if section.as_ref() != Some(&top) {
write!(
output,
"\n## {}\n\n| Setting | Default | Environment | CLI | Description |\n|---|---|---|---|---|\n",
if top == "(top level)" {
top.clone()
} else {
format!("[{top}]")
}
)
.expect("writing to a String cannot fail");
section = Some(top);
}
let description = option
.description()
.map(ToString::to_string)
.unwrap_or_default();
let summary = description
.split("\n\n")
.next()
.unwrap_or_default()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
let flag = option
.long_form()
.map(|value| format!("--{value}"))
.or_else(|| {
let sibling = format!("{path}_file");
reference
.credential_file_flags
.contains(&sibling.as_str())
.then(|| format!("--{} <PATH>", path.replace(['.', '_'], "-")))
});
writeln!(
output,
"| `{path}` | {} | {} | {} | {} |",
cell(code(option.default_help_str().map(ToString::to_string))),
cell(code(option.env_form().map(ToString::to_string))),
cell(code(flag)),
cell(summary),
)
.expect("writing to a String cannot fail");
for key in table_keys.unwrap_or_default() {
writeln!(
output,
"| `{path}{}` | {} | — | — | {} |",
key.suffix,
cell(if key.default.is_empty() {
"—".to_owned()
} else {
format!("`{}`", key.default)
}),
cell(key.description.to_owned()),
)
.expect("writing to a String cannot fail");
}
}
output
}