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}
11
12pub enum DocKind {
13    Handler,
14}
15
16impl CommandDoc {
17    pub fn handler(name: &'static str, url: &'static str, description: impl Into<String>) -> Self {
18        let raw = description.into();
19        let description = raw
20            .lines()
21            .map(|line| {
22                if line.is_empty() || line.starts_with("- ") {
23                    line.to_string()
24                } else {
25                    format!("- {line}")
26                }
27            })
28            .collect::<Vec<_>>()
29            .join("\n");
30        Self { name: name.to_string(), kind: DocKind::Handler, url, description, aliases: Vec::new() }
31    }
32
33    pub fn wordset(name: &'static str, url: &'static str, words: &WordSet) -> Self {
34        Self::handler(name, url, doc(words).build())
35    }
36
37    pub fn wordset_multi(name: &'static str, url: &'static str, words: &WordSet, multi: &[(&str, WordSet)]) -> Self {
38        Self::handler(name, url, doc_multi(words, multi).build())
39    }
40
41
42}
43
44#[derive(Default)]
45pub struct DocBuilder {
46    subcommands: Vec<String>,
47    flags: Vec<String>,
48    sections: Vec<String>,
49}
50
51impl DocBuilder {
52    pub fn new() -> Self {
53        Self::default()
54    }
55
56    pub fn wordset(mut self, words: &WordSet) -> Self {
57        for item in words.iter() {
58            if item.starts_with('-') {
59                self.flags.push(item.to_string());
60            } else {
61                self.subcommands.push(item.to_string());
62            }
63        }
64        self
65    }
66
67    pub fn multi_word(mut self, multi: &[(&str, WordSet)]) -> Self {
68        for (prefix, actions) in multi {
69            for action in actions.iter() {
70                self.subcommands.push(format!("{prefix} {action}"));
71            }
72        }
73        self
74    }
75
76    pub fn triple_word(mut self, triples: &[(&str, &str, WordSet)]) -> Self {
77        for (a, b, actions) in triples {
78            for action in actions.iter() {
79                self.subcommands.push(format!("{a} {b} {action}"));
80            }
81        }
82        self
83    }
84
85    pub fn subcommand(mut self, name: impl Into<String>) -> Self {
86        self.subcommands.push(name.into());
87        self
88    }
89
90    pub fn section(mut self, text: impl Into<String>) -> Self {
91        let s = text.into();
92        if !s.is_empty() {
93            self.sections.push(s);
94        }
95        self
96    }
97
98    pub fn build(self) -> String {
99        let mut lines = Vec::new();
100        if !self.subcommands.is_empty() {
101            let mut subs = self.subcommands;
102            subs.sort();
103            lines.push(format!("- Subcommands: {}", subs.join(", ")));
104        }
105        if !self.flags.is_empty() {
106            lines.push(format!("- Flags: {}", self.flags.join(", ")));
107        }
108        for s in self.sections {
109            if s.starts_with("- ") {
110                lines.push(s);
111            } else {
112                lines.push(format!("- {s}"));
113            }
114        }
115        lines.join("\n")
116    }
117}
118
119pub fn doc(words: &WordSet) -> DocBuilder {
120    DocBuilder::new().wordset(words)
121}
122
123pub fn doc_multi(words: &WordSet, multi: &[(&str, WordSet)]) -> DocBuilder {
124    DocBuilder::new().wordset(words).multi_word(multi)
125}
126
127pub fn wordset_items(words: &WordSet) -> String {
128    let items: Vec<&str> = words.iter().collect();
129    items.join(", ")
130}
131
132
133pub fn all_command_docs() -> Vec<CommandDoc> {
134    let mut docs = handlers::handler_docs();
135    docs.sort_by(|a, b| a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase()));
136    docs
137}
138
139pub fn render_markdown(docs: &[CommandDoc]) -> String {
140    let mut out = String::from(
141        "# Supported Commands\n\
142         \n\
143         Auto-generated by `safe-chains --list-commands`. These commands, subcommands, and flags are safe to run individually or in combination.\n\
144         \n\
145         ## Glossary\n\
146         \n\
147         | Term | Meaning |\n\
148         |------|---------|\n\
149         | **Allowed standalone flags** | Flags that take no value (`--verbose`, `-v`). Listed on flat commands. |\n\
150         | **Flags** | Same as standalone flags, but in the shorter format used within subcommand entries. |\n\
151         | **Allowed valued flags** | Flags that require a value (`--output file`, `-j 4`). |\n\
152         | **Valued** | Same as valued flags, in shorter format within subcommand entries. |\n\
153         | **Bare invocation allowed** | The command can be run with no arguments at all. |\n\
154         | **Subcommands** | Named subcommands that are allowed (e.g. `git log`, `cargo test`). |\n\
155         | **Positional arguments only** | No specific flags are listed; only positional arguments are accepted. |\n\
156         | **(requires --flag)** | A guarded subcommand that is only allowed when a specific flag is present (e.g. `cargo fmt` requires `--check`). |\n\
157         \n\
158         Unlisted flags, subcommands, and commands are not allowed.\n\n",
159    );
160
161    for doc in docs {
162        if doc.aliases.is_empty() {
163            out.push_str(&format!("### `{}` ({})\n\n", doc.name, doc.url));
164        } else {
165            let alias_str: Vec<String> = doc.aliases.iter().map(|a| format!("`{a}`")).collect();
166            out.push_str(&format!(
167                "### `{}` ({})\n\nAliases: {}\n\n",
168                doc.name, doc.url, alias_str.join(", ")
169            ));
170        }
171        out.push_str(&format!("{}\n\n", doc.description));
172    }
173
174    out
175}
176
177pub fn render_opencode_json(patterns: &[String]) -> String {
178    use serde_json::{Map, Value};
179    use std::fs;
180
181    let mut root: Map<String, Value> = fs::read_to_string("opencode.json")
182        .ok()
183        .and_then(|s| serde_json::from_str(&s).ok())
184        .and_then(|v: Value| v.as_object().cloned())
185        .unwrap_or_else(|| {
186            let mut m = Map::new();
187            m.insert(
188                "$schema".to_string(),
189                Value::String("https://opencode.ai/config.json".to_string()),
190            );
191            m
192        });
193
194    let mut bash = Map::new();
195    bash.insert("*".to_string(), Value::String("ask".to_string()));
196    for pat in patterns {
197        bash.insert(pat.clone(), Value::String("allow".to_string()));
198    }
199
200    let permission = root
201        .entry("permission")
202        .or_insert_with(|| Value::Object(Map::new()));
203    if !permission.is_object() {
204        *permission = Value::Object(Map::new());
205    }
206    if let Value::Object(perm_map) = permission {
207        perm_map.insert("bash".to_string(), Value::Object(bash));
208    }
209
210    let mut out = serde_json::to_string_pretty(&Value::Object(root)).unwrap_or_default();
211    out.push('\n');
212    out
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    #[test]
220    fn all_commands_have_url() {
221        for doc in all_command_docs() {
222            assert!(!doc.url.is_empty(), "{} has no documentation URL", doc.name);
223            assert!(
224                doc.url.starts_with("https://"),
225                "{} URL must use https: {}",
226                doc.name,
227                doc.url
228            );
229        }
230    }
231
232    #[test]
233    fn builder_two_sections() {
234        let ws = WordSet::new(&["--version", "list", "show"]);
235        assert_eq!(doc(&ws).build(), "- Subcommands: list, show\n- Flags: --version");
236    }
237
238    #[test]
239    fn builder_subcommands_only() {
240        let ws = WordSet::new(&["list", "show"]);
241        assert_eq!(doc(&ws).build(), "- Subcommands: list, show");
242    }
243
244    #[test]
245    fn builder_flags_only() {
246        let ws = WordSet::new(&["--check", "--version"]);
247        assert_eq!(doc(&ws).build(), "- Flags: --check, --version");
248    }
249
250    #[test]
251    fn builder_three_sections() {
252        let ws = WordSet::new(&["--version", "list", "show"]);
253        assert_eq!(
254            doc(&ws).section("Guarded: foo (bar only).").build(),
255            "- Subcommands: list, show\n- Flags: --version\n- Guarded: foo (bar only)."
256        );
257    }
258
259    #[test]
260    fn builder_multi_word_merged() {
261        let ws = WordSet::new(&["--version", "info", "show"]);
262        let multi: &[(&str, WordSet)] =
263            &[("config", WordSet::new(&["get", "list"]))];
264        assert_eq!(
265            doc_multi(&ws, multi).build(),
266            "- Subcommands: config get, config list, info, show\n- Flags: --version"
267        );
268    }
269
270    #[test]
271    fn builder_multi_word_with_extra_section() {
272        let ws = WordSet::new(&["--version", "show"]);
273        let multi: &[(&str, WordSet)] =
274            &[("config", WordSet::new(&["get", "list"]))];
275        assert_eq!(
276            doc_multi(&ws, multi).section("Guarded: foo.").build(),
277            "- Subcommands: config get, config list, show\n- Flags: --version\n- Guarded: foo."
278        );
279    }
280
281    #[test]
282    fn builder_no_flags_with_extra() {
283        let ws = WordSet::new(&["list", "show"]);
284        assert_eq!(
285            doc(&ws).section("Also: foo.").build(),
286            "- Subcommands: list, show\n- Also: foo."
287        );
288    }
289
290    #[test]
291    fn builder_custom_sections_only() {
292        assert_eq!(
293            DocBuilder::new()
294                .section("Read-only: foo.")
295                .section("Always safe: bar.")
296                .section("Guarded: baz.")
297                .build(),
298            "- Read-only: foo.\n- Always safe: bar.\n- Guarded: baz."
299        );
300    }
301
302    #[test]
303    fn builder_triple_word() {
304        let ws = WordSet::new(&["--version", "diff"]);
305        let triples: &[(&str, &str, WordSet)] =
306            &[("git", "remote", WordSet::new(&["list"]))];
307        assert_eq!(
308            doc(&ws).triple_word(triples).build(),
309            "- Subcommands: diff, git remote list\n- Flags: --version"
310        );
311    }
312
313    #[test]
314    fn builder_subcommand_method() {
315        let ws = WordSet::new(&["--version", "list"]);
316        assert_eq!(
317            doc(&ws).subcommand("plugin-list").build(),
318            "- Subcommands: list, plugin-list\n- Flags: --version"
319        );
320    }
321
322    #[test]
323    fn render_opencode_json_valid() {
324        let patterns = vec!["grep".to_string(), "grep *".to_string(), "ls".to_string()];
325        let json = render_opencode_json(&patterns);
326        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
327        let bash = &parsed["permission"]["bash"];
328        assert_eq!(bash["*"], "ask");
329        assert_eq!(bash["grep"], "allow");
330        assert_eq!(bash["grep *"], "allow");
331        assert_eq!(bash["ls"], "allow");
332        assert!(bash["rm"].is_null());
333    }
334
335    #[test]
336    fn render_opencode_json_has_schema() {
337        let json = render_opencode_json(&[]);
338        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
339        assert_eq!(parsed["$schema"], "https://opencode.ai/config.json");
340    }
341
342    #[test]
343    fn render_opencode_json_trailing_newline() {
344        let json = render_opencode_json(&[]);
345        assert!(json.ends_with('\n'));
346    }
347
348    #[test]
349    fn render_opencode_json_merges_existing() {
350        use std::fs;
351        let dir = tempfile::tempdir().expect("tmpdir");
352        let config_path = dir.path().join("opencode.json");
353        fs::write(
354            &config_path,
355            r#"{"$schema":"https://opencode.ai/config.json","model":"claude-sonnet-4-6","permission":{"bash":{"rm *":"deny"}}}"#,
356        )
357        .expect("write");
358
359        let prev = std::env::current_dir().expect("cwd");
360        std::env::set_current_dir(dir.path()).expect("cd");
361        let json = render_opencode_json(&["ls".to_string()]);
362        std::env::set_current_dir(prev).expect("cd back");
363
364        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
365        assert_eq!(parsed["model"], "claude-sonnet-4-6", "existing keys preserved");
366        assert_eq!(parsed["permission"]["bash"]["*"], "ask");
367        assert_eq!(parsed["permission"]["bash"]["ls"], "allow");
368        assert!(
369            parsed["permission"]["bash"]["rm *"].is_null(),
370            "old bash rules replaced, not merged"
371        );
372    }
373
374}