use std::fmt;
use std::io;
use std::process::Command;
use std::sync::Arc;
use std::time::Instant;
use crate::{Group, Scope};
#[derive(Debug)]
pub struct Spawn {
command: Command,
scope: Scope,
}
impl Spawn {
pub fn start(self) -> io::Result<Spawned> {
let started = Instant::now();
let group = Group::start(self.command, self.scope)?;
Ok(Spawned { group, started })
}
}
#[derive(Debug)]
#[must_use = "dropping a started child kills it"]
pub struct Spawned {
group: Group,
started: Instant,
}
impl Spawned {
pub(super) fn into_parts(self) -> (Group, Instant) {
(self.group, self.started)
}
}
#[derive(Clone)]
pub(super) struct AroundSpawn(Hook);
type Hook = Arc<dyn Fn(Spawn) -> io::Result<Spawned> + Send + Sync>;
impl AroundSpawn {
pub(super) fn new(hook: impl Fn(Spawn) -> io::Result<Spawned> + Send + Sync + 'static) -> Self {
Self(Arc::new(hook))
}
}
impl fmt::Debug for AroundSpawn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AroundSpawn(..)")
}
}
pub(super) fn start(
command: Command,
scope: Scope,
hook: Option<&AroundSpawn>,
) -> io::Result<Spawned> {
let spawn = Spawn { command, scope };
match hook {
Some(AroundSpawn(hook)) => hook(spawn),
None => spawn.start(),
}
}