Lines
100 %
Functions
Branches
//! Maps the CLI's select input (id, label or alias) to option ids before a submit.
use forms::{Form, FormValues, Kind, Row, Source, escape_str};
use rpc::Session;
use super::{FormOption, parse_option_list};
use crate::CommandError;
use crate::transaction::eval_text;
/// The `form-options` fetched per source.
pub type Fetched = Vec<(Source, Vec<FormOption>)>;
/// The id of the option `input` names: an own id, an exact label, or a unique
/// alias; `|` stands for `¦`, and commodities compare case-insensitively.
///
/// # Errors
/// [`CommandError::Argument`] naming `flag` when nothing matches, or listing
/// the candidate labels when several do.
pub fn resolve(
options: &[FormOption],
source: Source,
flag: &str,
input: &str,
) -> Result<String, CommandError> {
if let Some(own) = options.iter().find(|o| o.id.eq_ignore_ascii_case(input)) {
return Ok(own.id.clone());
}
let wanted = fold(source, input);
let by_label: Vec<_> = options
.iter()
.filter(|o| fold(source, &o.label) == wanted)
.collect();
let candidates = match by_label.is_empty() {
true => options
.filter(|o| fold(source, &o.alias) == wanted)
.collect(),
false => by_label,
};
match candidates.as_slice() {
[only] => Ok(only.id.clone()),
[] => Err(CommandError::Argument(format!(
"{flag}: '{input}' matches no entry"
))),
many => Err(CommandError::Argument(format!(
"{flag}: '{input}' is ambiguous, use one of: {}",
many.iter()
.map(|o| o.label.as_str())
.collect::<Vec<_>>()
.join(", ")
fn fold(source: Source, text: &str) -> String {
let text = text.replace('|', "¦");
match source {
Source::Commodities => text.to_lowercase(),
Source::Accounts | Source::Templates | Source::Scripts => text,
/// `values` with every non-empty select value replaced by its option id, over
/// one `form-options` fetch per source; the session sees no submit on failure.
/// [`CommandError::Argument`] for an unknown or ambiguous value, or the
/// server's refusal of the fetch.
pub async fn map_references(
session: &mut Session,
form: &Form,
values: &FormValues,
) -> Result<FormValues, CommandError> {
let mut fetched = Fetched::new();
for source in sources_used(form, values) {
let call = format!("(form-options {})", escape_str(source.name()));
let options = parse_option_list(&eval_text(session, &call).await?);
fetched.push((source, options));
map_values(form, values, &fetched, "--")
/// The option sources `values` has a select value in.
#[must_use]
pub fn sources_used(form: &Form, values: &FormValues) -> Vec<Source> {
let mut used = Vec::new();
for field in form.fields {
let sources = match field.kind {
Kind::Select { source, .. } => values.text(field.key).map(|_| vec![source]),
Kind::Rows { fields, .. } => values.rows(field.key).map(|rows| {
rows.iter()
.flat_map(|row| row.keys().filter_map(|k| select_source(fields, k)))
.collect()
}),
_ => None,
for source in sources.unwrap_or_default() {
if !used.contains(&source) {
used.push(source);
used
fn select_source(fields: &[forms::Field], key: &str) -> Option<Source> {
match fields.iter().find(|f| f.key == key)?.kind {
Kind::Select { source, .. } => Some(source),
/// `values` with every non-empty select value replaced by its id in `fetched`;
/// errors name a field as `{flag_prefix}{key}`.
/// [`CommandError::Argument`] for an unknown or ambiguous value.
pub fn map_values(
fetched: &Fetched,
flag_prefix: &str,
let mut mapped = FormValues::default();
match field.kind {
Kind::Select { source, .. } => {
if let Some(text) = values.text(field.key) {
let flag = format!("{flag_prefix}{}", field.key);
mapped.set(field.key, &map_one(fetched, source, &flag, text)?);
Kind::Rows { fields, .. } => {
if let Some(rows) = values.rows(field.key) {
mapped.set_rows(field.key);
for row in rows {
mapped.push_row(field.key, map_row(fields, row, fetched, flag_prefix)?);
_ => {
mapped.set(field.key, text);
Ok(mapped)
fn map_row(
fields: &[forms::Field],
row: &Row,
) -> Result<Row, CommandError> {
row.iter()
.map(|(key, text)| {
let flag = format!("{flag_prefix}row {key}");
let text = match select_source(fields, key) {
Some(source) => map_one(fetched, source, &flag, text)?,
None => text.clone(),
Ok((key.clone(), text))
})
fn map_one(
text: &str,
if text.is_empty() {
return Ok(String::new());
let options = fetched
.find(|(s, _)| *s == source)
.map_or(&[][..], |(_, options)| options.as_slice());
resolve(options, source, flag, text)