Skip to main content

cli/
script.rs

1//! `script` subcommands: list, create, edit, enable, disable, delete and run of scripts.
2
3use clap::Subcommand;
4use cli_core::CommandError;
5use cli_core::script as ops;
6use rpc::Session;
7use sqlx::types::Uuid;
8use std::io::{BufRead, IsTerminal};
9use std::path::PathBuf;
10
11use crate::eval::{RenderMode, build_delete_script_form, eval_print};
12use crate::template::read_path;
13use crate::transaction::confirmed;
14
15#[derive(Subcommand, Debug)]
16pub 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.
66pub async fn delete_script_confirmed(
67    session: &mut Session,
68    id: Uuid,
69    yes: bool,
70    interactive: bool,
71    input: impl BufRead,
72) -> Result<bool, CommandError> {
73    let question = format!("Delete script {id}?");
74    if !confirmed(&question, yes, interactive, input)? {
75        return Ok(false);
76    }
77    let form = build_delete_script_form(&id.to_string());
78    eval_print(session, &form, RenderMode::BoolSuccess).await?;
79    Ok(true)
80}
81
82/// Prints the run report; a run with failures is an error.
83fn report(run: &ops::RunReport) -> Result<(), CommandError> {
84    run.lines().iter().for_each(|line| println!("{line}"));
85    match run.failures.len() {
86        0 => Ok(()),
87        count => Err(CommandError::Command(format!(
88            "the script failed on {count} transaction(s)"
89        ))),
90    }
91}
92
93pub async fn run(session: &mut Session, cmd: ScriptCmd) -> Result<(), CommandError> {
94    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            let source = read_path(&file, std::io::stdin().lock())?;
101            println!("{}", ops::create(session, name.as_deref(), &source).await?);
102        }
103        ScriptCmd::Edit { id, name, file } => {
104            let source = file
105                .map(|file| read_path(&file, std::io::stdin().lock()))
106                .transpose()?;
107            let id = id.to_string();
108            let edited = ops::edit(session, &id, name.as_deref(), source.as_deref(), None);
109            println!("{}", edited.await?);
110        }
111        ScriptCmd::Enable { id } => toggle(session, id, true).await?,
112        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            report(&ops::run(session, &id.to_string(), &account).await?)?;
122        }
123    }
124    Ok(())
125}
126
127async fn toggle(session: &mut Session, id: Uuid, enabled: bool) -> Result<(), CommandError> {
128    let edited = ops::edit(session, &id.to_string(), None, None, Some(enabled)).await?;
129    println!("{edited}");
130    Ok(())
131}
132
133#[cfg(test)]
134mod tests;