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