command_group/stdlib/
erased.rs

1use std::{
2	io::Result,
3	process::{Child, ExitStatus, Output},
4};
5
6use super::GroupChild;
7
8/// Wrapper around a process child, be it grouped or ungrouped.
9///
10/// This is a helper which erases that a [`std::process::Child`] is a different type than a
11/// [`GroupChild`]. It forwards to the corresponding method on the inner type.
12#[derive(Debug)]
13pub enum ErasedChild {
14	/// A grouped process child.
15	Grouped(GroupChild),
16
17	/// An ungrouped process child.
18	Ungrouped(Child),
19}
20
21impl ErasedChild {
22	/// Returns the OS-assigned process (group) identifier.
23	///
24	/// - Grouped: [`GroupChild::id`]
25	/// - Ungrouped: [`Child::id`]
26	pub fn id(&mut self) -> u32 {
27		match self {
28			Self::Grouped(c) => c.id(),
29			Self::Ungrouped(c) => c.id(),
30		}
31	}
32
33	/// Forces the child to exit.
34	///
35	/// - Grouped: [`GroupChild::kill`]
36	/// - Ungrouped: [`Child::kill`]
37	pub fn kill(&mut self) -> Result<()> {
38		match self {
39			Self::Grouped(c) => c.kill(),
40			Self::Ungrouped(c) => c.kill(),
41		}
42	}
43
44	/// Attempts to collect the exit status of the child if it has already exited.
45	///
46	/// - Grouped: [`GroupChild::try_wait`]
47	/// - Ungrouped: [`Child::try_wait`]
48	pub fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
49		match self {
50			Self::Grouped(c) => c.try_wait(),
51			Self::Ungrouped(c) => c.try_wait(),
52		}
53	}
54
55	/// Waits for the process to exit, and returns its exit status.
56	///
57	/// - Grouped: [`GroupChild::wait`]
58	/// - Ungrouped: [`Child::wait`]
59	pub fn wait(&mut self) -> Result<ExitStatus> {
60		match self {
61			Self::Grouped(c) => c.wait(),
62			Self::Ungrouped(c) => c.wait(),
63		}
64	}
65
66	/// Waits for the process to exit, and returns its exit status.
67	///
68	/// - Grouped: [`GroupChild::wait_with_output`]
69	/// - Ungrouped: [`Child::wait_with_output`]
70	pub fn wait_with_output(self) -> Result<Output> {
71		match self {
72			Self::Grouped(c) => c.wait_with_output(),
73			Self::Ungrouped(c) => c.wait_with_output(),
74		}
75	}
76
77	/// Sends a Unix signal to the process.
78	///
79	/// - Grouped: [`GroupChild::signal`]
80	/// - Ungrouped: [`Child::signal`]
81	#[cfg(unix)]
82	pub fn signal(&self, sig: crate::Signal) -> Result<()> {
83		use crate::UnixChildExt;
84
85		match self {
86			Self::Grouped(c) => c.signal(sig),
87			Self::Ungrouped(c) => c.signal(sig),
88		}
89	}
90}