Skip to main content

crumbkit_process/run/
spawn.rs

1//! The hook around the start of a run's child.
2
3use std::fmt;
4use std::io;
5use std::process::Command;
6use std::sync::Arc;
7use std::time::Instant;
8
9use crate::{Group, Scope};
10
11/// The start of one run's child, which a hook set with
12/// [`RunOptions::around_spawn`](crate::RunOptions::around_spawn) receives.
13#[derive(Debug)]
14pub struct Spawn {
15    command: Command,
16    scope: Scope,
17}
18
19impl Spawn {
20    /// Starts the child.
21    ///
22    /// # Errors
23    ///
24    /// Returns the error of the start, as [`RunError::Start`](crate::RunError::Start)
25    /// describes it.
26    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/// A child that [`Spawn::start`] started, which a hook returns to the run.
34///
35/// Only [`Spawn::start`] makes this value, so a hook that returns `Ok` has
36/// started the child. Dropping it kills the child and every process in its
37/// scope and reaps the child.
38#[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    /// Returns the child and the time just before it started.
47    pub(super) fn into_parts(self) -> (Group, Instant) {
48        (self.group, self.started)
49    }
50}
51
52/// A hook around the start of a run's child.
53#[derive(Clone)]
54pub(super) struct AroundSpawn(Hook);
55
56/// The caller's function, which threads of a run share with the settings.
57type Hook = Arc<dyn Fn(Spawn) -> io::Result<Spawned> + Send + Sync>;
58
59impl AroundSpawn {
60    /// Wraps the caller's function.
61    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
72/// Starts `command` in `scope`, through `hook` when the run has one.
73pub(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}