Skip to main content

safe_chains/
docs.rs

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