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 "blockchain" => "Blockchain / Crypto",
177 "build" => "Build Systems",
178 "builtins" => "Shell Builtins",
179 "clipboard" => "Clipboard",
180 "compile" => "Compilation Toolchains",
181 "configmgmt" => "Config Management",
182 "cppkg" => "C++ Package Managers",
183 "crypto" => "Cryptography",
184 "c" => "C / C++",
185 "cloud" => "Cloud Providers",
186 "containers" => "Containers",
187 "crystal" => "Crystal",
188 "d" => "D",
189 "dart" => "Dart / Flutter",
190 "data" => "Data Processing",
191 "db" => "Database Clients",
192 "editors" => "Editors",
193 "embedded" => "Embedded",
194 "dotnet" => ".NET",
195 "elixir" => "Elixir / Erlang",
196 "erlang" => "Erlang",
197 "game" => "Game Engines",
198 "gleam" => "Gleam",
199 "media" => "Media",
200 "migrations" => "Database Migrations",
201 "ml" => "ML / Observability",
202 "mobile" => "Mobile Frameworks",
203 "niche" => "Niche / Esoteric",
204 "nix" => "Nix",
205 "forges" => "Code Forges",
206 "fs" => "Filesystem",
207 "fuzzy" => "Fuzzy Finders",
208 "go" => "Go",
209 "hash" => "Hashing",
210 "haskell" => "Haskell",
211 "julia" => "Julia",
212 "jvm" => "JVM",
213 "kafka" => "Kafka",
214 "lisp" => "Common Lisp",
215 "lua" => "Lua",
216 "magick" => "ImageMagick",
217 "net" => "Networking",
218 "nim" => "Nim",
219 "node" => "Node.js",
220 "ocaml" => "OCaml",
221 "pdf" => "PDF / Document",
222 "perl" => "Perl",
223 "php" => "PHP",
224 "proof" => "Theorem Provers",
225 "scaffold" => "Project Scaffolders",
226 "serverless" => "Serverless / IaC",
227 "pm" => "Package Managers",
228 "python" => "Python",
229 "r" => "R",
230 "racket" => "Racket",
231 "roc" => "Roc",
232 "ruby" => "Ruby",
233 "rust" => "Rust",
234 "search" => "Search",
235 "swift" => "Swift",
236 "sysinfo" => "System Info",
237 "system" => "System",
238 "tex" => "TeX / LaTeX",
239 "text" => "Text Processing",
240 "tools" => "Developer Tools",
241 "vcs" => "Version Control",
242 "wasm" => "WebAssembly",
243 "wrappers" => "Shell Wrappers",
244 "xcode" => "Xcode",
245 other => panic!("unknown category '{other}' — add it to category_display_name() in src/docs.rs")
246 }
247}
248
249fn render_command_entry(doc: &CommandDoc) -> String {
250 let mut out = String::new();
251 out.push_str(&format!("### `{}`\n", doc.name));
252 out.push_str(&format!(
253 "<p class=\"cmd-url\"><a href=\"{}\">{}</a></p>\n\n",
254 doc.url, doc.url,
255 ));
256 if !doc.aliases.is_empty() {
257 let alias_str: Vec<String> = doc.aliases.iter().map(|a| format!("`{a}`")).collect();
258 out.push_str(&format!("Aliases: {}\n\n", alias_str.join(", ")));
259 }
260 out.push_str(&format!("{}\n\n", doc.description));
261 out
262}
263
264pub fn render_book(docs: &[CommandDoc], output_dir: &std::path::Path) {
265 use std::collections::BTreeMap;
266 use std::fs;
267
268 let commands_dir = output_dir.join("src").join("commands");
269 fs::create_dir_all(&commands_dir).expect("failed to create commands dir");
270
271 let mut by_category: BTreeMap<&str, Vec<&CommandDoc>> = BTreeMap::new();
272 for doc in docs {
273 by_category.entry(&doc.category).or_default().push(doc);
274 }
275
276 let total: usize = by_category.values().map(|v| v.len()).sum();
277
278 let includes_dir = output_dir.join("src").join("includes");
279 fs::create_dir_all(&includes_dir).expect("failed to create includes dir");
280 fs::write(includes_dir.join("command-count.md"), format!("{total}\n"))
281 .expect("failed to write command-count.md");
282
283 let version = env!("CARGO_PKG_VERSION");
284 fs::write(
285 output_dir.join("src").join("version-footer.js"),
286 format!(
287 "document.addEventListener('DOMContentLoaded', function() {{\n\
288 \x20 var nav = document.querySelector('.nav-wide-wrapper') || document.querySelector('.nav-wrapper');\n\
289 \x20 if (nav) {{\n\
290 \x20 var footer = document.createElement('div');\n\
291 \x20 footer.className = 'version-footer';\n\
292 \x20 footer.textContent = 'safe-chains v{version} · {total} commands';\n\
293 \x20 nav.parentNode.insertBefore(footer, nav.nextSibling);\n\
294 \x20 }}\n\
295 }});\n"
296 ),
297 )
298 .expect("failed to write version-footer.js");
299
300 let mut readme = format!(
301 "# Command Reference\n\n\
302 safe-chains knows {total} commands across {} categories.\n\n\
303 ## Glossary\n\n{GLOSSARY}\n",
304 by_category.len(),
305 );
306 for (slug, cmds) in &by_category {
307 let name = category_display_name(slug);
308 readme.push_str(&format!(
309 "- [{}]({}.md) ({} commands)\n",
310 name, slug, cmds.len(),
311 ));
312 }
313 readme.push('\n');
314 fs::write(commands_dir.join("README.md"), &readme)
315 .expect("failed to write commands/README.md");
316
317 for (slug, cmds) in &by_category {
318 let name = category_display_name(slug);
319 let mut page = format!("# {name}\n\n");
320 for doc in cmds {
321 page.push_str(&render_command_entry(doc));
322 }
323 fs::write(commands_dir.join(format!("{slug}.md")), &page)
324 .expect("failed to write category page");
325 }
326
327 eprintln!("Generated {} category pages:", by_category.len());
328 for slug in by_category.keys() {
329 eprintln!(" - [{}](commands/{}.md)", category_display_name(slug), slug);
330 }
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 #[test]
338 fn all_commands_have_url() {
339 for doc in all_command_docs() {
340 assert!(!doc.url.is_empty(), "{} has no documentation URL", doc.name);
341 assert!(
342 doc.url.starts_with("https://"),
343 "{} URL must use https: {}",
344 doc.name,
345 doc.url
346 );
347 }
348 }
349
350 #[test]
351 fn all_commands_have_valid_category() {
352 for doc in all_command_docs() {
353 assert!(!doc.category.is_empty(), "{} has no category", doc.name);
354 category_display_name(&doc.category);
355 }
356 }
357
358 #[test]
359 fn builder_two_sections() {
360 let ws = WordSet::new(&["--version", "list", "show"]);
361 assert_eq!(doc(&ws).build(), "- Subcommands: list, show\n- Flags: --version");
362 }
363
364 #[test]
365 fn builder_subcommands_only() {
366 let ws = WordSet::new(&["list", "show"]);
367 assert_eq!(doc(&ws).build(), "- Subcommands: list, show");
368 }
369
370 #[test]
371 fn builder_flags_only() {
372 let ws = WordSet::new(&["--check", "--version"]);
373 assert_eq!(doc(&ws).build(), "- Flags: --check, --version");
374 }
375
376 #[test]
377 fn builder_three_sections() {
378 let ws = WordSet::new(&["--version", "list", "show"]);
379 assert_eq!(
380 doc(&ws).section("Guarded: foo (bar only).").build(),
381 "- Subcommands: list, show\n- Flags: --version\n- Guarded: foo (bar only)."
382 );
383 }
384
385 #[test]
386 fn builder_multi_word_merged() {
387 let ws = WordSet::new(&["--version", "info", "show"]);
388 let multi: &[(&str, WordSet)] =
389 &[("config", WordSet::new(&["get", "list"]))];
390 assert_eq!(
391 doc_multi(&ws, multi).build(),
392 "- Subcommands: config get, config list, info, show\n- Flags: --version"
393 );
394 }
395
396 #[test]
397 fn builder_multi_word_with_extra_section() {
398 let ws = WordSet::new(&["--version", "show"]);
399 let multi: &[(&str, WordSet)] =
400 &[("config", WordSet::new(&["get", "list"]))];
401 assert_eq!(
402 doc_multi(&ws, multi).section("Guarded: foo.").build(),
403 "- Subcommands: config get, config list, show\n- Flags: --version\n- Guarded: foo."
404 );
405 }
406
407 #[test]
408 fn builder_no_flags_with_extra() {
409 let ws = WordSet::new(&["list", "show"]);
410 assert_eq!(
411 doc(&ws).section("Also: foo.").build(),
412 "- Subcommands: list, show\n- Also: foo."
413 );
414 }
415
416 #[test]
417 fn builder_custom_sections_only() {
418 assert_eq!(
419 DocBuilder::new()
420 .section("Read-only: foo.")
421 .section("Always safe: bar.")
422 .section("Guarded: baz.")
423 .build(),
424 "- Read-only: foo.\n- Always safe: bar.\n- Guarded: baz."
425 );
426 }
427
428 #[test]
429 fn builder_triple_word() {
430 let ws = WordSet::new(&["--version", "diff"]);
431 let triples: &[(&str, &str, WordSet)] =
432 &[("git", "remote", WordSet::new(&["list"]))];
433 assert_eq!(
434 doc(&ws).triple_word(triples).build(),
435 "- Subcommands: diff, git remote list\n- Flags: --version"
436 );
437 }
438
439 #[test]
440 fn builder_subcommand_method() {
441 let ws = WordSet::new(&["--version", "list"]);
442 assert_eq!(
443 doc(&ws).subcommand("plugin-list").build(),
444 "- Subcommands: list, plugin-list\n- Flags: --version"
445 );
446 }
447
448}