Medlar/crates/core/src/run.rs
2026-11-25 21:23:13 -06:00

89 lines
3.1 KiB
Rust

//! Runs a program of the user's: an argument list with placeholders, never a shell.
use std::time::Duration;
use tokio::io::AsyncReadExt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunSpec {
pub program: String,
/// May hold `{file}`, `{name}`, `{folder}`, `{url}`, `{queue}`.
pub args: Vec<String>,
pub timeout: Duration,
}
/// What the placeholders stand for.
#[derive(Debug, Clone, Default)]
pub struct Vars {
pub file: String,
pub name: String,
pub folder: String,
pub url: String,
pub queue: String,
}
impl Vars {
fn fill(&self, arg: &str) -> String {
arg.replace("{file}", &self.file)
.replace("{name}", &self.name)
.replace("{folder}", &self.folder)
.replace("{url}", &self.url)
.replace("{queue}", &self.queue)
}
}
/// The arguments as they will be passed. Each stays one argument, whatever it holds.
pub fn expand(spec: &RunSpec, vars: &Vars) -> Vec<String> {
spec.args.iter().map(|a| vars.fill(a)).collect()
}
const OUTPUT: usize = 16 * 1024;
/// Runs it; its output (the first 16 KiB) goes to the log and comes back. Killed when the time is out.
pub async fn run(spec: &RunSpec, vars: &Vars) -> Result<String, String> {
if spec.program.trim().is_empty() {
return Err("No program is set.".into());
}
let mut child = tokio::process::Command::new(&spec.program)
.args(expand(spec, vars))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("{} did not start: {e}", spec.program))?;
let (out, err) = (child.stdout.take().unwrap(), child.stderr.take().unwrap());
let work = async {
let (mut a, mut b) = (vec![], vec![]);
let (mut out, mut err) = (out.take(OUTPUT as u64), err.take(OUTPUT as u64));
let (_, _, status) = tokio::join!(out.read_to_end(&mut a), err.read_to_end(&mut b), child.wait());
(status, a, b)
};
match tokio::time::timeout(spec.timeout, work).await {
Err(_) => {
let _ = child.start_kill();
Err(format!("{} was stopped after {} seconds.", spec.program, spec.timeout.as_secs()))
}
Ok((status, a, b)) => {
let mut text = String::from_utf8_lossy(&a).into_owned();
text.push_str(&String::from_utf8_lossy(&b));
log::info!("{} said: {}", spec.program, text.trim());
match status {
Ok(s) if s.success() => Ok(text),
Ok(s) => Err(format!("{} ended with {s}.", spec.program)),
Err(e) => Err(format!("{} could not be waited for: {e}", spec.program)),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn placeholders_stay_single_arguments() {
let spec = RunSpec { program: "x".into(), args: vec!["{file}".into(), "-n={name}".into()], timeout: Duration::from_secs(1) };
let vars = Vars { file: "/a b/c; rm -rf".into(), name: "c".into(), ..Vars::default() };
assert_eq!(expand(&spec, &vars), ["/a b/c; rm -rf", "-n=c"]);
}
}