1
use 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]
10
2738
pub fn command_tree() -> Vec<CommandNode> {
11
2738
    vec![
12
2738
        CliVersion::node(),
13
2738
        CommandNode {
14
2738
            name: "transaction".to_string(),
15
2738
            is_leaf: false,
16
2738
            subcommands: vec![CliTransactionList::node(), CliTransactionCreate::node()],
17
2738
        },
18
2738
        CommandNode {
19
2738
            name: "account".to_string(),
20
2738
            is_leaf: false,
21
2738
            subcommands: vec![
22
2738
                CliAccountList::node(),
23
2738
                CliAccountBalance::node(),
24
2738
                CliAccountCreate::node(),
25
2738
                CommandNode {
26
2738
                    name: "merge".to_string(),
27
2738
                    is_leaf: true,
28
2738
                    subcommands: vec![],
29
2738
                },
30
2738
                CommandNode {
31
2738
                    name: "edit".to_string(),
32
2738
                    is_leaf: true,
33
2738
                    subcommands: vec![],
34
2738
                },
35
2738
            ],
36
2738
        },
37
2738
        CommandNode {
38
2738
            name: "commodity".to_string(),
39
2738
            is_leaf: false,
40
2738
            subcommands: vec![
41
2738
                CliCommodityList::node(),
42
2738
                CliCommodityCreate::node(),
43
2738
                CommandNode {
44
2738
                    name: "edit".to_string(),
45
2738
                    is_leaf: true,
46
2738
                    subcommands: vec![],
47
2738
                },
48
2738
                CommandNode {
49
2738
                    name: "convert".to_string(),
50
2738
                    is_leaf: true,
51
2738
                    subcommands: vec![],
52
2738
                },
53
2738
            ],
54
2738
        },
55
2738
        CommandNode {
56
2738
            name: "config".to_string(),
57
2738
            is_leaf: false,
58
2738
            subcommands: vec![CliGetConfig::node(), CliSetConfig::node()],
59
2738
        },
60
2738
        CommandNode {
61
2738
            name: "reports".to_string(),
62
2738
            is_leaf: false,
63
2738
            subcommands: vec![
64
2738
                CommandNode {
65
2738
                    name: "balance".to_string(),
66
2738
                    is_leaf: true,
67
2738
                    subcommands: vec![],
68
2738
                },
69
2738
                CommandNode {
70
2738
                    name: "activity".to_string(),
71
2738
                    is_leaf: true,
72
2738
                    subcommands: vec![],
73
2738
                },
74
2738
                CommandNode {
75
2738
                    name: "breakdown".to_string(),
76
2738
                    is_leaf: true,
77
2738
                    subcommands: vec![],
78
2738
                },
79
2738
            ],
80
2738
        },
81
2738
        CommandNode {
82
2738
            name: "ssh-key".to_string(),
83
2738
            is_leaf: false,
84
2738
            subcommands: vec![
85
2738
                CommandNode {
86
2738
                    name: "add".to_string(),
87
2738
                    is_leaf: true,
88
2738
                    subcommands: vec![],
89
2738
                },
90
2738
                CommandNode {
91
2738
                    name: "list".to_string(),
92
2738
                    is_leaf: true,
93
2738
                    subcommands: vec![],
94
2738
                },
95
2738
                CliSshKeyRemove::node(),
96
2738
            ],
97
2738
        },
98
    ]
99
2738
}
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]
105
3588
pub fn find_leaf<'a>(tree: &'a [CommandNode], path: &[&str]) -> Option<&'a CommandNode> {
106
3588
    let (head, rest) = path.split_first()?;
107
11588
    let node = tree.iter().find(|n| n.name == *head)?;
108
3488
    if rest.is_empty() {
109
1792
        node.is_leaf.then_some(node)
110
    } else {
111
1696
        find_leaf(&node.subcommands, rest)
112
    }
113
3588
}
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]
122
91
pub fn complete(tree: &[CommandNode], input: &str) -> Vec<String> {
123
91
    let trailing = input.ends_with(' ');
124
91
    let tokens: Vec<&str> = input.split_whitespace().collect();
125
91
    let (parent_path, prefix): (&[&str], &str) = if trailing {
126
38
        (tokens.as_slice(), "")
127
    } else {
128
53
        match tokens.split_last() {
129
91
            None => return tree.iter().map(|n| n.name.clone()).collect(),
130
40
            Some((last, parents)) => (parents, *last),
131
        }
132
    };
133
78
    descend(tree, parent_path)
134
78
        .iter()
135
459
        .filter(|n| n.name.starts_with(prefix))
136
224
        .map(|n| n.name.clone())
137
        .collect()
138
91
}
139

            
140
120
fn descend<'a>(tree: &'a [CommandNode], path: &[&str]) -> &'a [CommandNode] {
141
120
    match path.split_first() {
142
78
        None => tree,
143
124
        Some((head, rest)) => match tree.iter().find(|n| n.name == *head) {
144
            None => &[],
145
42
            Some(node) => descend(&node.subcommands, rest),
146
        },
147
    }
