use std::fs;
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Ended {
pub passed: bool,
pub out: String,
pub err: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<i32>,
}
impl Ended {
pub fn said(&self) -> String {
let (out, err) = (self.out.trim(), self.err.trim());
match (out.is_empty(), err.is_empty()) {
(_, true) => out.to_owned(),
(true, false) => err.to_owned(),
(false, false) => format!("{out}\n{err}"),
}
}
pub fn points(&self, line: &str) -> String {
let said = self.said();
if !said.is_empty() {
return said;
}
match self.code {
Some(code) => {
format!("The command `{line}` ended with the code {code} and wrote nothing.")
}
None => format!("The command `{line}` was stopped and wrote nothing."),
}
}
}
pub fn run_kept(
line: &str,
folder: &Path,
keep: &Path,
deadline: Option<Instant>,
) -> Result<Ended, TimeOver> {
if !cfg!(unix) || fs::create_dir_all(keep).is_err() {
return run(line, folder, &[], "", deadline);
}
let path = |name: &str| {
let path = keep.join(name).display().to_string();
format!("'{}'", path.replace('\'', "'\\''"))
};
let wrapped = format!(
"echo $$ > {pid}; ( {line}\n ) > {out} 2> {err}; echo $? > {part} && mv {part} {code}",
pid = path("pid"),
out = path("out"),
err = path("err"),
part = path("code.part"),
code = path("code"),
);
let ended = run(&wrapped, folder, &[], "", deadline)?;
Ok(kept(keep).unwrap_or(ended))
}
pub fn kept(dir: &Path) -> Option<Ended> {
let code: i32 = fs::read_to_string(dir.join("code"))
.ok()?
.trim()
.parse()
.ok()?;
let read = |name: &str| fs::read_to_string(dir.join(name)).unwrap_or_default();
Some(Ended {
passed: code == 0,
out: read("out"),
err: read("err"),
code: Some(code),
})
}
pub fn alive(pid: u32) -> bool {
cfg!(unix)
&& Command::new("kill")
.args(["-0", &pid.to_string()])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
pub struct TimeOver;
fn shell(line: &str) -> Command {
if cfg!(windows) {
let mut command = Command::new("cmd");
command.args(["/C", line]);
command
} else {
let mut command = Command::new("sh");
command.args(["-c", line]);
command
}
}
fn reader(mut stream: impl Read + Send + 'static) -> JoinHandle<String> {
thread::spawn(move || {
let mut bytes = Vec::new();
let _ = stream.read_to_end(&mut bytes);
String::from_utf8_lossy(&bytes).into_owned()
})
}
fn stop(child: &mut Child) {
#[cfg(unix)]
{
let _ = Command::new("kill")
.args(["-KILL", "--", &format!("-{}", child.id())])
.stderr(Stdio::null())
.status();
}
let _ = child.kill();
let _ = child.wait();
}
pub fn run(
line: &str,
folder: &Path,
variables: &[(&str, String)],
input: &str,
deadline: Option<Instant>,
) -> Result<Ended, TimeOver> {
let mut command = shell(line);
command
.current_dir(folder)
.envs(variables.iter().map(|(key, value)| (*key, value)))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
let mut child = match command.spawn() {
Ok(child) => child,
Err(error) => {
return Ok(Ended {
passed: false,
out: String::new(),
err: format!("the command could not start: {error}"),
code: None,
});
}
};
if let Some(mut stdin) = child.stdin.take() {
let input = input.to_owned();
thread::spawn(move || {
let _ = stdin.write_all(input.as_bytes());
});
}
let out = child.stdout.take().map(reader);
let err = child.stderr.take().map(reader);
loop {
match child.try_wait() {
Ok(Some(status)) => {
let text = |handle: Option<JoinHandle<String>>| {
handle
.and_then(|handle| handle.join().ok())
.unwrap_or_default()
};
return Ok(Ended {
passed: status.success(),
out: text(out),
err: text(err),
code: status.code(),
});
}
Ok(None) if deadline.is_some_and(|deadline| Instant::now() >= deadline) => {
stop(&mut child);
return Err(TimeOver);
}
Ok(None) => thread::sleep(Duration::from_millis(10)),
Err(error) => {
stop(&mut child);
return Ok(Ended {
passed: false,
out: String::new(),
err: format!("the command could not be followed: {error}"),
code: None,
});
}
}
}
}