use std::os::windows::process::CommandExt as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
pub(crate) fn cmd(script: &str) -> Command {
#[expect(
clippy::disallowed_methods,
reason = "the tests build the commands that the crate runs"
)]
let mut cmd = Command::new("cmd");
cmd.raw_arg("/C").raw_arg(script);
cmd
}
pub(crate) fn pid_file(name: &str) -> PathBuf {
std::env::temp_dir().join(format!("crumbkit-process-{}-{name}", std::process::id()))
}
pub(crate) fn started_grandchild(file: &Path, seconds: u32) -> String {
let file = file.display();
format!(
"start /B powershell -NoProfile -NonInteractive -Command \
\"$PID; Set-Content -Path '{file}' -Value $PID; Start-Sleep {seconds}; 'woke'\" \
& for /L %i in (1,1,60) do @(if not exist \"{file}\" ping -n 2 127.0.0.1 >NUL) \
& echo started"
)
}
pub(crate) fn pid_in(bytes: &[u8]) -> u32 {
String::from_utf8_lossy(bytes)
.lines()
.find_map(|line| line.trim().parse().ok())
.unwrap()
}
fn alive(pid: u32) -> bool {
#[expect(
clippy::disallowed_methods,
reason = "the tests ask tasklist whether a process is running"
)]
let listed = Command::new("tasklist")
.raw_arg(format!("/FI \"PID eq {pid}\" /NH /FO CSV"))
.output()
.unwrap();
String::from_utf8_lossy(&listed.stdout).contains(&format!("\"{pid}\""))
}
pub(crate) fn gone(pid: u32) -> bool {
let deadline = Instant::now() + Duration::from_secs(10);
while alive(pid) {
if Instant::now() > deadline {
return false;
}
std::thread::sleep(Duration::from_millis(100));
}
true
}
pub(crate) fn remove(path: &Path) {
#[expect(
clippy::disallowed_methods,
reason = "the tests remove the files that their grandchildren created"
)]
let _ = std::fs::remove_file(path);
}