Skip to main content

cli/
account_merge.rs

1//! `account merge`, built from the `account-merge` form descriptor.
2
3use clap::{Arg, ArgAction, ArgMatches, Args, Command, Error, FromArgMatches};
4use cli_core::CommandError;
5use forms::{ACCOUNT_MERGE, FormValues};
6use rpc::Session;
7use std::io::{BufRead, IsTerminal};
8
9use crate::transaction::{confirmed, field_arg, values_of};
10
11#[derive(Debug)]
12pub struct MergeArgs {
13    pub values: FormValues,
14    pub yes: bool,
15}
16
17impl Args for MergeArgs {
18    fn augment_args(cmd: Command) -> Command {
19        ACCOUNT_MERGE
20            .fields
21            .iter()
22            .fold(cmd, |cmd, field| cmd.arg(field_arg(&ACCOUNT_MERGE, field)))
23            .arg(
24                Arg::new("yes")
25                    .long("yes")
26                    .action(ArgAction::SetTrue)
27                    .help("Merge without asking; required when stdin is not a terminal"),
28            )
29    }
30
31    fn augment_args_for_update(cmd: Command) -> Command {
32        Self::augment_args(cmd)
33    }
34}
35
36impl FromArgMatches for MergeArgs {
37    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
38        Ok(Self {
39            values: values_of(&ACCOUNT_MERGE, matches),
40            yes: matches.get_flag("yes"),
41        })
42    }
43
44    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
45        *self = Self::from_arg_matches(matches)?;
46        Ok(())
47    }
48}
49
50fn question(values: &FormValues) -> String {
51    let pick = |key| values.text(key).unwrap_or_default();
52    format!(
53        "Merge account {} into {}? Its splits, lots, budgets, sub-accounts and tags move, \
54         and it is deleted.",
55        pick("from"),
56        pick("into")
57    )
58}
59
60async fn merge_confirmed(
61    session: &mut Session,
62    args: &MergeArgs,
63    interactive: bool,
64    input: impl BufRead,
65) -> Result<Option<String>, CommandError> {
66    match confirmed(&question(&args.values), args.yes, interactive, input)? {
67        true => Ok(Some(
68            Box::pin(cli_core::account::merge(session, &args.values)).await?,
69        )),
70        false => Ok(None),
71    }
72}
73
74pub async fn run(session: &mut Session, args: &MergeArgs) -> Result<(), CommandError> {
75    let stdin = std::io::stdin();
76    match merge_confirmed(session, args, stdin.is_terminal(), stdin.lock()).await? {
77        Some(id) => println!("{id}"),
78        None => eprintln!("Cancelled"),
79    }
80    Ok(())
81}
82
83#[cfg(test)]
84#[path = "account_merge_tests.rs"]
85mod tests;