Skip to main content

tui/
command.rs

1//! Palette command builders.
2//!
3//! Every leaf parses its `key=value` args through [`parse_args`]. Eval-able
4//! leaves build a nomiscript form string for
5//! [`crate::app::App::submit_console_form`]; reports, account merge, account
6//! balance and transaction list build values the caller resolves and runs.
7//! Leaves that open modals or switch tabs take no args.
8
9use cli_core::CommandError;
10use cli_core::eval::escape_str;
11use cli_core::forms::{FormOption, resolve};
12use forms::{ACCOUNT_MERGE, CONFIG_SET, Field, FormValues, Kind, Source, TRANSACTION_QUERY};
13
14use crate::tabs::reports::ReportKind;
15
16/// A `reports <kind>` palette command: the typed args as form values.
17pub struct ReportRequest {
18    pub kind: ReportKind,
19    /// Choice values resolved to their keys; select values as typed until looked up.
20    pub values: FormValues,
21    /// A bare `reports <kind>` asks for its form, not a run.
22    pub interactive: bool,
23}
24
25/// Whether every field the report requires holds a value.
26#[must_use]
27pub fn report_ready(kind: ReportKind, values: &FormValues) -> bool {
28    kind.descriptor()
29        .fields
30        .iter()
31        .filter(|field| field.required)
32        .all(|field| values.text(field.key).is_some_and(|text| !text.is_empty()))
33}
34
35/// The keys a report accepts as palette args: its single-value fields.
36pub fn report_arg_keys(kind: ReportKind) -> impl Iterator<Item = &'static str> {
37    kind.descriptor()
38        .fields
39        .iter()
40        .filter(|field| takes_arg(field))
41        .map(|field| field.key)
42}
43
44fn takes_arg(field: &Field) -> bool {
45    !matches!(field.kind, Kind::Rows { .. } | Kind::Hidden)
46}
47
48/// Resolve a `reports <kind>` palette command; `Ok(None)` for any other path.
49///
50/// # Errors
51///
52/// Returns an error for a key the report does not take or a choice value that
53/// is not one of its options.
54pub fn build_report_request(
55    path: &[String],
56    args: &[(String, String)],
57) -> Result<Option<ReportRequest>, CommandError> {
58    let kind = match path_key(path).as_str() {
59        "reports balance" => ReportKind::Balance,
60        "reports activity" => ReportKind::Activity,
61        "reports breakdown" => ReportKind::Breakdown,
62        _ => return Ok(None),
63    };
64    let keys: Vec<&str> = report_arg_keys(kind).collect();
65    let mut values = FormValues::default();
66    let given = parse_args(&keys, args)?;
67    for field in kind.descriptor().fields.iter().filter(|f| takes_arg(f)) {
68        let Some(&(key, value)) = given.iter().find(|(key, _)| *key == field.key) else {
69            continue;
70        };
71        match field.kind {
72            Kind::Choice { options, .. } => values.set(key, &resolve_choice(key, options, value)?),
73            _ => values.set(key, value),
74        }
75    }
76    Ok(Some(ReportRequest {
77        kind,
78        values,
79        interactive: args.is_empty(),
80    }))
81}
82
83fn resolve_choice(
84    key: &str,
85    options: &[(&str, &str)],
86    input: &str,
87) -> Result<String, CommandError> {
88    let options: Vec<FormOption> = options
89        .iter()
90        .map(|&(id, label)| FormOption {
91            id: id.to_string(),
92            label: label.to_string(),
93            alias: String::new(),
94            commodity: None,
95        })
96        .collect();
97    resolve(&options, Source::Accounts, key, input)
98}
99
100/// The non-empty `key=value` args, each key allowed and given once. An empty
101/// value means the key is not given.
102///
103/// # Errors
104///
105/// Returns an error for a key outside `allowed` or one given twice.
106pub fn parse_args<'a>(
107    allowed: &[&str],
108    args: &'a [(String, String)],
109) -> Result<Vec<(&'a str, &'a str)>, CommandError> {
110    let mut parsed: Vec<(&str, &str)> = Vec::new();
111    let mut seen: Vec<&str> = Vec::new();
112    for (key, value) in args {
113        if !allowed.contains(&key.as_str()) {
114            return Err(CommandError::Argument(format!("unknown arg: {key}")));
115        }
116        if seen.contains(&key.as_str()) {
117            return Err(CommandError::Argument(format!("duplicate arg: {key}")));
118        }
119        seen.push(key);
120        if !value.is_empty() {
121            parsed.push((key, value));
122        }
123    }
124    Ok(parsed)
125}
126
127fn values_of(parsed: &[(&str, &str)]) -> FormValues {
128    let mut values = FormValues::default();
129    parsed
130        .iter()
131        .for_each(|(key, value)| values.set(key, value));
132    values
133}
134
135fn require<'a>(parsed: &[(&str, &'a str)], key: &str) -> Result<&'a str, CommandError> {
136    parsed
137        .iter()
138        .find(|(k, _)| *k == key)
139        .map(|&(_, value)| value)
140        .ok_or_else(|| CommandError::Argument(format!("missing required arg: {key}")))
141}
142
143/// The args a leaf takes; `None` for the leaves with their own builder.
144fn leaf_arg_keys(leaf: &str) -> Option<Vec<&'static str>> {
145    match leaf {
146        "version" | "account create" | "account edit" | "account list" | "commodity create"
147        | "commodity edit" | "commodity convert" | "commodity list" | "transaction create" => {
148            Some(Vec::new())
149        }
150        "config get" => Some(vec!["key"]),
151        "config set" => Some(CONFIG_SET.fields.iter().map(|field| field.key).collect()),
152        "ssh-key add" => Some(vec!["key"]),
153        "ssh-key list" => Some(Vec::new()),
154        "ssh-key remove" => Some(vec!["fingerprint"]),
155        _ => None,
156    }
157}
158
159/// Attempt to build a nomiscript form for the leaf at `path` given `args`.
160///
161/// Returns `Ok(Some(form))` for eval-able leaves, `Ok(None)` when the
162/// leaf is handled outside the eval path (modal, tab switch or its own
163/// builder), and `Err` for an unknown, repeated or missing arg.
164pub fn build_form(
165    path: &[String],
166    args: &[(String, String)],
167) -> Result<Option<String>, CommandError> {
168    let leaf = path_key(path);
169    let Some(allowed) = leaf_arg_keys(&leaf) else {
170        return Ok(None);
171    };
172    let parsed = parse_args(&allowed, args)?;
173    match leaf.as_str() {
174        "version" => Ok(Some("(get-version)".to_string())),
175        "config get" => Ok(Some(format!(
176            "(get-config {})",
177            escape_str(require(&parsed, "key")?)
178        ))),
179        _ => Ok(None),
180    }
181}
182
183pub const BALANCE_ACCOUNT: &str = "account";
184
185/// The args of `account balance`, resolved like a form's select values.
186pub const BALANCE_ARGS: forms::Form = forms::Form {
187    name: "account-balance",
188    title: "Account balance",
189    fields: &[Field {
190        key: BALANCE_ACCOUNT,
191        label: "Account",
192        kind: Kind::Select {
193            source: Source::Accounts,
194            fills: None,
195            empty: None,
196        },
197        required: true,
198    }],
199    action: forms::Action::Query,
200};
201
202/// The account label or id `account balance` names.
203///
204/// # Errors
205///
206/// Returns an error for an unknown or repeated key, or no `account`.
207pub fn build_account_balance(args: &[(String, String)]) -> Result<String, CommandError> {
208    let parsed = parse_args(&[BALANCE_ACCOUNT], args)?;
209    require(&parsed, BALANCE_ACCOUNT).map(str::to_string)
210}
211
212/// The `account merge` args as form values: `from` and `into`, each at most once.
213///
214/// # Errors
215///
216/// Returns an error for an unknown or repeated key.
217pub fn build_account_merge(args: &[(String, String)]) -> Result<FormValues, CommandError> {
218    let keys: Vec<&str> = ACCOUNT_MERGE.fields.iter().map(|field| field.key).collect();
219    parse_args(&keys, args).map(|parsed| values_of(&parsed))
220}
221
222/// The `transaction list` args as filter values; the accepted keys are the
223/// `transaction-query` descriptor's, paging ones aside.
224///
225/// # Errors
226///
227/// Returns an error for a key that does not filter transactions or is repeated.
228pub fn build_transaction_filter(args: &[(String, String)]) -> Result<FormValues, CommandError> {
229    let keys: Vec<&str> = TRANSACTION_QUERY
230        .filter_fields()
231        .map(|field| field.key)
232        .collect();
233    parse_args(&keys, args).map(|parsed| values_of(&parsed))
234}
235
236/// Flatten `path` into a space-joined key for matching.
237fn path_key(path: &[String]) -> String {
238    path.join(" ")
239}
240
241#[cfg(test)]
242mod tests;