Skip to main content

safe_chains/
docs.rs

1use crate::handlers;
2use crate::parse::WordSet;
3
4pub struct CommandDoc {
5    pub name: &'static str,
6    pub kind: DocKind,
7    pub url: &'static str,
8    pub description: String,
9}
10
11pub enum DocKind {
12    Handler,
13}
14
15impl CommandDoc {
16    pub fn handler(name: &'static str, url: &'static str, description: impl Into<String>) -> Self {
17        let raw = description.into();
18        let description = raw
19            .lines()
20            .map(|line| {
21                if line.is_empty() || line.starts_with("- ") {
22                    line.to_string()
23                } else {
24                    format!("- {line}")
25                }
26            })
27            .collect::<Vec<_>>()
28            .join("\n");
29        Self { name, kind: DocKind::Handler, url, description }
30    }
31
32    pub fn wordset(name: &'static str, url: &'static str, words: &WordSet) -> Self {
33        Self::handler(name, url, doc(words).build())
34    }
35
36    pub fn wordset_multi(name: &'static str, url: &'static str, words: &WordSet, multi: &[(&str, WordSet)]) -> Self {
37        Self::handler(name, url, doc_multi(words, multi).build())
38    }
39
40
41}
42
43#[derive(Default)]
44pub struct DocBuilder {
45    subcommands: Vec<String>,
46    flags: Vec<String>,
47    sections: Vec<String>,
48}
49
50impl DocBuilder {
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    pub fn wordset(mut self, words: &WordSet) -> Self {
56        for item in words.iter() {
57            if item.starts_with('-') {
58                self.flags.push(item.to_string());
59            } else {
60                self.subcommands.push(item.to_string());
61            }
62        }
63        self
64    }
65
66    pub fn multi_word(mut self, multi: &[(&str, WordSet)]) -> Self {
67        for (prefix, actions) in multi {
68            for action in actions.iter() {
69                self.subcommands.push(format!("{prefix} {action}"));
70            }
71        }
72        self
73    }
74
75    pub fn triple_word(mut self, triples: &[(&str, &str, WordSet)]) -> Self {
76        for (a, b, actions) in triples {
77            for action in actions.iter() {
78                self.subcommands.push(format!("{a} {b} {action}"));
79            }
80        }
81        self
82    }
83
84    pub fn subcommand(mut self, name: impl Into<String>) -> Self {
85        self.subcommands.push(name.into());
86        self
87    }
88
89    pub fn section(mut self, text: impl Into<String>) -> Self {
90        let s = text.into();
91        if !s.is_empty() {
92            self.sections.push(s);
93        }
94        self
95    }
96
97    pub fn build(self) -> String {
98        let mut lines = Vec::new();
99        if !self.subcommands.is_empty() {
100            let mut subs = self.subcommands;
101            subs.sort();
102            lines.push(format!("- Subcommands: {}", subs.join(", ")));
103        }
104        if !self.flags.is_empty() {
105            lines.push(format!("- Flags: {}", self.flags.join(", ")));
106        }
107        for s in self.sections {
108            if s.starts_with("- ") {
109                lines.push(s);
110            } else {
111                lines.push(format!("- {s}"));
112            }
113        }
114        lines.join("\n")
115    }
116}
117
118pub fn doc(words: &WordSet) -> DocBuilder {
119    DocBuilder::new().wordset(words)
120}
121
122pub fn doc_multi(words: &WordSet, multi: &[(&str, WordSet)]) -> DocBuilder {
123    DocBuilder::new().wordset(words).multi_word(multi)
124}
125
126pub fn wordset_items(words: &WordSet) -> String {
127    let items: Vec<&str> = words.iter().collect();
128    items.join(", ")
129}
130
131
132pub fn all_command_docs() -> Vec<CommandDoc> {
133    let mut docs = handlers::handler_docs();
134    docs.sort_by_key(|d| d.name);
135    docs
136}
137
138pub fn render_markdown(docs: &[CommandDoc]) -> String {
139    let mut out = String::from(
140        "# Supported Commands\n\
141         \n\
142         Auto-generated by `safe-chains --list-commands`. These commands, subcommands, and flags are read-only and safe to run individually or in combination.\n\
143         \n\
144         Any command with only `--version` or `--help` as its sole argument is always allowed.\n\n",
145    );
146
147    for doc in docs {
148        out.push_str(&format!("### `{}` ({})\n\n{}\n\n", doc.name, doc.url, doc.description));
149    }
150
151    out
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    #[test]
159    fn all_commands_have_url() {
160        for doc in all_command_docs() {
161            assert!(!doc.url.is_empty(), "{} has no documentation URL", doc.name);
162            assert!(
163                doc.url.starts_with("https://"),
164                "{} URL must use https: {}",
165                doc.name,
166                doc.url
167            );
168        }
169    }
170
171    #[test]
172    fn builder_two_sections() {
173        let ws = WordSet::new(&["--version", "list", "show"]);
174        assert_eq!(doc(&ws).build(), "- Subcommands: list, show\n- Flags: --version");
175    }
176
177    #[test]
178    fn builder_subcommands_only() {
179        let ws = WordSet::new(&["list", "show"]);
180        assert_eq!(doc(&ws).build(), "- Subcommands: list, show");
181    }
182
183    #[test]
184    fn builder_flags_only() {
185        let ws = WordSet::new(&["--check", "--version"]);
186        assert_eq!(doc(&ws).build(), "- Flags: --check, --version");
187    }
188
189    #[test]
190    fn builder_three_sections() {
191        let ws = WordSet::new(&["--version", "list", "show"]);
192        assert_eq!(
193            doc(&ws).section("Guarded: foo (bar only).").build(),
194            "- Subcommands: list, show\n- Flags: --version\n- Guarded: foo (bar only)."
195        );
196    }
197
198    #[test]
199    fn builder_multi_word_merged() {
200        let ws = WordSet::new(&["--version", "info", "show"]);
201        let multi: &[(&str, WordSet)] =
202            &[("config", WordSet::new(&["get", "list"]))];
203        assert_eq!(
204            doc_multi(&ws, multi).build(),
205            "- Subcommands: config get, config list, info, show\n- Flags: --version"
206        );
207    }
208
209    #[test]
210    fn builder_multi_word_with_extra_section() {
211        let ws = WordSet::new(&["--version", "show"]);
212        let multi: &[(&str, WordSet)] =
213            &[("config", WordSet::new(&["get", "list"]))];
214        assert_eq!(
215            doc_multi(&ws, multi).section("Guarded: foo.").build(),
216            "- Subcommands: config get, config list, show\n- Flags: --version\n- Guarded: foo."
217        );
218    }
219
220    #[test]
221    fn builder_no_flags_with_extra() {
222        let ws = WordSet::new(&["list", "show"]);
223        assert_eq!(
224            doc(&ws).section("Also: foo.").build(),
225            "- Subcommands: list, show\n- Also: foo."
226        );
227    }
228
229    #[test]
230    fn builder_custom_sections_only() {
231        assert_eq!(
232            DocBuilder::new()
233                .section("Read-only: foo.")
234                .section("Always safe: bar.")
235                .section("Guarded: baz.")
236                .build(),
237            "- Read-only: foo.\n- Always safe: bar.\n- Guarded: baz."
238        );
239    }
240
241    #[test]
242    fn builder_triple_word() {
243        let ws = WordSet::new(&["--version", "diff"]);
244        let triples: &[(&str, &str, WordSet)] =
245            &[("git", "remote", WordSet::new(&["list"]))];
246        assert_eq!(
247            doc(&ws).triple_word(triples).build(),
248            "- Subcommands: diff, git remote list\n- Flags: --version"
249        );
250    }
251
252    #[test]
253    fn builder_subcommand_method() {
254        let ws = WordSet::new(&["--version", "list"]);
255        assert_eq!(
256            doc(&ws).subcommand("plugin-list").build(),
257            "- Subcommands: list, plugin-list\n- Flags: --version"
258        );
259    }
260
261}