crumbkit_process/run/
spawn.rs1use std::fmt;
4use std::io;
5use std::process::Command;
6use std::sync::Arc;
7use std::time::Instant;
8
9use crate::{Group, Scope};
10
11#[derive(Debug)]
14pub struct Spawn {
15 command: Command,
16 scope: Scope,
17}
18
19impl Spawn {
20 pub fn start(self) -> io::Result<Spawned> {
27 let started = Instant::now();
28 let group = Group::start(self.command, self.scope)?;
29 Ok(Spawned { group, started })
30 }
31}
32
33#[derive(Debug)]
39#[must_use = "dropping a started child kills it"]
40pub struct Spawned {
41 group: Group,
42 started: Instant,
43}
44
45impl Spawned {
46 pub(super) fn into_parts(self) -> (Group, Instant) {
48 (self.group, self.started)
49 }
50}
51
52#[derive(Clone)]
54pub(super) struct AroundSpawn(Hook);
55
56type Hook = Arc<dyn Fn(Spawn) -> io::Result<Spawned> + Send + Sync>;
58
59impl AroundSpawn {
60 pub(super) fn new(hook: impl Fn(Spawn) -> io::Result<Spawned> + Send + Sync + 'static) -> Self {
62 Self(Arc::new(hook))
63 }
64}
65
66impl fmt::Debug for AroundSpawn {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str("AroundSpawn(..)")
69 }
70}
71
72pub(super) fn start(
74 command: Command,
75 scope: Scope,
76 hook: Option<&AroundSpawn>,
77) -> io::Result<Spawned> {
78 let spawn = Spawn { command, scope };
79 match hook {
80 Some(AroundSpawn(hook)) => hook(spawn),
81 None => spawn.start(),
82 }
83}