1
//! `account merge`, built from the `account-merge` form descriptor.
2

            
3
use clap::{Arg, ArgAction, ArgMatches, Args, Command, Error, FromArgMatches};
4
use cli_core::CommandError;
5
use forms::{ACCOUNT_MERGE, FormValues};
6
use rpc::Session;
7
use std::io::{BufRead, IsTerminal};
8

            
9
use crate::transaction::{confirmed, field_arg, values_of};
10

            
11
#[derive(Debug)]
12
pub struct MergeArgs {
13
    pub values: FormValues,
14
    pub yes: bool,
15
}
16

            
17
impl Args for MergeArgs {
18
113
    fn augment_args(cmd: Command) -> Command {
19
113
        ACCOUNT_MERGE
20
113
            .fields
21
113
            .iter()
22
226
            .fold(cmd, |cmd, field| cmd.arg(field_arg(&ACCOUNT_MERGE, field)))
23
            .arg(
24
113
                Arg::new("yes")
25
113
                    .long("yes")
26
113
                    .action(ArgAction::SetTrue)
27
113
                    .help("Merge without asking; required when stdin is not a terminal"),
28
            )
29
113
    }
30

            
31
    fn augment_args_for_update(cmd: Command) -> Command {
32
        Self::augment_args(cmd)
33
    }
34
}
35

            
36
impl FromArgMatches for MergeArgs {
37
4
    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
38
4
        Ok(Self {
39
4
            values: values_of(&ACCOUNT_MERGE, matches),
40
4
            yes: matches.get_flag("yes"),
41
4
        })
42
4
    }
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

            
50
3
fn question(values: &FormValues) -> String {
51
6
    let pick = |key| values.text(key).unwrap_or_default();
52
3
    format!(
53
        "Merge account {} into {}? Its splits, lots, budgets, sub-accounts and tags move, \
54
         and it is deleted.",
55
3
        pick("from"),
56
3
        pick("into")
57
    )
58
3
}
59

            
60
2
async fn merge_confirmed(
61
2
    session: &mut Session,
62
2
    args: &MergeArgs,
63
2
    interactive: bool,
64
2
    input: impl BufRead,
65
2
) -> Result<Option<String>, CommandError> {
66
2
    match confirmed(&question(&args.values), args.yes, interactive, input)? {
67
        true => Ok(Some(
68
1
            Box::pin(cli_core::account::merge(session, &args.values)).await?,
69
        )),
70
1
        false => Ok(None),
71
    }
72
2
}
73

            
74
pub 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"]
85
mod tests;