Skip to main content

cli_core/
script.rs

1//! Script commands over the script forms, `list-scripts` and `run-script`.
2
3use forms::{FormValues, SCRIPT_CREATE, SCRIPT_EDIT, Source, escape_str};
4use nomiscript::{Value, list_to_vec};
5use rpc::Session;
6
7use crate::CommandError;
8use crate::eval::{plist_field, plist_field_raw};
9use crate::flat::{Reply, edit as edit_form, submit};
10use crate::forms::resolve;
11use crate::template::options;
12use crate::transaction::eval_value;
13
14/// A stored script as `list-scripts` reports it.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct ScriptInfo {
17    pub id: String,
18    pub name: String,
19    pub enabled: bool,
20    pub has_source: bool,
21}
22
23impl ScriptInfo {
24    /// `id  name  enabled|disabled  source|bytecode-only`.
25    #[must_use]
26    pub fn line(&self) -> String {
27        let state = if self.enabled { "enabled" } else { "disabled" };
28        let kind = if self.has_source {
29            "source"
30        } else {
31            "bytecode-only"
32        };
33        format!("{}  {}  {state}  {kind}", self.id, self.name)
34    }
35}
36
37/// The outcome of one script run over an account.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct RunReport {
40    pub ran: String,
41    pub committed: String,
42    pub failures: Vec<String>,
43}
44
45impl RunReport {
46    /// The counts, then one line per failure.
47    #[must_use]
48    pub fn lines(&self) -> Vec<String> {
49        let mut lines = vec![
50            format!("ran: {}", self.ran),
51            format!("committed: {}", self.committed),
52            format!("failures: {}", self.failures.len()),
53        ];
54        lines.extend(self.failures.iter().cloned());
55        lines
56    }
57}
58
59fn info_of(item: &Value) -> Option<ScriptInfo> {
60    let flag = |key| !matches!(plist_field_raw(item, key), Some(Value::Nil) | None);
61    Some(ScriptInfo {
62        id: plist_field(item, ":id")?,
63        name: plist_field(item, ":name").unwrap_or_default(),
64        enabled: flag(":enabled"),
65        has_source: flag(":has-source"),
66    })
67}
68
69/// The user's scripts.
70///
71/// # Errors
72/// The server error, or [`CommandError::Command`] for a malformed reply.
73pub async fn list(session: &mut Session) -> Result<Vec<ScriptInfo>, CommandError> {
74    let reply = eval_value(session, "(list-scripts)").await?;
75    list_to_vec(&reply)
76        .unwrap_or_default()
77        .iter()
78        .map(|item| {
79            info_of(item).ok_or_else(|| {
80                CommandError::Command(format!(
81                    "malformed script entry: {}",
82                    nomiscript::format_value(item)
83                ))
84            })
85        })
86        .collect()
87}
88
89fn stored_id(reply: Reply) -> Result<String, CommandError> {
90    match reply {
91        Reply::Entity(id) => Ok(id),
92        other => Err(CommandError::Command(format!(
93            "unexpected script reply: {other:?}"
94        ))),
95    }
96}
97
98fn values_of(name: Option<&str>, source: Option<&str>, enabled: Option<bool>) -> FormValues {
99    let mut values = FormValues::default();
100    name.into_iter().for_each(|name| values.set("name", name));
101    source
102        .into_iter()
103        .for_each(|source| values.set("source", source));
104    enabled
105        .into_iter()
106        .for_each(|on| values.set("enabled", if on { "true" } else { "false" }));
107    values
108}
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.
114pub async fn create(
115    session: &mut Session,
116    name: Option<&str>,
117    source: &str,
118) -> Result<String, CommandError> {
119    let values = values_of(name, Some(source), None);
120    stored_id(submit(session, &SCRIPT_CREATE, &values).await?.reply)
121}
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.
129pub async fn edit(
130    session: &mut Session,
131    id: &str,
132    name: Option<&str>,
133    source: Option<&str>,
134    enabled: Option<bool>,
135) -> Result<String, CommandError> {
136    let values = values_of(name, source, enabled);
137    stored_id(edit_form(session, &SCRIPT_EDIT, id, &values).await?.reply)
138}
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.
144pub async fn run(
145    session: &mut Session,
146    script: &str,
147    account: &str,
148) -> Result<RunReport, CommandError> {
149    let accounts = options(session, "accounts").await?;
150    let account = resolve(&accounts, Source::Accounts, "--account", account)?;
151    let call = format!(
152        "(run-script {} {})",
153        escape_str(script),
154        escape_str(&account)
155    );
156    parse_report(&eval_value(session, &call).await?)
157}
158
159fn failure_line(failure: &Value) -> String {
160    let field = |key| plist_field(failure, key).unwrap_or_default();
161    format!(
162        "failed: transaction {}: {}: {}",
163        field(":transaction"),
164        field(":code"),
165        field(":message")
166    )
167}
168
169/// The report of a `run-script` reply.
170///
171/// # Errors
172/// [`CommandError::Command`] when `reply` is not a run report.
173pub fn parse_report(reply: &Value) -> Result<RunReport, CommandError> {
174    let (Some(ran), Some(committed)) =
175        (plist_field(reply, ":ran"), plist_field(reply, ":committed"))
176    else {
177        return Err(CommandError::Command(format!(
178            "malformed script run: {}",
179            nomiscript::format_value(reply)
180        )));
181    };
182    let failures = plist_field_raw(reply, ":failures")
183        .as_ref()
184        .and_then(list_to_vec)
185        .unwrap_or_default()
186        .iter()
187        .map(failure_line)
188        .collect();
189    Ok(RunReport {
190        ran,
191        committed,
192        failures,
193    })
194}
195
196#[cfg(test)]
197mod tests;