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 read-only and safe to run individually or in combination.\n\n",
144    );
145
146    for doc in docs {
147        if doc.aliases.is_empty() {
148            out.push_str(&format!("### `{}` ({})\n\n", doc.name, doc.url));
149        } else {
150            let alias_str: Vec<String> = doc.aliases.iter().map(|a| format!("`{a}`")).collect();
151            out.push_str(&format!(
152                "### `{}` ({})\n\nAliases: {}\n\n",
153                doc.name, doc.url, alias_str.join(", ")
154            ));
155        }
156        out.push_str(&format!("{}\n\n", doc.description));
157    }
158
159    out
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn all_commands_have_url() {
168        for doc in all_command_docs() {
169            assert!(!doc.url.is_empty(), "{} has no documentation URL", doc.name);
170            assert!(
171                doc.url.starts_with("https://"),
172                "{} URL must use https: {}",
173                doc.name,
174                doc.url
175            );
176        }
177    }
178
179    #[test]
180    fn builder_two_sections() {
181        let ws = WordSet::new(&["--version", "list", "show"]);
182        assert_eq!(doc(&ws).build(), "- Subcommands: list, show\n- Flags: --version");
183    }
184
185    #[test]
186    fn builder_subcommands_only() {
187        let ws = WordSet::new(&["list", "show"]);
188        assert_eq!(doc(&ws).build(), "- Subcommands: list, show");
189    }
190
191    #[test]
192    fn builder_flags_only() {
193        let ws = WordSet::new(&["--check", "--version"]);
194        assert_eq!(doc(&ws).build(), "- Flags: --check, --version");
195    }
196
197    #[test]
198    fn builder_three_sections() {
199        let ws = WordSet::new(&["--version", "list", "show"]);
200        assert_eq!(
201            doc(&ws).section("Guarded: foo (bar only).").build(),
202            "- Subcommands: list, show\n- Flags: --version\n- Guarded: foo (bar only)."
203        );
204    }
205
206    #[test]
207    fn builder_multi_word_merged() {
208        let ws = WordSet::new(&["--version", "info", "show"]);
209        let multi: &[(&str, WordSet)] =
210            &[("config", WordSet::new(&["get", "list"]))];
211        assert_eq!(
212            doc_multi(&ws, multi).build(),
213            "- Subcommands: config get, config list, info, show\n- Flags: --version"
214        );
215    }
216
217    #[test]
218    fn builder_multi_word_with_extra_section() {
219        let ws = WordSet::new(&["--version", "show"]);
220        let multi: &[(&str, WordSet)] =
221            &[("config", WordSet::new(&["get", "list"]))];
222        assert_eq!(
223            doc_multi(&ws, multi).section("Guarded: foo.").build(),
224            "- Subcommands: config get, config list, show\n- Flags: --version\n- Guarded: foo."
225        );
226    }
227
228    #[test]
229    fn builder_no_flags_with_extra() {
230        let ws = WordSet::new(&["list", "show"]);
231        assert_eq!(
232            doc(&ws).section("Also: foo.").build(),
233            "- Subcommands: list, show\n- Also: foo."
234        );
235    }
236
237    #[test]
238    fn builder_custom_sections_only() {
239        assert_eq!(
240            DocBuilder::new()
241                .section("Read-only: foo.")
242                .section("Always safe: bar.")
243                .section("Guarded: baz.")
244                .build(),
245            "- Read-only: foo.\n- Always safe: bar.\n- Guarded: baz."
246        );
247    }
248
249    #[test]
250    fn builder_triple_word() {
251        let ws = WordSet::new(&["--version", "diff"]);
252        let triples: &[(&str, &str, WordSet)] =
253            &[("git", "remote", WordSet::new(&["list"]))];
254        assert_eq!(
255            doc(&ws).triple_word(triples).build(),
256            "- Subcommands: diff, git remote list\n- Flags: --version"
257        );
258    }
259
260    #[test]
261    fn builder_subcommand_method() {
262        let ws = WordSet::new(&["--version", "list"]);
263        assert_eq!(
264            doc(&ws).subcommand("plugin-list").build(),
265            "- Subcommands: list, plugin-list\n- Flags: --version"
266        );
267    }
268
269}