use std::io::Write;
use std::process::{Child, ChildStdin, Command};
pub(crate) struct StdChild(Option<Child>);
impl StdChild {
#[track_caller]
pub(crate) fn spawn(cmd: &mut Command) -> Self {
Self(Some(crate::test_spawn::spawn(cmd).expect("spawn the std child")))
}
#[cfg(windows)]
#[track_caller]
pub(crate) fn spawn_with(cmd: &mut Command, flags: u32, console: super::Console) -> Self {
Self(Some(
crate::test_spawn::spawn_with(cmd, flags, console).expect("spawn the std child"),
))
}
#[must_use = "the child is no longer killed or reaped when dropped"]
pub(crate) fn into_inner(mut self) -> Child {
self.0.take().expect("the child is present until into_inner")
}
#[must_use = "the child is no longer killed or reaped when dropped"]
pub(crate) fn into_parts(self) -> (Child, ChildStdin) {
let mut child = self.into_inner();
let stdin = child.stdin.take().expect("piped stdin");
(child, stdin)
}
}
impl std::ops::Deref for StdChild {
type Target = Child;
fn deref(&self) -> &Child {
self.0.as_ref().expect("the child is present until into_inner")
}
}
impl std::ops::DerefMut for StdChild {
fn deref_mut(&mut self) -> &mut Child {
self.0.as_mut().expect("the child is present until into_inner")
}
}
impl Drop for StdChild {
fn drop(&mut self) {
let Some(mut child) = self.0.take() else {
return;
};
let panicking = std::thread::panicking();
if let Err(e) = child.kill() {
_ = writeln!(std::io::stderr(), "StdChild: kill: {e}");
debug_assert!(panicking, "kill the std child: {e}");
return;
}
if let Err(e) = child.wait() {
_ = writeln!(std::io::stderr(), "StdChild: wait: {e}");
debug_assert!(panicking, "reap the std child: {e}");
}
}
}
pub(crate) fn blocker() -> StdChild {
blocker_with(|_| {})
}
pub(crate) fn blocker_with(configure: impl FnOnce(&mut Command)) -> StdChild {
let mut cmd = blocker_command();
configure(&mut cmd);
StdChild::spawn(&mut cmd)
}
#[cfg(windows)]
pub(crate) fn blocker_with_flags(
flags: u32,
console: super::Console,
configure: impl FnOnce(&mut Command),
) -> StdChild {
let mut cmd = blocker_command();
configure(&mut cmd);
StdChild::spawn_with(&mut cmd, flags, console)
}
fn blocker_command() -> Command {
let mut cmd = Command::new(super::BLOCKER_ARGV[0]);
cmd.args(&super::BLOCKER_ARGV[1..])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null());
cmd
}