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