Lines
100 %
Functions
68.33 %
Branches
//! Palette command builders.
//!
//! Every leaf parses its `key=value` args through [`parse_args`]. Eval-able
//! leaves build a nomiscript form string for
//! [`crate::app::App::submit_console_form`]; reports, account merge, account
//! balance and transaction list build values the caller resolves and runs.
//! Leaves that open modals or switch tabs take no args.
use cli_core::CommandError;
use cli_core::eval::escape_str;
use cli_core::forms::{FormOption, resolve};
use forms::{ACCOUNT_MERGE, CONFIG_SET, Field, FormValues, Kind, Source, TRANSACTION_QUERY};
use crate::tabs::reports::ReportKind;
/// A `reports <kind>` palette command: the typed args as form values.
pub struct ReportRequest {
pub kind: ReportKind,
/// Choice values resolved to their keys; select values as typed until looked up.
pub values: FormValues,
/// A bare `reports <kind>` asks for its form, not a run.
pub interactive: bool,
}
/// Whether every field the report requires holds a value.
#[must_use]
pub fn report_ready(kind: ReportKind, values: &FormValues) -> bool {
kind.descriptor()
.fields
.iter()
.filter(|field| field.required)
.all(|field| values.text(field.key).is_some_and(|text| !text.is_empty()))
/// The keys a report accepts as palette args: its single-value fields.
pub fn report_arg_keys(kind: ReportKind) -> impl Iterator<Item = &'static str> {
.filter(|field| takes_arg(field))
.map(|field| field.key)
fn takes_arg(field: &Field) -> bool {
!matches!(field.kind, Kind::Rows { .. } | Kind::Hidden)
/// Resolve a `reports <kind>` palette command; `Ok(None)` for any other path.
///
/// # Errors
/// Returns an error for a key the report does not take or a choice value that
/// is not one of its options.
pub fn build_report_request(
path: &[String],
args: &[(String, String)],
) -> Result<Option<ReportRequest>, CommandError> {
let kind = match path_key(path).as_str() {
"reports balance" => ReportKind::Balance,
"reports activity" => ReportKind::Activity,
"reports breakdown" => ReportKind::Breakdown,
_ => return Ok(None),
};
let keys: Vec<&str> = report_arg_keys(kind).collect();
let mut values = FormValues::default();
let given = parse_args(&keys, args)?;
for field in kind.descriptor().fields.iter().filter(|f| takes_arg(f)) {
let Some(&(key, value)) = given.iter().find(|(key, _)| *key == field.key) else {
continue;
match field.kind {
Kind::Choice { options, .. } => values.set(key, &resolve_choice(key, options, value)?),
_ => values.set(key, value),
Ok(Some(ReportRequest {
kind,
values,
interactive: args.is_empty(),
}))
fn resolve_choice(
key: &str,
options: &[(&str, &str)],
input: &str,
) -> Result<String, CommandError> {
let options: Vec<FormOption> = options
.map(|&(id, label)| FormOption {
id: id.to_string(),
label: label.to_string(),
alias: String::new(),
commodity: None,
})
.collect();
resolve(&options, Source::Accounts, key, input)
/// The non-empty `key=value` args, each key allowed and given once. An empty
/// value means the key is not given.
/// Returns an error for a key outside `allowed` or one given twice.
pub fn parse_args<'a>(
allowed: &[&str],
args: &'a [(String, String)],
) -> Result<Vec<(&'a str, &'a str)>, CommandError> {
let mut parsed: Vec<(&str, &str)> = Vec::new();
let mut seen: Vec<&str> = Vec::new();
for (key, value) in args {
if !allowed.contains(&key.as_str()) {
return Err(CommandError::Argument(format!("unknown arg: {key}")));
if seen.contains(&key.as_str()) {
return Err(CommandError::Argument(format!("duplicate arg: {key}")));
seen.push(key);
if !value.is_empty() {
parsed.push((key, value));
Ok(parsed)
fn values_of(parsed: &[(&str, &str)]) -> FormValues {
parsed
.for_each(|(key, value)| values.set(key, value));
values
fn require<'a>(parsed: &[(&str, &'a str)], key: &str) -> Result<&'a str, CommandError> {
.find(|(k, _)| *k == key)
.map(|&(_, value)| value)
.ok_or_else(|| CommandError::Argument(format!("missing required arg: {key}")))
/// The args a leaf takes; `None` for the leaves with their own builder.
fn leaf_arg_keys(leaf: &str) -> Option<Vec<&'static str>> {
match leaf {
"version" | "account create" | "account edit" | "account list" | "commodity create"
| "commodity edit" | "commodity convert" | "commodity list" | "transaction create" => {
Some(Vec::new())
"config get" => Some(vec!["key"]),
"config set" => Some(CONFIG_SET.fields.iter().map(|field| field.key).collect()),
"ssh-key add" => Some(vec!["key"]),
"ssh-key list" => Some(Vec::new()),
"ssh-key remove" => Some(vec!["fingerprint"]),
_ => None,
/// Attempt to build a nomiscript form for the leaf at `path` given `args`.
/// Returns `Ok(Some(form))` for eval-able leaves, `Ok(None)` when the
/// leaf is handled outside the eval path (modal, tab switch or its own
/// builder), and `Err` for an unknown, repeated or missing arg.
pub fn build_form(
) -> Result<Option<String>, CommandError> {
let leaf = path_key(path);
let Some(allowed) = leaf_arg_keys(&leaf) else {
return Ok(None);
let parsed = parse_args(&allowed, args)?;
match leaf.as_str() {
"version" => Ok(Some("(get-version)".to_string())),
"config get" => Ok(Some(format!(
"(get-config {})",
escape_str(require(&parsed, "key")?)
))),
_ => Ok(None),
pub const BALANCE_ACCOUNT: &str = "account";
/// The args of `account balance`, resolved like a form's select values.
pub const BALANCE_ARGS: forms::Form = forms::Form {
name: "account-balance",
title: "Account balance",
fields: &[Field {
key: BALANCE_ACCOUNT,
label: "Account",
kind: Kind::Select {
source: Source::Accounts,
fills: None,
empty: None,
},
required: true,
}],
action: forms::Action::Query,
/// The account label or id `account balance` names.
/// Returns an error for an unknown or repeated key, or no `account`.
pub fn build_account_balance(args: &[(String, String)]) -> Result<String, CommandError> {
let parsed = parse_args(&[BALANCE_ACCOUNT], args)?;
require(&parsed, BALANCE_ACCOUNT).map(str::to_string)
/// The `account merge` args as form values: `from` and `into`, each at most once.
/// Returns an error for an unknown or repeated key.
pub fn build_account_merge(args: &[(String, String)]) -> Result<FormValues, CommandError> {
let keys: Vec<&str> = ACCOUNT_MERGE.fields.iter().map(|field| field.key).collect();
parse_args(&keys, args).map(|parsed| values_of(&parsed))
/// The `transaction list` args as filter values; the accepted keys are the
/// `transaction-query` descriptor's, paging ones aside.
/// Returns an error for a key that does not filter transactions or is repeated.
pub fn build_transaction_filter(args: &[(String, String)]) -> Result<FormValues, CommandError> {
let keys: Vec<&str> = TRANSACTION_QUERY
.filter_fields()
/// Flatten `path` into a space-joined key for matching.
fn path_key(path: &[String]) -> String {
path.join(" ")
#[cfg(test)]
mod tests;