Skip to main content

cli_core/
tree.rs

1use crate::commands::{
2    CliAccountBalance, CliAccountCreate, CliAccountList, CliCommand, CliCommodityCreate,
3    CliCommodityList, CliGetConfig, CliSetConfig, CliSshKeyRemove, CliTransactionCreate,
4    CliTransactionList, CliVersion, CommandNode,
5};
6
7/// Command tree of the TUI command palette. The automation CLI parses its
8/// own grammar with clap and does not use this tree.
9#[must_use]
10pub fn command_tree() -> Vec<CommandNode> {
11    vec![
12        CliVersion::node(),
13        CommandNode {
14            name: "transaction".to_string(),
15            is_leaf: false,
16            subcommands: vec![CliTransactionList::node(), CliTransactionCreate::node()],
17        },
18        CommandNode {
19            name: "account".to_string(),
20            is_leaf: false,
21            subcommands: vec![
22                CliAccountList::node(),
23                CliAccountBalance::node(),
24                CliAccountCreate::node(),
25                CommandNode {
26                    name: "merge".to_string(),
27                    is_leaf: true,
28                    subcommands: vec![],
29                },
30                CommandNode {
31                    name: "edit".to_string(),
32                    is_leaf: true,
33                    subcommands: vec![],
34                },
35            ],
36        },
37        CommandNode {
38            name: "commodity".to_string(),
39            is_leaf: false,
40            subcommands: vec![
41                CliCommodityList::node(),
42                CliCommodityCreate::node(),
43                CommandNode {
44                    name: "edit".to_string(),
45                    is_leaf: true,
46                    subcommands: vec![],
47                },
48                CommandNode {
49                    name: "convert".to_string(),
50                    is_leaf: true,
51                    subcommands: vec![],
52                },
53            ],
54        },
55        CommandNode {
56            name: "config".to_string(),
57            is_leaf: false,
58            subcommands: vec![CliGetConfig::node(), CliSetConfig::node()],
59        },
60        CommandNode {
61            name: "reports".to_string(),
62            is_leaf: false,
63            subcommands: vec![
64                CommandNode {
65                    name: "balance".to_string(),
66                    is_leaf: true,
67                    subcommands: vec![],
68                },
69                CommandNode {
70                    name: "activity".to_string(),
71                    is_leaf: true,
72                    subcommands: vec![],
73                },
74                CommandNode {
75                    name: "breakdown".to_string(),
76                    is_leaf: true,
77                    subcommands: vec![],
78                },
79            ],
80        },
81        CommandNode {
82            name: "ssh-key".to_string(),
83            is_leaf: false,
84            subcommands: vec![
85                CommandNode {
86                    name: "add".to_string(),
87                    is_leaf: true,
88                    subcommands: vec![],
89                },
90                CommandNode {
91                    name: "list".to_string(),
92                    is_leaf: true,
93                    subcommands: vec![],
94                },
95                CliSshKeyRemove::node(),
96            ],
97        },
98    ]
99}
100
101/// Walk a command path (`["reports", "balance"]`) down the tree and return
102/// the matching leaf. Returns `None` when any segment is unknown or when
103/// the path does not terminate at a leaf command.
104#[must_use]
105pub fn find_leaf<'a>(tree: &'a [CommandNode], path: &[&str]) -> Option<&'a CommandNode> {
106    let (head, rest) = path.split_first()?;
107    let node = tree.iter().find(|n| n.name == *head)?;
108    if rest.is_empty() {
109        node.is_leaf.then_some(node)
110    } else {
111        find_leaf(&node.subcommands, rest)
112    }
113}
114
115/// Return candidate next-tokens for `input` against `tree`.
116///
117/// If `input` ends with a space the last segment is considered complete
118/// and candidates are the children of the resolved parent. Otherwise the
119/// last whitespace-delimited token is treated as a prefix and only
120/// children whose names start with it are returned.
121#[must_use]
122pub fn complete(tree: &[CommandNode], input: &str) -> Vec<String> {
123    let trailing = input.ends_with(' ');
124    let tokens: Vec<&str> = input.split_whitespace().collect();
125    let (parent_path, prefix): (&[&str], &str) = if trailing {
126        (tokens.as_slice(), "")
127    } else {
128        match tokens.split_last() {
129            None => return tree.iter().map(|n| n.name.clone()).collect(),
130            Some((last, parents)) => (parents, *last),
131        }
132    };
133    descend(tree, parent_path)
134        .iter()
135        .filter(|n| n.name.starts_with(prefix))
136        .map(|n| n.name.clone())
137        .collect()
138}
139
140fn descend<'a>(tree: &'a [CommandNode], path: &[&str]) -> &'a [CommandNode] {
141    match path.split_first() {
142        None => tree,
143        Some((head, rest)) => match tree.iter().find(|n| n.name == *head) {
144            None => &[],
145            Some(node) => descend(&node.subcommands, rest),
146        },
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn all_leaf_paths<'a>(
155        tree: &'a [CommandNode],
156        prefix: &[&'a str],
157        out: &mut Vec<Vec<&'a str>>,
158    ) {
159        for node in tree {
160            let mut here: Vec<&'a str> = prefix.to_vec();
161            here.push(node.name.as_str());
162            if node.is_leaf {
163                out.push(here.clone());
164            }
165            all_leaf_paths(&node.subcommands, &here, out);
166        }
167    }
168
169    #[test]
170    fn tree_exposes_expected_top_level_groups() {
171        let tree = command_tree();
172        let names: Vec<&str> = tree.iter().map(|n| n.name.as_str()).collect();
173        assert!(names.contains(&"version"));
174        assert!(names.contains(&"transaction"));
175        assert!(names.contains(&"account"));
176        assert!(names.contains(&"commodity"));
177        assert!(names.contains(&"config"));
178        assert!(names.contains(&"ssh-key"));
179        assert!(!names.contains(&"sql"));
180        assert!(names.contains(&"reports"));
181    }
182
183    #[test]
184    fn every_leaf_resolves_via_find_leaf() {
185        let tree = command_tree();
186        let mut leaves = Vec::new();
187        all_leaf_paths(&tree, &[], &mut leaves);
188        assert!(!leaves.is_empty());
189        for path in leaves {
190            let found = find_leaf(&tree, &path);
191            assert!(
192                found.is_some(),
193                "leaf {path:?} should be resolvable via find_leaf"
194            );
195            assert!(found.unwrap().is_leaf);
196        }
197    }
198
199    #[test]
200    fn find_leaf_returns_none_for_unknown_path() {
201        let tree = command_tree();
202        assert!(find_leaf(&tree, &["does-not-exist"]).is_none());
203        assert!(find_leaf(&tree, &["reports", "nonsense"]).is_none());
204    }
205
206    #[test]
207    fn find_leaf_returns_none_for_group_without_command() {
208        let tree = command_tree();
209        assert!(find_leaf(&tree, &["reports"]).is_none());
210        assert!(find_leaf(&tree, &["account"]).is_none());
211    }
212
213    #[test]
214    fn reports_leaves_are_present() {
215        let tree = command_tree();
216        assert!(find_leaf(&tree, &["reports", "balance"]).is_some());
217        assert!(find_leaf(&tree, &["reports", "activity"]).is_some());
218        assert!(find_leaf(&tree, &["reports", "breakdown"]).is_some());
219    }
220
221    #[test]
222    fn edit_leaves_present_and_tag_leaves_gone() {
223        let tree = command_tree();
224        assert!(find_leaf(&tree, &["account", "edit"]).is_some());
225        assert!(find_leaf(&tree, &["commodity", "edit"]).is_some());
226        assert!(find_leaf(&tree, &["account", "tag"]).is_none());
227        assert!(find_leaf(&tree, &["transaction", "tag"]).is_none());
228    }
229
230    #[test]
231    fn commodity_convert_leaf_is_present() {
232        let tree = command_tree();
233        assert!(find_leaf(&tree, &["commodity", "convert"]).is_some());
234    }
235
236    #[test]
237    fn complete_empty_returns_all_top_level() {
238        let tree = command_tree();
239        let cands = complete(&tree, "");
240        assert!(cands.contains(&"account".to_string()));
241        assert!(cands.contains(&"transaction".to_string()));
242        assert!(cands.contains(&"version".to_string()));
243    }
244
245    #[test]
246    fn complete_prefix_filters_top_level() {
247        let tree = command_tree();
248        let cands = complete(&tree, "acc");
249        assert_eq!(cands, vec!["account".to_string()]);
250    }
251
252    #[test]
253    fn complete_trailing_space_lists_children() {
254        let tree = command_tree();
255        let cands = complete(&tree, "account ");
256        assert!(cands.contains(&"create".to_string()));
257        assert!(cands.contains(&"list".to_string()));
258        assert!(cands.contains(&"edit".to_string()));
259        assert!(!cands.contains(&"account".to_string()));
260    }
261
262    #[test]
263    fn complete_partial_child_filters() {
264        let tree = command_tree();
265        let cands = complete(&tree, "account c");
266        assert_eq!(cands, vec!["create".to_string()]);
267    }
268
269    #[test]
270    fn complete_no_match_returns_empty() {
271        let tree = command_tree();
272        let cands = complete(&tree, "account xyz");
273        assert!(cands.is_empty());
274    }
275
276    #[test]
277    fn complete_exact_leaf_without_space_returns_itself() {
278        let tree = command_tree();
279        let cands = complete(&tree, "account list");
280        assert_eq!(cands, vec!["list".to_string()]);
281    }
282
283    #[test]
284    fn complete_exact_leaf_with_trailing_space_returns_empty() {
285        let tree = command_tree();
286        let cands = complete(&tree, "account list ");
287        assert!(cands.is_empty());
288    }
289}