1
//! `script` subcommands: list, create, edit, enable, disable, delete and run of scripts.
2

            
3
use clap::Subcommand;
4
use cli_core::CommandError;
5
use cli_core::script as ops;
6
use rpc::Session;
7
use sqlx::types::Uuid;
8
use std::io::{BufRead, IsTerminal};
9
use std::path::PathBuf;
10

            
11
use crate::eval::{RenderMode, build_delete_script_form, eval_print};
12
use crate::template::read_path;
13
use crate::transaction::confirmed;
14

            
15
#[derive(Subcommand, Debug)]
16
pub enum ScriptCmd {
17
    /// List the scripts: id, name, state and whether the source is stored
18
    List,
19
    /// Create a script from a source
20
    Create {
21
        #[arg(long)]
22
        name: Option<String>,
23
        /// File holding the source; `-` reads standard input
24
        #[arg(long, value_name = "PATH")]
25
        file: PathBuf,
26
    },
27
    /// Edit a script; omitted fields stay as stored
28
    Edit {
29
        /// Id of the script
30
        id: Uuid,
31
        #[arg(long)]
32
        name: Option<String>,
33
        /// File holding the new source; `-` reads standard input
34
        #[arg(long, value_name = "PATH")]
35
        file: Option<PathBuf>,
36
    },
37
    /// Let the script run on triggers again
38
    Enable {
39
        /// Id of the script
40
        id: Uuid,
41
    },
42
    /// Stop the script from running on triggers
43
    Disable {
44
        /// Id of the script
45
        id: Uuid,
46
    },
47
    /// Delete a script
48
    Delete {
49
        /// Id of the script
50
        id: Uuid,
51
        /// Delete without asking; required when stdin is not a terminal
52
        #[arg(long)]
53
        yes: bool,
54
    },
55
    /// Run a script over the transactions of an account
56
    Run {
57
        /// Id of the script
58
        id: Uuid,
59
        /// Account id or name
60
        #[arg(long)]
61
        account: String,
62
    },
63
}
64

            
65
/// Deletes the script unless the answer declines; returns whether it was deleted.
66
3
pub async fn delete_script_confirmed(
67
3
    session: &mut Session,
68
3
    id: Uuid,
69
3
    yes: bool,
70
3
    interactive: bool,
71
3
    input: impl BufRead,
72
3
) -> Result<bool, CommandError> {
73
3
    let question = format!("Delete script {id}?");
74
3
    if !confirmed(&question, yes, interactive, input)? {
75
1
        return Ok(false);
76
1
    }
77
1
    let form = build_delete_script_form(&id.to_string());
78
1
    eval_print(session, &form, RenderMode::BoolSuccess).await?;
79
1
    Ok(true)
80
3
}
81

            
82
/// Prints the run report; a run with failures is an error.
83
2
fn report(run: &ops::RunReport) -> Result<(), CommandError> {
84
7
    run.lines().iter().for_each(|line| println!("{line}"));
85
2
    match run.failures.len() {
86
1
        0 => Ok(()),
87
1
        count => Err(CommandError::Command(format!(
88
1
            "the script failed on {count} transaction(s)"
89
1
        ))),
90
    }
91
2
}
92

            
93
7
pub async fn run(session: &mut Session, cmd: ScriptCmd) -> Result<(), CommandError> {
94
7
    match cmd {
95
        ScriptCmd::List => ops::list(session)
96
            .await?
97
            .iter()
98
            .for_each(|script| println!("{}", script.line())),
99
        ScriptCmd::Create { name, file } => {
100
1
            let source = read_path(&file, std::io::stdin().lock())?;
101
1
            println!("{}", ops::create(session, name.as_deref(), &source).await?);
102
        }
103
        ScriptCmd::Edit { id, name, file } => {
104
2
            let source = file
105
1
                .map(|file| read_path(&file, std::io::stdin().lock()))
106
                .transpose()?;
107
2
            let id = id.to_string();
108
2
            let edited = ops::edit(session, &id, name.as_deref(), source.as_deref(), None);
109
2
            println!("{}", edited.await?);
110
        }
111
1
        ScriptCmd::Enable { id } => toggle(session, id, true).await?,
112
2
        ScriptCmd::Disable { id } => toggle(session, id, false).await?,
113
        ScriptCmd::Delete { id, yes } => {
114
            let stdin = std::io::stdin();
115
            if !delete_script_confirmed(session, id, yes, stdin.is_terminal(), stdin.lock()).await?
116
            {
117
                eprintln!("Cancelled");
118
            }
119
        }
120
        ScriptCmd::Run { id, account } => {
121
1
            report(&ops::run(session, &id.to_string(), &account).await?)?;
122
        }
123
    }
124
3
    Ok(())
125
7
}
126

            
127
3
async fn toggle(session: &mut Session, id: Uuid, enabled: bool) -> Result<(), CommandError> {
128
3
    let edited = ops::edit(session, &id.to_string(), None, None, Some(enabled)).await?;
129
2
    println!("{edited}");
130
2
    Ok(())
131
3
}
132

            
133
#[cfg(test)]
134
mod tests;