1
//! Script commands over the script forms, `list-scripts` and `run-script`.
2

            
3
use forms::{FormValues, SCRIPT_CREATE, SCRIPT_EDIT, Source, escape_str};
4
use nomiscript::{Value, list_to_vec};
5
use rpc::Session;
6

            
7
use crate::CommandError;
8
use crate::eval::{plist_field, plist_field_raw};
9
use crate::flat::{Reply, edit as edit_form, submit};
10
use crate::forms::resolve;
11
use crate::template::options;
12
use crate::transaction::eval_value;
13

            
14
/// A stored script as `list-scripts` reports it.
15
#[derive(Debug, Clone, PartialEq, Eq)]
16
pub struct ScriptInfo {
17
    pub id: String,
18
    pub name: String,
19
    pub enabled: bool,
20
    pub has_source: bool,
21
}
22

            
23
impl ScriptInfo {
24
    /// `id  name  enabled|disabled  source|bytecode-only`.
25
    #[must_use]
26
2
    pub fn line(&self) -> String {
27
2
        let state = if self.enabled { "enabled" } else { "disabled" };
28
2
        let kind = if self.has_source {
29
1
            "source"
30
        } else {
31
1
            "bytecode-only"
32
        };
33
2
        format!("{}  {}  {state}  {kind}", self.id, self.name)
34
2
    }
35
}
36

            
37
/// The outcome of one script run over an account.
38
#[derive(Debug, Clone, PartialEq, Eq)]
39
pub struct RunReport {
40
    pub ran: String,
41
    pub committed: String,
42
    pub failures: Vec<String>,
43
}
44

            
45
impl RunReport {
46
    /// The counts, then one line per failure.
47
    #[must_use]
48
25
    pub fn lines(&self) -> Vec<String> {
49
25
        let mut lines = vec![
50
25
            format!("ran: {}", self.ran),
51
25
            format!("committed: {}", self.committed),
52
25
            format!("failures: {}", self.failures.len()),
53
        ];
54
25
        lines.extend(self.failures.iter().cloned());
55
25
        lines
56
25
    }
57
}
58

            
59
79
fn info_of(item: &Value) -> Option<ScriptInfo> {
60
158
    let flag = |key| !matches!(plist_field_raw(item, key), Some(Value::Nil) | None);
61
    Some(ScriptInfo {
62
79
        id: plist_field(item, ":id")?,
63
79
        name: plist_field(item, ":name").unwrap_or_default(),
64
79
        enabled: flag(":enabled"),
65
79
        has_source: flag(":has-source"),
66
    })
67
79
}
68

            
69
/// The user's scripts.
70
///
71
/// # Errors
72
/// The server error, or [`CommandError::Command`] for a malformed reply.
73
91
pub async fn list(session: &mut Session) -> Result<Vec<ScriptInfo>, CommandError> {
74
91
    let reply = eval_value(session, "(list-scripts)").await?;
75
91
    list_to_vec(&reply)
76
91
        .unwrap_or_default()
77
91
        .iter()
78
79
        .map(|item| {
79
79
            info_of(item).ok_or_else(|| {
80
                CommandError::Command(format!(
81
                    "malformed script entry: {}",
82
                    nomiscript::format_value(item)
83
                ))
84
            })
85
79
        })
86
        .collect()
87
91
}
88

            
89
109
fn stored_id(reply: Reply) -> Result<String, CommandError> {
90
109
    match reply {
91
109
        Reply::Entity(id) => Ok(id),
92
        other => Err(CommandError::Command(format!(
93
            "unexpected script reply: {other:?}"
94
        ))),
95
    }
96
109
}
97

            
98
148
fn values_of(name: Option<&str>, source: Option<&str>, enabled: Option<bool>) -> FormValues {
99
148
    let mut values = FormValues::default();
100
148
    name.into_iter().for_each(|name| values.set("name", name));
101
148
    source
102
148
        .into_iter()
103
95
        .for_each(|source| values.set("source", source));
104
148
    enabled
105
148
        .into_iter()
106
39
        .for_each(|on| values.set("enabled", if on { "true" } else { "false" }));
107
148
    values
108
148
}
109

            
110
/// Store a new, enabled script and return its id.
111
///
112
/// # Errors
113
/// [`CommandError::FormInvalid`] for a source that does not compile, or the server error.
114
81
pub async fn create(
115
81
    session: &mut Session,
116
81
    name: Option<&str>,
117
81
    source: &str,
118
81
) -> Result<String, CommandError> {
119
81
    let values = values_of(name, Some(source), None);
120
81
    stored_id(submit(session, &SCRIPT_CREATE, &values).await?.reply)
121
81
}
122

            
123
/// Replace the given fields of script `id`, keeping the rest as stored.
124
///
125
/// # Errors
126
/// The server's refusal of the load, [`CommandError::FormInvalid`] for a
127
/// source that does not compile, a stale revision or a script that cannot
128
/// be saved this way.
129
67
pub async fn edit(
130
67
    session: &mut Session,
131
67
    id: &str,
132
67
    name: Option<&str>,
133
67
    source: Option<&str>,
134
67
    enabled: Option<bool>,
135
67
) -> Result<String, CommandError> {
136
67
    let values = values_of(name, source, enabled);
137
67
    stored_id(edit_form(session, &SCRIPT_EDIT, id, &values).await?.reply)
138
67
}
139

            
140
/// Run script `script` over `account`, an id or a name.
141
///
142
/// # Errors
143
/// [`CommandError::Argument`] for an unknown or ambiguous account, or the server error.
144
15
pub async fn run(
145
15
    session: &mut Session,
146
15
    script: &str,
147
15
    account: &str,
148
15
) -> Result<RunReport, CommandError> {
149
15
    let accounts = options(session, "accounts").await?;
150
15
    let account = resolve(&accounts, Source::Accounts, "--account", account)?;
151
2
    let call = format!(
152
        "(run-script {} {})",
153
2
        escape_str(script),
154
2
        escape_str(&account)
155
    );
156
2
    parse_report(&eval_value(session, &call).await?)
157
15
}
158

            
159
2
fn failure_line(failure: &Value) -> String {
160
6
    let field = |key| plist_field(failure, key).unwrap_or_default();
161
2
    format!(
162
        "failed: transaction {}: {}: {}",
163
2
        field(":transaction"),
164
2
        field(":code"),
165
2
        field(":message")
166
    )
167
2
}
168

            
169
/// The report of a `run-script` reply.
170
///
171
/// # Errors
172
/// [`CommandError::Command`] when `reply` is not a run report.
173
4
pub fn parse_report(reply: &Value) -> Result<RunReport, CommandError> {
174
    let (Some(ran), Some(committed)) =
175
4
        (plist_field(reply, ":ran"), plist_field(reply, ":committed"))
176
    else {
177
1
        return Err(CommandError::Command(format!(
178
1
            "malformed script run: {}",
179
1
            nomiscript::format_value(reply)
180
1
        )));
181
    };
182
3
    let failures = plist_field_raw(reply, ":failures")
183
3
        .as_ref()
184
3
        .and_then(list_to_vec)
185
3
        .unwrap_or_default()
186
3
        .iter()
187
3
        .map(failure_line)
188
3
        .collect();
189
3
    Ok(RunReport {
190
3
        ran,
191
3
        committed,
192
3
        failures,
193
3
    })
194
4
}
195

            
196
#[cfg(test)]
197
mod tests;