148
120
}
149

            
150
#[cfg(test)]
151
mod tests {
152
    use super::*;
153

            
154
27
    fn all_leaf_paths<'a>(
155
27
        tree: &'a [CommandNode],
156
27
        prefix: &[&'a str],
157
27
        out: &mut Vec<Vec<&'a str>>,
158
27
    ) {
159
27
        for node in tree {
160
26
            let mut here: Vec<&'a str> = prefix.to_vec();
161
26
            here.push(node.name.as_str());
162
26
            if node.is_leaf {
163
20
                out.push(here.clone());
164
6
            }
165
26
            all_leaf_paths(&node.subcommands, &here, out);
166
        }
167
27
    }
168

            
169
    #[test]
170
1
    fn tree_exposes_expected_top_level_groups() {
171
1
        let tree = command_tree();
172
7
        let names: Vec<&str> = tree.iter().map(|n| n.name.as_str()).collect();
173
1
        assert!(names.contains(&"version"));
174
1
        assert!(names.contains(&"transaction"));
175
1
        assert!(names.contains(&"account"));
176
1
        assert!(names.contains(&"commodity"));
177
1
        assert!(names.contains(&"config"));
178
1
        assert!(names.contains(&"ssh-key"));
179
1
        assert!(!names.contains(&"sql"));
180
1
        assert!(names.contains(&"reports"));
181
1
    }
182

            
183
    #[test]
184
1
    fn every_leaf_resolves_via_find_leaf() {
185
1
        let tree = command_tree();
186
1
        let mut leaves = Vec::new();
187
1
        all_leaf_paths(&tree, &[], &mut leaves);
188
1
        assert!(!leaves.is_empty());
189
1
        for path in leaves {
190
20
            let found = find_leaf(&tree, &path);
191
20
            assert!(
192
20
                found.is_some(),
193
                "leaf {path:?} should be resolvable via find_leaf"
194
            );
195
20
            assert!(found.unwrap().is_leaf);
196
        }
197
1
    }
198

            
199
    #[test]
200
1
    fn find_leaf_returns_none_for_unknown_path() {
201
1
        let tree = command_tree();
202
1
        assert!(find_leaf(&tree, &["does-not-exist"]).is_none());
203
1
        assert!(find_leaf(&tree, &["reports", "nonsense"]).is_none());
204
1
    }
205

            
206
    #[test]
207
1
    fn find_leaf_returns_none_for_group_without_command() {
208
1
        let tree = command_tree();
209
1
        assert!(find_leaf(&tree, &["reports"]).is_none());
210
1
        assert!(find_leaf(&tree, &["account"]).is_none());
211
1
    }
212

            
213
    #[test]
214
1
    fn reports_leaves_are_present() {
215
1
        let tree = command_tree();
216
1
        assert!(find_leaf(&tree, &["reports", "balance"]).is_some());
217
1
        assert!(find_leaf(&tree, &["reports", "activity"]).is_some());
218
1
        assert!(find_leaf(&tree, &["reports", "breakdown"]).is_some());
219
1
    }
220

            
221
    #[test]
222
1
    fn edit_leaves_present_and_tag_leaves_gone() {
223
1
        let tree = command_tree();
224
1
        assert!(find_leaf(&tree, &["account", "edit"]).is_some());
225
1
        assert!(find_leaf(&tree, &["commodity", "edit"]).is_some());
226
1
        assert!(find_leaf(&tree, &["account", "tag"]).is_none());
227
1
        assert!(find_leaf(&tree, &["transaction", "tag"]).is_none());
228
1
    }
229

            
230
    #[test]
231
1
    fn commodity_convert_leaf_is_present() {
232
1
        let tree = command_tree();
233
1
        assert!(find_leaf(&tree, &["commodity", "convert"]).is_some());
234
1
    }
235

            
236
    #[test]
237
1
    fn complete_empty_returns_all_top_level() {
238
1
        let tree = command_tree();
239
1
        let cands = complete(&tree, "");
240
1
        assert!(cands.contains(&"account".to_string()));
241
1
        assert!(cands.contains(&"transaction".to_string()));
242
1
        assert!(cands.contains(&"version".to_string()));
243
1
    }
244

            
245
    #[test]
246
1
    fn complete_prefix_filters_top_level() {
247
1
        let tree = command_tree();
248
1
        let cands = complete(&tree, "acc");
249
1
        assert_eq!(cands, vec!["account".to_string()]);
250
1
    }
251

            
252
    #[test]
253
1
    fn complete_trailing_space_lists_children() {
254
1
        let tree = command_tree();
255
1
        let cands = complete(&tree, "account ");
256
1
        assert!(cands.contains(&"create".to_string()));
257
1
        assert!(cands.contains(&"list".to_string()));
258
1
        assert!(cands.contains(&"edit".to_string()));
259
1
        assert!(!cands.contains(&"account".to_string()));
260
1
    }
261

            
262
    #[test]
263
1
    fn complete_partial_child_filters() {
264
1
        let tree = command_tree();
265
1
        let cands = complete(&tree, "account c");
266
1
        assert_eq!(cands, vec!["create".to_string()]);
267
1
    }
268

            
269
    #[test]
270
1
    fn complete_no_match_returns_empty() {
271
1
        let tree = command_tree();
272
1
        let cands = complete(&tree, "account xyz");
273
1
        assert!(cands.is_empty());
274
1
    }
275

            
276
    #[test]
277
1
    fn complete_exact_leaf_without_space_returns_itself() {
278
1
        let tree = command_tree();
279
1
        let cands = complete(&tree, "account list");
280
1
        assert_eq!(cands, vec!["list".to_string()]);
281
1
    }
282

            
283
    #[test]
284
1
    fn complete_exact_leaf_with_trailing_space_returns_empty() {
285
1
        let tree = command_tree();
286
1
        let cands = complete(&tree, "account list ");
287
1
        assert!(cands.is_empty());
288
1
    }
289
}