1use crate::handlers;
2use crate::parse::WordSet;
3
4pub struct CommandDoc {
5 pub name: String,
6 pub kind: DocKind,
7 pub url: &'static str,
8 pub description: String,
9 pub aliases: Vec<String>,
10 pub category: String,
11}
12
13pub enum DocKind {
14 Handler,
15}
16
17impl CommandDoc {
18 pub fn handler(name: &'static str, url: &'static str, description: impl Into<String>, category: &str) -> Self {
19 let raw = description.into();
20 let description = raw
21 .lines()
22 .map(|line| {
23 if line.is_empty() || line.starts_with("- ") {
24 line.to_string()
25 } else {
26 format!("- {line}")
27 }
28 })
29 .collect::<Vec<_>>()
30 .join("\n");
31 Self { name: name.to_string(), kind: DocKind::Handler, url, description, aliases: Vec::new(), category: category.to_string() }
32 }
33
34 pub fn wordset(name: &'static str, url: &'static str, words: &WordSet, category: &str) -> Self {
35 Self::handler(name, url, doc(words).build(), category)
36 }
37
38 pub fn wordset_multi(name: &'static str, url: &'static str, words: &WordSet, multi: &[(&str, WordSet)], category: &str) -> Self {
39 Self::handler(name, url, doc_multi(words, multi).build(), category)
40 }
41
42
43}
44
45#[derive(Default)]
46pub struct DocBuilder {
47 subcommands: Vec<String>,
48 flags: Vec<String>,
49 sections: Vec<String>,
50}
51
52impl DocBuilder {
53 pub fn new() -> Self {
54 Self::default()
55 }
56
57 pub fn wordset(mut self, words: &WordSet) -> Self {
58 for item in words.iter() {
59 if item.starts_with('-') {
60 self.flags.push(item.to_string());
61 } else {
62 self.subcommands.push(item.to_string());
63 }
64 }
65 self
66 }
67
68 pub fn multi_word(mut self, multi: &[(&str, WordSet)]) -> Self {
69 for (prefix, actions) in multi {
70 for action in actions.iter() {
71 self.subcommands.push(format!("{prefix} {action}"));
72 }
73 }
74 self
75 }
76
77 pub fn triple_word(mut self, triples: &[(&str, &str, WordSet)]) -> Self {
78 for (a, b, actions) in triples {
79 for action in actions.iter() {
80 self.subcommands.push(format!("{a} {b} {action}"));
81 }
82 }
83 self
84 }
85
86 pub fn subcommand(mut self, name: impl Into<String>) -> Self {
87 self.subcommands.push(name.into());
88 self
89 }
90
91 pub fn section(mut self, text: impl Into<String>) -> Self {
92 let s = text.into();
93 if !s.is_empty() {
94 self.sections.push(s);
95 }
96 self
97 }
98
99 pub fn build(self) -> String {
100 let mut lines = Vec::new();
101 if !self.subcommands.is_empty() {
102 let mut subs = self.subcommands;
103 subs.sort();
104 lines.push(format!("- Subcommands: {}", subs.join(", ")));
105 }
106 if !self.flags.is_empty() {
107 lines.push(format!("- Flags: {}", self.flags.join(", ")));
108 }
109 for s in self.sections {
110 if s.starts_with("- ") {
111 lines.push(s);
112 } else {
113 lines.push(format!("- {s}"));
114 }
115 }
116 lines.join("\n")
117 }
118}
119
120pub fn doc(words: &WordSet) -> DocBuilder {
121 DocBuilder::new().wordset(words)
122}
123
124pub fn doc_multi(words: &WordSet, multi: &[(&str, WordSet)]) -> DocBuilder {
125 DocBuilder::new().wordset(words).multi_word(multi)
126}
127
128pub fn wordset_items(words: &WordSet) -> String {
129 let items: Vec<&str> = words.iter().collect();
130 items.join(", ")
131}
132
133
134pub fn all_command_docs() -> Vec<CommandDoc> {
135 let mut docs = handlers::handler_docs();
136 docs.sort_by_key(|a| a.name.to_ascii_lowercase());
137 docs
138}
139
140const GLOSSARY: &str = "\
141| Term | Meaning |\n\
142|------|---------|\n\
143| **Allowed standalone flags** | Flags that take no value (`--verbose`, `-v`). Listed on flat commands. |\n\
144| **Flags** | Same as standalone flags, but in the shorter format used within subcommand entries. |\n\
145| **Allowed valued flags** | Flags that require a value (`--output file`, `-j 4`). |\n\
146| **Valued** | Same as valued flags, in shorter format within subcommand entries. |\n\
147| **Bare invocation allowed** | The command can be run with no arguments at all. |\n\
148| **Subcommands** | Named subcommands that are allowed (e.g. `git log`, `cargo test`). |\n\
149| **Positional arguments only** | No specific flags are listed; only positional arguments are accepted. |\n\
150| **(requires --flag)** | A guarded subcommand that is only allowed when a specific flag is present (e.g. `cargo fmt` requires `--check`). |\n\
151\n\
152Unlisted flags, subcommands, and commands are not allowed.\n";
153
154pub fn render_markdown(docs: &[CommandDoc]) -> String {
155 let mut out = format!(
156 "# Supported Commands\n\n\
157 Auto-generated by `safe-chains --list-commands`. These commands, subcommands, and flags are safe to run individually or in combination.\n\n\
158 ## Glossary\n\n{GLOSSARY}\n",
159 );
160
161 for doc in docs {
162 out.push_str(&render_command_entry(doc));
163 }
164
165 out
166}
167
168fn category_display_name(slug: &str) -> &'static str {
169 match slug {
170 "ai" => "AI Tools",
171 "android" => "Android",
172 "ansible" => "Ansible",
173 "api" => "API / Load Testing",
174 "archive" => "Compression / Archive",
175 "binary" => "Binary Analysis",
176 "build" => "Build Systems",
177 "builtins" => "Shell Builtins",
178 "crypto" => "Cryptography",
179 "c" => "C / C++",
180 "cloud" => "Cloud Providers",
181 "containers" => "Containers",
182 "crystal" => "Crystal",
183 "d" => "D",
184 "dart" => "Dart / Flutter",
185 "data" => "Data Processing",
186 "db" => "Database Clients",
187 "editors" => "Editors",
188 "embedded" => "Embedded",
189 "dotnet" => ".NET",
190 "elixir" => "Elixir / Erlang",
191 "erlang" => "Erlang",
192 "gleam" => "Gleam",
193 "media" => "Media",
194 "ml" => "ML / Observability",
195 "forges" => "Code Forges",
196 "fs" => "Filesystem",
197 "fuzzy" => "Fuzzy Finders",
198 "go" => "Go",
199 "hash" => "Hashing",
200 "haskell" => "Haskell",
201 "julia" => "Julia",
202 "jvm" => "JVM",
203 "kafka" => "Kafka",
204 "lisp" => "Common Lisp",
205 "lua" => "Lua",
206 "magick" => "ImageMagick",
207 "net" => "Networking",
208 "nim" => "Nim",
209 "node" => "Node.js",
210 "ocaml" => "OCaml",
211 "perl" => "Perl",
212 "php" => "PHP",
213 "proof" => "Theorem Provers",
214 "pm" => "Package Managers",
215 "python" => "Python",
216 "r" => "R",
217 "racket" => "Racket",
218 "roc" => "Roc",
219 "ruby" => "Ruby",
220 "rust" => "Rust",
221 "search" => "Search",
222 "swift" => "Swift",
223 "sysinfo" => "System Info",
224 "system" => "System",
225 "tex" => "TeX / LaTeX",
226 "text" => "Text Processing",
227 "tools" => "Developer Tools",
228 "vcs" => "Version Control",
229 "wasm" => "WebAssembly",
230 "wrappers" => "Shell Wrappers",
231 "xcode" => "Xcode",
232 other => panic!("unknown category '{other}' — add it to category_display_name() in src/docs.rs")
233 }
234}
235
236fn render_command_entry(doc: &CommandDoc) -> String {
237 let mut out = String::new();
238 out.push_str(&format!("### `{}`\n", doc.name));
239 out.push_str(&format!(
240 "<p class=\"cmd-url\"><a href=\"{}\">{}</a></p>\n\n",
241 doc.url, doc.url,
242 ));
243 if !doc.aliases.is_empty() {
244 let alias_str: Vec<String> = doc.aliases.iter().map(|a| format!("`{a}`")).collect();
245 out.push_str(&format!("Aliases: {}\n\n", alias_str.join(", ")));
246 }
247 out.push_str(&format!("{}\n\n", doc.description));
248 out
249}
250
251pub fn render_book(docs: &[CommandDoc], output_dir: &std::path::Path) {
252 use std::collections::BTreeMap;
253 use std::fs;
254
255 let commands_dir = output_dir.join("src").join("commands");
256 fs::create_dir_all(&commands_dir).expect("failed to create commands dir");
257
258 let mut by_category: BTreeMap<&str, Vec<&CommandDoc>> = BTreeMap::new();
259 for doc in docs {
260 by_category.entry(&doc.category).or_default().push(doc);
261 }
262
263 let total: usize = by_category.values().map(|v| v.len()).sum();
264
265 let includes_dir = output_dir.join("src").join("includes");
266 fs::create_dir_all(&includes_dir).expect("failed to create includes dir");
267 fs::write(includes_dir.join("command-count.md"), format!("{total}\n"))
268 .expect("failed to write command-count.md");
269
270 let version = env!("CARGO_PKG_VERSION");
271 fs::write(
272 output_dir.join("src").join("version-footer.js"),
273 format!(
274 "document.addEventListener('DOMContentLoaded', function() {{\n\
275 \x20 var nav = document.querySelector('.nav-wide-wrapper') || document.querySelector('.nav-wrapper');\n\
276 \x20 if (nav) {{\n\
277 \x20 var footer = document.createElement('div');\n\
278 \x20 footer.className = 'version-footer';\n\
279 \x20 footer.textContent = 'safe-chains v{version} · {total} commands';\n\
280 \x20 nav.parentNode.insertBefore(footer, nav.nextSibling);\n\
281 \x20 }}\n\
282 }});\n"
283 ),
284 )
285 .expect("failed to write version-footer.js");
286
287 let mut readme = format!(
288 "# Command Reference\n\n\
289 safe-chains knows {total} commands across {} categories.\n\n\
290 ## Glossary\n\n{GLOSSARY}\n",
291 by_category.len(),
292 );
293 for (slug, cmds) in &by_category {
294 let name = category_display_name(slug);
295 readme.push_str(&format!(
296 "- [{}]({}.md) ({} commands)\n",
297 name, slug, cmds.len(),
298 ));
299 }
300 readme.push('\n');
301 fs::write(commands_dir.join("README.md"), &readme)
302 .expect("failed to write commands/README.md");
303
304 for (slug, cmds) in &by_category {
305 let name = category_display_name(slug);
306 let mut page = format!("# {name}\n\n");
307 for doc in cmds {
308 page.push_str(&render_command_entry(doc));
309 }
310 fs::write(commands_dir.join(format!("{slug}.md")), &page)
311 .expect("failed to write category page");
312 }
313
314 eprintln!("Generated {} category pages:", by_category.len());
315 for slug in by_category.keys() {
316 eprintln!(" - [{}](commands/{}.md)", category_display_name(slug), slug);
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323
324 #[test]
325 fn all_commands_have_url() {
326 for doc in all_command_docs() {
327 assert!(!doc.url.is_empty(), "{} has no documentation URL", doc.name);
328 assert!(
329 doc.url.starts_with("https://"),
330 "{} URL must use https: {}",
331 doc.name,
332 doc.url
333 );
334 }
335 }
336
337 #[test]
338 fn all_commands_have_valid_category() {
339 for doc in all_command_docs() {
340 assert!(!doc.category.is_empty(), "{} has no category", doc.name);
341 category_display_name(&doc.category);
342 }
343 }
344
345 #[test]
346 fn builder_two_sections() {
347 let ws = WordSet::new(&["--version", "list", "show"]);
348 assert_eq!(doc(&ws).build(), "- Subcommands: list, show\n- Flags: --version");
349 }
350
351 #[test]
352 fn builder_subcommands_only() {
353 let ws = WordSet::new(&["list", "show"]);
354 assert_eq!(doc(&ws).build(), "- Subcommands: list, show");
355 }
356
357 #[test]
358 fn builder_flags_only() {
359 let ws = WordSet::new(&["--check", "--version"]);
360 assert_eq!(doc(&ws).build(), "- Flags: --check, --version");
361 }
362
363 #[test]
364 fn builder_three_sections() {
365 let ws = WordSet::new(&["--version", "list", "show"]);
366 assert_eq!(
367 doc(&ws).section("Guarded: foo (bar only).").build(),
368 "- Subcommands: list, show\n- Flags: --version\n- Guarded: foo (bar only)."
369 );
370 }
371
372 #[test]
373 fn builder_multi_word_merged() {
374 let ws = WordSet::new(&["--version", "info", "show"]);
375 let multi: &[(&str, WordSet)] =
376 &[("config", WordSet::new(&["get", "list"]))];
377 assert_eq!(
378 doc_multi(&ws, multi).build(),
379 "- Subcommands: config get, config list, info, show\n- Flags: --version"
380 );
381 }
382
383 #[test]
384 fn builder_multi_word_with_extra_section() {
385 let ws = WordSet::new(&["--version", "show"]);
386 let multi: &[(&str, WordSet)] =
387 &[("config", WordSet::new(&["get", "list"]))];
388 assert_eq!(
389 doc_multi(&ws, multi).section("Guarded: foo.").build(),
390 "- Subcommands: config get, config list, show\n- Flags: --version\n- Guarded: foo."
391 );
392 }
393
394 #[test]
395 fn builder_no_flags_with_extra() {
396 let ws = WordSet::new(&["list", "show"]);
397 assert_eq!(
398 doc(&ws).section("Also: foo.").build(),
399 "- Subcommands: list, show\n- Also: foo."
400 );
401 }
402
403 #[test]
404 fn builder_custom_sections_only() {
405 assert_eq!(
406 DocBuilder::new()
407 .section("Read-only: foo.")
408 .section("Always safe: bar.")
409 .section("Guarded: baz.")
410 .build(),
411 "- Read-only: foo.\n- Always safe: bar.\n- Guarded: baz."
412 );
413 }
414
415 #[test]
416 fn builder_triple_word() {
417 let ws = WordSet::new(&["--version", "diff"]);
418 let triples: &[(&str, &str, WordSet)] =
419 &[("git", "remote", WordSet::new(&["list"]))];
420 assert_eq!(
421 doc(&ws).triple_word(triples).build(),
422 "- Subcommands: diff, git remote list\n- Flags: --version"
423 );
424 }
425
426 #[test]
427 fn builder_subcommand_method() {
428 let ws = WordSet::new(&["--version", "list"]);
429 assert_eq!(
430 doc(&ws).subcommand("plugin-list").build(),
431 "- Subcommands: list, plugin-list\n- Flags: --version"
432 );
433 }
434
435}