Skip to main content

didbot_cli/
reference.rs

1//! The CLI reference in the workspace's `README.md`, made from each binary's
2//! own `--help`.
3//!
4//! Every binary a person runs has a `cli_reference` test that renders its
5//! section and fails while the README holds anything else, so a new
6//! subcommand or flag cannot land without its entry. A clap binary also fails
7//! on any subcommand or argument with no help text, since that text is the
8//! whole reference. `scripts/gen-cli-reference.sh` writes every section again.
9//!
10//! Behind the `reference` feature, which only those tests turn on.
11
12use std::path::PathBuf;
13
14use clap::Command;
15
16/// Set to anything but empty, and a stale section is written rather than
17/// failed.
18pub const BLESS: &str = "DIDBOT_BLESS_README";
19
20/// The column help text is wrapped at, whatever terminal the test runs in.
21const WIDTH: usize = 100;
22
23/// What a developer runs when a section is stale.
24const FIX: &str = "run scripts/gen-cli-reference.sh and stage README.md";
25
26/// Checks the section of a binary whose parser is clap.
27///
28/// # Panics
29///
30/// When a subcommand or argument has no help text, or the section is stale
31/// and [`BLESS`] is unset.
32pub fn check_command(binary: &str, command: Command) {
33    let mut command = command.term_width(WIDTH);
34    command.build();
35    let missing = undocumented(&command);
36    assert!(
37        missing.is_empty(),
38        "{binary}: give these help text, which the README's CLI reference is made of:\n  {}",
39        missing.join("\n  ")
40    );
41    check(binary, &section(binary, &pages(binary, &command)));
42}
43
44/// Checks the section of a binary that prints a hand-written usage.
45///
46/// # Panics
47///
48/// When the section is stale and [`BLESS`] is unset.
49pub fn check_usage(binary: &str, usage: &str) {
50    check(
51        binary,
52        &section(binary, &[(binary.to_owned(), usage.to_owned())]),
53    );
54}
55
56fn check(binary: &str, section: &str) {
57    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../README.md");
58    let readme = std::fs::read_to_string(&path).expect("the workspace README");
59    let Some(wanted) = stale(&readme, binary, section).unwrap_or_else(|why| panic!("{why}")) else {
60        return;
61    };
62    if std::env::var_os(BLESS).is_some_and(|set| !set.is_empty()) {
63        std::fs::write(&path, wanted).expect("the workspace README is writable");
64        return;
65    }
66    panic!("README.md's CLI reference for {binary} is not what its --help prints: {FIX}");
67}
68
69/// The README with `binary`'s section replaced by `section`, or `None` when
70/// it already holds exactly that.
71fn stale(readme: &str, binary: &str, section: &str) -> Result<Option<String>, String> {
72    let begin = format!("<!-- cli-reference {binary} -->\n");
73    let end = format!("<!-- /cli-reference {binary} -->");
74    let missing = || format!("README.md has no `{begin}` … `{end}` pair to write {binary} into");
75    let start = readme.find(&begin).ok_or_else(missing)? + begin.len();
76    let stop = start + readme[start..].find(&end).ok_or_else(missing)?;
77    if &readme[start..stop] == section {
78        return Ok(None);
79    }
80    Ok(Some(format!(
81        "{}{section}{}",
82        &readme[..start],
83        &readme[stop..]
84    )))
85}
86
87/// One collapsed block per binary, and in it each command's help under a
88/// heading naming what a person types.
89fn section(binary: &str, pages: &[(String, String)]) -> String {
90    let mut out = format!("<details>\n<summary><code>{binary}</code></summary>\n\n");
91    for (title, help) in pages {
92        let help: Vec<&str> = help.trim_end().lines().map(str::trim_end).collect();
93        out.push_str(&format!(
94            "### `{title}`\n\n```text\n{}\n```\n\n",
95            help.join("\n")
96        ));
97    }
98    out.push_str("</details>\n");
99    out
100}
101
102/// Every command a person can reach, each with its `--help`: the root under
103/// the binary's name, and each subcommand as a person types it.
104fn pages(binary: &str, command: &Command) -> Vec<(String, String)> {
105    let mut out = Vec::new();
106    walk(command, &mut |sub| {
107        let title = match sub.get_bin_name() {
108            Some(typed) if !std::ptr::eq(sub, command) => typed,
109            _ => binary,
110        };
111        out.push((title.to_owned(), sub.clone().render_long_help().to_string()));
112    });
113    out
114}
115
116/// Every subcommand and argument with no help text, by where it sits.
117fn undocumented(command: &Command) -> Vec<String> {
118    let mut out = Vec::new();
119    walk(command, &mut |command| {
120        let title = command.get_bin_name().unwrap_or(command.get_name());
121        if command.get_about().is_none() && command.get_long_about().is_none() {
122            out.push(title.to_owned());
123        }
124        for arg in command.get_arguments().filter(|arg| !arg.is_hide_set()) {
125            if arg.get_help().is_none() && arg.get_long_help().is_none() {
126                out.push(format!("{title}: {}", arg.get_id()));
127            }
128        }
129    });
130    out
131}
132
133/// `visit` on `command` and every visible subcommand beneath it, skipping the
134/// `help` subcommand clap adds.
135fn walk(command: &Command, visit: &mut impl FnMut(&Command)) {
136    visit(command);
137    for sub in command.get_subcommands() {
138        if !sub.is_hide_set() && sub.get_name() != "help" {
139            walk(sub, visit);
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use clap::{Arg, Command};
147
148    use super::{pages, section, stale, undocumented};
149
150    fn tool() -> Command {
151        Command::new("tool")
152            .about("Does a thing")
153            .subcommand(Command::new("list").about("Lists the things"))
154    }
155
156    fn rendered(mut command: Command) -> String {
157        command.build();
158        section("tool", &pages("tool", &command))
159    }
160
161    fn readme(section: &str) -> String {
162        format!("# Title\n\n<!-- cli-reference tool -->\n{section}<!-- /cli-reference tool -->\n\nAfter.\n")
163    }
164
165    /// A README written from one parser is current for it, and stale as soon
166    /// as a subcommand is added without writing it again. The rewrite holds
167    /// the new subcommand and leaves the rest of the file alone.
168    #[test]
169    fn a_new_subcommand_makes_the_written_reference_stale() {
170        let written = readme(&rendered(tool()));
171        assert_eq!(stale(&written, "tool", &rendered(tool())), Ok(None));
172
173        let grown = tool().subcommand(Command::new("export").about("Exports the things"));
174        let fixed = stale(&written, "tool", &rendered(grown.clone()))
175            .unwrap()
176            .expect("the added subcommand is not in the README yet");
177        assert!(fixed.contains("### `tool export`"), "{fixed}");
178        assert!(fixed.starts_with("# Title\n\n") && fixed.ends_with("\n\nAfter.\n"));
179        assert_eq!(stale(&fixed, "tool", &rendered(grown)), Ok(None));
180    }
181
182    /// A binary with no place in the README is refused rather than appended
183    /// somewhere a person did not choose.
184    #[test]
185    fn a_readme_without_the_markers_is_refused() {
186        let error = stale("# Title\n", "tool", &rendered(tool())).unwrap_err();
187        assert!(error.contains("<!-- cli-reference tool -->"), "{error}");
188    }
189
190    /// A flag or subcommand with no help text is named, so its section never
191    /// carries an entry that says nothing.
192    #[test]
193    fn an_argument_or_subcommand_without_help_is_named() {
194        let mut command = tool()
195            .arg(Arg::new("quiet").long("quiet"))
196            .subcommand(Command::new("export"));
197        command.build();
198        assert_eq!(
199            undocumented(&command),
200            ["tool: quiet", "tool export"].map(str::to_owned)
201        );
202    }
203}