1
//! `:`-driven command palette. Parses a typed command string into
2
//! (path, args), looks the path up in the shared [`cli_core`] command
3
//! tree, and returns the runnable leaf the event layer should execute.
4
//!
5
//! Grammar (matches the TUI's prior single-pane mode so automation and
6
//! interactive grammar agree):
7
//!
8
//! ```text
9
//! word (word)* (key=value)*
10
//! ```
11
//!
12
//! `word` tokens identify the path (e.g. `reports balance`). `key=value`
13
//! tokens become arguments. Values with embedded spaces are not
14
//! currently supported — this matches the existing CLI grammar.
15

            
16
use cli_core::{CommandNode, command_tree, find_leaf};
17

            
18
/// One line per command of the tree: `account create|list|…`.
19
#[must_use]
20
62
pub fn command_lines() -> Vec<String> {
21
434
    let line = |node: &CommandNode| match node.subcommands.is_empty() {
22
62
        true => format!("  {}", node.name),
23
        false => {
24
372
            let subs: Vec<&str> = node
25
372
                .subcommands
26
372
                .iter()
27
1178
                .map(|sub| sub.name.as_str())
28
                .collect();
29
372
            format!("  {} {}", node.name, subs.join("|"))
30
        }
31
434
    };
32
62
    command_tree().iter().map(line).collect()
33
62
}
34

            
35
#[derive(Debug, PartialEq, Eq)]
36
pub struct PaletteQuery {
37
    pub path: Vec<String>,
38
    pub args: Vec<(String, String)>,
39
}
40

            
41
/// Parse `input` into (path, args). Empty input yields an empty query.
42
#[must_use]
43
163
pub fn parse(input: &str) -> PaletteQuery {
44
163
    let mut path = Vec::new();
45
163
    let mut args = Vec::new();
46
163
    for token in input.split_whitespace() {
47
434
        if let Some((k, v)) = token.split_once('=') {
48
126
            args.push((k.to_string(), v.to_string()));
49
        } else {
50
308
            path.push(token.to_string());
51
        }
52
    }
53
163
    PaletteQuery { path, args }
54
163
}
55

            
56
/// Resolve a parsed query against the command tree. Returns the leaf
57
/// node's name and its argument list if the path is complete, or
58
/// `None` when the path refers to a group without a runnable command.
59
#[must_use]
60
159
pub fn resolve<'a>(tree: &'a [CommandNode], query: &PaletteQuery) -> Option<&'a CommandNode> {
61
159
    let path_refs: Vec<&str> = query.path.iter().map(String::as_str).collect();
62
159
    find_leaf(tree, &path_refs)
63
159
}
64

            
65
/// Return the longest string that is a common prefix of all `candidates`.
66
/// Returns an empty string when `candidates` is empty or contains no common prefix.
67
#[must_use]
68
12
pub fn longest_common_prefix(candidates: &[String]) -> String {
69
12
    match candidates {
70
2
        [] => String::new(),
71
2
        [one] => one.clone(),
72
        [first, rest @ ..] => {
73
22
            let len = rest.iter().fold(first.len(), |n, s| {
74
22
                first
75
22
                    .bytes()
76
22
                    .zip(s.bytes())
77
28
                    .take_while(|(a, b)| a == b)
78
                    .count()
79
22
                    .min(n)
80
22
            });
81
8
            first[..len].to_string()
82
        }
83
    }
84
12
}
85

            
86
#[cfg(test)]
87
mod tests {
88
    use super::*;
89
    use cli_core::command_tree;
90

            
91
    #[test]
92
1
    fn parses_empty_input_to_empty_query() {
93
1
        let q = parse("");
94
1
        assert!(q.path.is_empty());
95
1
        assert!(q.args.is_empty());
96
1
    }
97

            
98
    #[test]
99
1
    fn parses_single_word_path() {
100
1
        let q = parse("version");
101
1
        assert_eq!(q.path, vec!["version"]);
102
1
        assert!(q.args.is_empty());
103
1
    }
104

            
105
    #[test]
106
1
    fn parses_nested_path() {
107
1
        let q = parse("reports balance");
108
1
        assert_eq!(q.path, vec!["reports", "balance"]);
109
1
    }
110

            
111
    #[test]
112
1
    fn parses_key_value_arguments() {
113
1
        let q = parse("reports balance from=2026-01-01 to=2026-04-30 tag=food");
114
1
        assert_eq!(q.path, vec!["reports", "balance"]);
115
1
        assert_eq!(q.args.len(), 3);
116
1
        assert_eq!(q.args[0], ("from".to_string(), "2026-01-01".to_string()));
117
1
        assert_eq!(q.args[2], ("tag".to_string(), "food".to_string()));
118
1
    }
119

            
120
    #[test]
121
1
    fn command_lines_name_each_top_level_command_with_its_subcommands() {
122
1
        let lines = command_lines();
123
1
        assert_eq!(lines.len(), command_tree().len());
124
1
        assert!(lines.contains(&"  version".to_string()));
125
1
        assert!(lines.contains(&"  reports balance|activity|breakdown".to_string()));
126
1
    }
127

            
128
    #[test]
129
1
    fn resolves_version_leaf() {
130
1
        let tree = command_tree();
131
1
        let q = parse("version");
132
1
        let leaf = resolve(&tree, &q).expect("version resolves");
133
1
        assert_eq!(leaf.name, "version");
134
1
        assert!(leaf.is_leaf);
135
1
    }
136

            
137
    #[test]
138
1
    fn resolves_reports_balance_leaf() {
139
1
        let tree = command_tree();
140
1
        let q = parse("reports balance from=2026-01-01");
141
1
        let leaf = resolve(&tree, &q).expect("reports balance resolves");
142
1
        assert_eq!(leaf.name, "balance");
143
1
        assert!(leaf.is_leaf);
144
1
    }
145

            
146
    #[test]
147
1
    fn rejects_unknown_path() {
148
1
        let tree = command_tree();
149
1
        let q = parse("nope");
150
1
        assert!(resolve(&tree, &q).is_none());
151
1
    }
152

            
153
    #[test]
154
1
    fn rejects_group_without_command() {
155
1
        let tree = command_tree();
156
1
        let q = parse("reports");
157
1
        assert!(resolve(&tree, &q).is_none());
158
1
    }
159

            
160
    #[test]
161
1
    fn lcp_empty_candidates_returns_empty() {
162
1
        assert_eq!(longest_common_prefix(&[]), "");
163
1
    }
164

            
165
    #[test]
166
1
    fn lcp_single_candidate_returns_it() {
167
1
        assert_eq!(longest_common_prefix(&["account".to_string()]), "account");
168
1
    }
169

            
170
    #[test]
171
1
    fn lcp_shared_prefix() {
172
1
        let cands = vec!["create".to_string(), "commodity".to_string()];
173
1
        assert_eq!(longest_common_prefix(&cands), "c");
174
1
    }
175

            
176
    #[test]
177
1
    fn lcp_no_shared_prefix() {
178
1
        let cands = vec!["account".to_string(), "transaction".to_string()];
179
1
        assert_eq!(longest_common_prefix(&cands), "");
180
1
    }
181

            
182
    #[test]
183
1
    fn lcp_identical_candidates() {
184
1
        let cands = vec!["list".to_string(), "list".to_string()];
185
1
        assert_eq!(longest_common_prefix(&cands), "list");
186
1
    }
187
}