Lines
63.37 %
Functions
35.87 %
Branches
100 %
//! Create, edit, convert and config subcommands, built from the compiled-in form descriptors.
use clap::error::ErrorKind;
use clap::{ArgMatches, Command, Error, FromArgMatches, Subcommand};
use cli_core::CommandError;
use cli_core::flat::{self, Reply};
use forms::{Action, Form, FormValues};
use rpc::Session;
use sqlx::types::Uuid;
use std::io::BufRead;
use crate::eval::{RenderMode, build_delete_tag_form, eval_print};
use crate::transaction::{confirmed, form_command, id_arg, id_of, values_of};
#[derive(Debug)]
pub struct FormCall {
form: &'static Form,
id: Option<Uuid>,
values: FormValues,
}
pub struct Entry {
name: &'static str,
about: &'static str,
pub const ACCOUNT_FORMS: [Entry; 2] = [
Entry {
name: "create",
about: "Create new account",
form: &forms::ACCOUNT_CREATE,
},
name: "edit",
about: "Edit an account; omitted fields stay as stored",
form: &forms::ACCOUNT_EDIT,
];
pub const COMMODITY_FORMS: [Entry; 3] = [
about: "Create new commodity",
form: &forms::COMMODITY_CREATE,
about: "Edit a commodity; omitted fields stay as stored",
form: &forms::COMMODITY_EDIT,
name: "convert",
about: "Convert an amount between commodities with the latest price",
form: &forms::CONVERT,
pub const TAG_FORMS: [Entry; 2] = [
about: "Create new tag",
form: &forms::TAG_CREATE,
about: "Edit a tag; omitted fields stay as stored",
form: &forms::TAG_EDIT,
pub const CONFIG_FORMS: [Entry; 1] = [Entry {
name: "set",
about: "Set the value in config",
form: &forms::CONFIG_SET,
}];
fn entry_command(entry: &Entry) -> Command {
let command = form_command(entry.name, entry.about, entry.form);
match entry.form.action {
Action::LoadMutation => command.arg(id_arg()),
_ => command,
fn augment(cmd: Command, entries: &[Entry]) -> Command {
entries
.iter()
.fold(cmd, |cmd, entry| cmd.subcommand(entry_command(entry)))
fn parse(matches: &ArgMatches, entries: &[Entry]) -> Result<FormCall, Error> {
let (name, sub) = matches
.subcommand()
.ok_or_else(|| Error::raw(ErrorKind::MissingSubcommand, "a subcommand is required"))?;
let entry = entries
.find(|entry| entry.name == name)
.ok_or_else(|| {
Error::raw(
ErrorKind::InvalidSubcommand,
format!("unknown subcommand '{name}'"),
)
})?;
let id = match entry.form.action {
Action::LoadMutation => Some(id_of(sub)?),
_ => None,
};
Ok(FormCall {
form: entry.form,
id,
values: values_of(entry.form, sub),
})
macro_rules! form_group {
($group:ident, $entries:expr) => {
pub struct $group(pub FormCall);
impl Subcommand for $group {
fn augment_subcommands(cmd: Command) -> Command {
augment(cmd, &$entries)
fn augment_subcommands_for_update(cmd: Command) -> Command {
fn has_subcommand(name: &str) -> bool {
$entries.iter().any(|entry| entry.name == name)
impl FromArgMatches for $group {
fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
parse(matches, &$entries).map(Self)
fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
*self = Self::from_arg_matches(matches)?;
Ok(())
form_group!(AccountForms, ACCOUNT_FORMS);
form_group!(CommodityForms, COMMODITY_FORMS);
form_group!(TagForms, TAG_FORMS);
form_group!(ConfigForms, CONFIG_FORMS);
fn converted_line(values: &FormValues, converted: &str) -> String {
let text = |key| values.text(key).unwrap_or_default();
format!(
"{} {} = {converted} {}",
text("amount"),
text("from"),
text("to")
fn printed(values: &FormValues, reply: &Reply) -> Option<String> {
match reply {
Reply::Entity(id) => Some(id.clone()),
Reply::Done => None,
Reply::Value(converted) => Some(converted_line(values, converted)),
impl AccountForms {
pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
run(session, self.0).await
impl CommodityForms {
impl TagForms {
impl ConfigForms {
/// Deletes the tag unless the answer declines; returns whether it was deleted.
pub async fn delete_tag_confirmed(
session: &mut Session,
id: Uuid,
yes: bool,
interactive: bool,
input: impl BufRead,
) -> Result<bool, CommandError> {
let question = format!("Delete tag {id} and every link to it?");
if !confirmed(&question, yes, interactive, input)? {
return Ok(false);
let form = build_delete_tag_form(&id.to_string());
eval_print(session, &form, RenderMode::BoolSuccess).await?;
Ok(true)
async fn run(session: &mut Session, call: FormCall) -> Result<(), CommandError> {
let submitted = match call.id {
Some(id) => flat::edit(session, call.form, &id.to_string(), &call.values).await?,
None => flat::submit(session, call.form, &call.values).await?,
if let Some(line) = printed(&call.values, &submitted.reply) {
println!("{line}");
for notice in submitted.notices {
eprintln!("notice: {notice}");
#[cfg(test)]
pub(crate) mod tests;