command_error/
child_context.rs

1use std::borrow::Borrow;
2use std::fmt::Debug;
3
4#[cfg(doc)]
5use std::process::Child;
6#[cfg(doc)]
7use std::process::Command;
8
9#[cfg(doc)]
10use crate::ChildExt;
11use crate::CommandDisplay;
12#[cfg(doc)]
13use crate::OutputContext;
14
15/// A [`Child`] process combined with context about the [`Command`] that produced it.
16///
17/// The context information stored in this type is used to produce diagnostics in [`ChildExt`].
18///
19/// See: [`OutputContext`].
20pub struct ChildContext<C> {
21    child: C,
22    command: Box<dyn CommandDisplay + Send + Sync>,
23}
24
25impl<C> ChildContext<C> {
26    /// Construct a new [`ChildContext`].
27    pub fn new(child: C, command: Box<dyn CommandDisplay + Send + Sync>) -> Self {
28        Self { child, command }
29    }
30
31    /// Get the child process.
32    pub fn into_child(self) -> C {
33        self.child
34    }
35
36    /// Get a reference to the child process.
37    pub fn child(&self) -> &C {
38        &self.child
39    }
40
41    /// Get a mutable reference to the child process.
42    pub fn child_mut(&mut self) -> &mut C {
43        &mut self.child
44    }
45
46    /// Get a reference to the command which produced this child process.
47    pub fn command(&self) -> &(dyn CommandDisplay + Send + Sync + 'static) {
48        self.command.borrow()
49    }
50
51    /// Get a reference to the [`Box`] containing the command which produced this child process.
52    ///
53    /// This value, unlike the return value from [`ChildContext::command`], can be [`Clone`]d.
54    #[expect(clippy::borrowed_box)]
55    pub fn command_boxed(&self) -> &Box<dyn CommandDisplay + Send + Sync> {
56        &self.command
57    }
58
59    /// Get the child and command which produced the child.
60    pub fn into_child_and_command(self) -> (C, Box<dyn CommandDisplay + Send + Sync>) {
61        (self.child, self.command)
62    }
63}
64
65impl<C> Debug for ChildContext<C>
66where
67    C: Debug,
68{
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.debug_struct("ChildContext")
71            .field("child", &self.child)
72            .field("command", &self.command.to_string())
73            .finish()
74    }
75}