1use std::path::PathBuf;
13
14use clap::Command;
15
16pub const BLESS: &str = "DIDBOT_BLESS_README";
19
20const WIDTH: usize = 100;
22
23const FIX: &str = "run scripts/gen-cli-reference.sh and stage README.md";
25
26pub 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, §ion(binary, &pages(binary, &command)));
42}
43
44pub fn check_usage(binary: &str, usage: &str) {
50 check(
51 binary,
52 §ion(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
69fn 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
87fn 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
102fn 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
116fn 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
133fn 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 #[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 #[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 #[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}