command_error/
try_wait_context.rs

1use std::borrow::Borrow;
2use std::fmt::Debug;
3use std::process::ExitStatus;
4
5#[cfg(doc)]
6use std::process::Child;
7#[cfg(doc)]
8use std::process::Command;
9
10use crate::CommandDisplay;
11use crate::OutputContext;
12
13/// An optional [`ExitStatus`] combined with context about the [`Command`] that produced it.
14///
15/// See also: [`OutputContext`].
16pub struct TryWaitContext {
17    status: Option<ExitStatus>,
18    command: Box<dyn CommandDisplay + Send + Sync>,
19}
20
21impl TryWaitContext {
22    /// Construct a new [`TryWaitContext`].
23    pub fn new(status: Option<ExitStatus>, command: Box<dyn CommandDisplay + Send + Sync>) -> Self {
24        Self { status, command }
25    }
26
27    /// Get the result of the [`Child::try_wait`] call.
28    pub fn status(&self) -> Option<ExitStatus> {
29        self.status
30    }
31
32    /// Get a reference to the command contained in this context object, for use in error messages
33    /// or diagnostics.
34    pub fn command(&self) -> &(dyn CommandDisplay + Send + Sync) {
35        self.command.borrow()
36    }
37
38    /// Get the command contained in this context object, for use in error messages or diagnostics.
39    pub fn into_command(self) -> Box<(dyn CommandDisplay + Send + Sync)> {
40        self.command
41    }
42
43    /// If the [`ExitStatus`] is present, get an [`OutputContext`] for constructing error messages.
44    pub fn into_output_context(self) -> Option<OutputContext<ExitStatus>> {
45        self.status
46            .map(|status| OutputContext::new(status, self.command))
47    }
48}
49
50impl Debug for TryWaitContext {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("TryWaitContext")
53            .field("status", &self.status)
54            .field("command", &self.command.to_string())
55            .finish()
56    }
57}