Lines
92.73 %
Functions
86.36 %
Branches
100 %
//! Script commands over the script forms, `list-scripts` and `run-script`.
use forms::{FormValues, SCRIPT_CREATE, SCRIPT_EDIT, Source, escape_str};
use nomiscript::{Value, list_to_vec};
use rpc::Session;
use crate::CommandError;
use crate::eval::{plist_field, plist_field_raw};
use crate::flat::{Reply, edit as edit_form, submit};
use crate::forms::resolve;
use crate::template::options;
use crate::transaction::eval_value;
/// A stored script as `list-scripts` reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptInfo {
pub id: String,
pub name: String,
pub enabled: bool,
pub has_source: bool,
}
impl ScriptInfo {
/// `id name enabled|disabled source|bytecode-only`.
#[must_use]
pub fn line(&self) -> String {
let state = if self.enabled { "enabled" } else { "disabled" };
let kind = if self.has_source {
"source"
} else {
"bytecode-only"
};
format!("{} {} {state} {kind}", self.id, self.name)
/// The outcome of one script run over an account.
pub struct RunReport {
pub ran: String,
pub committed: String,
pub failures: Vec<String>,
impl RunReport {
/// The counts, then one line per failure.
pub fn lines(&self) -> Vec<String> {
let mut lines = vec![
format!("ran: {}", self.ran),
format!("committed: {}", self.committed),
format!("failures: {}", self.failures.len()),
];
lines.extend(self.failures.iter().cloned());
lines
fn info_of(item: &Value) -> Option<ScriptInfo> {
let flag = |key| !matches!(plist_field_raw(item, key), Some(Value::Nil) | None);
Some(ScriptInfo {
id: plist_field(item, ":id")?,
name: plist_field(item, ":name").unwrap_or_default(),
enabled: flag(":enabled"),
has_source: flag(":has-source"),
})
/// The user's scripts.
///
/// # Errors
/// The server error, or [`CommandError::Command`] for a malformed reply.
pub async fn list(session: &mut Session) -> Result<Vec<ScriptInfo>, CommandError> {
let reply = eval_value(session, "(list-scripts)").await?;
list_to_vec(&reply)
.unwrap_or_default()
.iter()
.map(|item| {
info_of(item).ok_or_else(|| {
CommandError::Command(format!(
"malformed script entry: {}",
nomiscript::format_value(item)
))
.collect()
fn stored_id(reply: Reply) -> Result<String, CommandError> {
match reply {
Reply::Entity(id) => Ok(id),
other => Err(CommandError::Command(format!(
"unexpected script reply: {other:?}"
))),
fn values_of(name: Option<&str>, source: Option<&str>, enabled: Option<bool>) -> FormValues {
let mut values = FormValues::default();
name.into_iter().for_each(|name| values.set("name", name));
source
.into_iter()
.for_each(|source| values.set("source", source));
enabled
.for_each(|on| values.set("enabled", if on { "true" } else { "false" }));
values
/// Store a new, enabled script and return its id.
/// [`CommandError::FormInvalid`] for a source that does not compile, or the server error.
pub async fn create(
session: &mut Session,
name: Option<&str>,
source: &str,
) -> Result<String, CommandError> {
let values = values_of(name, Some(source), None);
stored_id(submit(session, &SCRIPT_CREATE, &values).await?.reply)
/// Replace the given fields of script `id`, keeping the rest as stored.
/// The server's refusal of the load, [`CommandError::FormInvalid`] for a
/// source that does not compile, a stale revision or a script that cannot
/// be saved this way.
pub async fn edit(
id: &str,
source: Option<&str>,
enabled: Option<bool>,
let values = values_of(name, source, enabled);
stored_id(edit_form(session, &SCRIPT_EDIT, id, &values).await?.reply)
/// Run script `script` over `account`, an id or a name.
/// [`CommandError::Argument`] for an unknown or ambiguous account, or the server error.
pub async fn run(
script: &str,
account: &str,
) -> Result<RunReport, CommandError> {
let accounts = options(session, "accounts").await?;
let account = resolve(&accounts, Source::Accounts, "--account", account)?;
let call = format!(
"(run-script {} {})",
escape_str(script),
escape_str(&account)
);
parse_report(&eval_value(session, &call).await?)
fn failure_line(failure: &Value) -> String {
let field = |key| plist_field(failure, key).unwrap_or_default();
format!(
"failed: transaction {}: {}: {}",
field(":transaction"),
field(":code"),
field(":message")
)
/// The report of a `run-script` reply.
/// [`CommandError::Command`] when `reply` is not a run report.
pub fn parse_report(reply: &Value) -> Result<RunReport, CommandError> {
let (Some(ran), Some(committed)) =
(plist_field(reply, ":ran"), plist_field(reply, ":committed"))
else {
return Err(CommandError::Command(format!(
"malformed script run: {}",
nomiscript::format_value(reply)
)));
let failures = plist_field_raw(reply, ":failures")
.as_ref()
.and_then(list_to_vec)
.map(failure_line)
.collect();
Ok(RunReport {
ran,
committed,
failures,
#[cfg(test)]
mod tests;