command_error/
child_ext.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use std::borrow::Borrow;
use std::fmt::Debug;
use std::fmt::Display;
use std::process::Child;
use std::process::ExitStatus;
use std::process::Output;

use utf8_command::Utf8Output;

use crate::ChildContext;
#[cfg(doc)]
use crate::CommandExt;

use crate::Error;
use crate::ExecError;
use crate::OutputContext;
use crate::OutputConversionError;
use crate::OutputLike;
use crate::TryWaitContext;
use crate::WaitError;

/// Checked methods for [`Child`] processes.
///
/// This trait is largely the same as [`CommandExt`], with the difference that the
/// [`ChildExt::output_checked`] methods take `self` as an owned parameter and the
/// [`CommandExt::output_checked`] methods take `self` as a mutable reference.
///
/// Additionally, methods that return an [`ExitStatus`] are named
/// [`wait_checked`][`ChildExt::wait_checked`] instead of
/// [`status_checked`][`CommandExt::status_checked`], to match the method names on [`Child`].
pub trait ChildExt: Sized {
    /// The error type returned from methods on this trait.
    type Error: From<Error>;

    /// Wait for the process to complete, capturing its output. `succeeded` is called and returned
    /// to determine if the command succeeded.
    ///
    /// See [`CommandExt::output_checked_as`] for more information.
    #[track_caller]
    fn output_checked_as<O, R, E>(
        self,
        succeeded: impl Fn(OutputContext<O>) -> Result<R, E>,
    ) -> Result<R, E>
    where
        O: Debug,
        O: OutputLike,
        O: 'static,
        O: TryFrom<Output>,
        <O as TryFrom<Output>>::Error: Display + Send + Sync,
        E: From<Self::Error>;

    /// Wait for the process to complete, capturing its output. `succeeded` is called and used to
    /// determine if the command succeeded and (optionally) to add an additional message to the error returned.
    ///
    /// See [`CommandExt::output_checked_with`] and [`Child::wait_with_output`] for more information.
    #[track_caller]
    fn output_checked_with<O, E>(
        self,
        succeeded: impl Fn(&O) -> Result<(), Option<E>>,
    ) -> Result<O, Self::Error>
    where
        O: Debug,
        O: OutputLike,
        O: TryFrom<Output>,
        <O as TryFrom<Output>>::Error: Display + Send + Sync,
        O: Send + Sync + 'static,
        E: Debug,
        E: Display,
        E: Send + Sync + 'static,
    {
        self.output_checked_as(|context| match succeeded(context.output()) {
            Ok(()) => Ok(context.into_output()),
            Err(user_error) => Err(context.maybe_error_msg(user_error).into()),
        })
    }

    /// Wait for the process to complete, capturing its output. If the command exits with a
    /// non-zero exit code, an error is raised.
    ///
    /// See [`CommandExt::output_checked`] and [`Child::wait_with_output`] for more information.
    #[track_caller]
    fn output_checked(self) -> Result<Output, Self::Error> {
        self.output_checked_with(|output: &Output| {
            if output.status.success() {
                Ok(())
            } else {
                Err(None::<String>)
            }
        })
    }

    /// Wait for the process to exit, capturing its output and decoding it as UTF-8. If the command
    /// exits with a non-zero exit code, an error is raised.
    ///
    /// See [`CommandExt::output_checked_utf8`] and [`Child::wait_with_output`] for more information.
    #[track_caller]
    fn output_checked_utf8(self) -> Result<Utf8Output, Self::Error> {
        self.output_checked_with_utf8(|output| {
            if output.status.success() {
                Ok(())
            } else {
                Err(None::<String>)
            }
        })
    }

    /// Wait for the process to exit, capturing its output and decoding it as UTF-8. `succeeded` is
    /// called and used to determine if the command succeeded and (optionally) to add an additional
    /// message to the error returned.
    ///
    /// See [`CommandExt::output_checked_with_utf8`] and [`Child::wait_with_output`] for more information.
    #[track_caller]
    fn output_checked_with_utf8<E>(
        self,
        succeeded: impl Fn(&Utf8Output) -> Result<(), Option<E>>,
    ) -> Result<Utf8Output, Self::Error>
    where
        E: Display,
        E: Debug,
        E: Send + Sync + 'static,
    {
        self.output_checked_with(succeeded)
    }

    /// Check if the process has exited.
    ///
    /// The `succeeded` closure is called and returned to determine the result.
    ///
    /// Errors while attempting to retrieve the process's exit status are returned as
    /// [`WaitError`]s.
    ///
    /// See [`Child::try_wait`] for more information.
    #[track_caller]
    fn try_wait_checked_as<R, E>(
        &mut self,
        succeeded: impl Fn(TryWaitContext) -> Result<R, E>,
    ) -> Result<R, E>
    where
        E: From<Self::Error>;

    /// Check if the process has exited and, if it failed, return an error.
    ///
    /// Errors while attempting to retrieve the process's exit status are transformed into
    /// [`WaitError`]s.
    ///
    /// See [`Child::try_wait`] for more information.
    #[track_caller]
    fn try_wait_checked(&mut self) -> Result<Option<ExitStatus>, Self::Error> {
        self.try_wait_checked_as(|context| match context.into_output_context() {
            Some(context) => {
                if context.status().success() {
                    Ok(Some(context.status()))
                } else {
                    Err(context.error().into())
                }
            }
            None => Ok(None),
        })
    }

    /// Wait for the process to exit. `succeeded` is called and returned to determine
    /// if the command succeeded.
    ///
    /// See [`CommandExt::status_checked_as`] and [`Child::wait`] for more information.
    #[track_caller]
    fn wait_checked_as<R, E>(
        &mut self,
        succeeded: impl Fn(OutputContext<ExitStatus>) -> Result<R, E>,
    ) -> Result<R, E>
    where
        E: From<Self::Error>;

    /// Wait for the process to exit. `succeeded` is called and used to determine
    /// if the command succeeded and (optionally) to add an additional message to the error
    /// returned.
    ///
    /// See [`CommandExt::status_checked_with`] and [`Child::wait`] for more information.
    #[track_caller]
    fn wait_checked_with<E>(
        &mut self,
        succeeded: impl Fn(ExitStatus) -> Result<(), Option<E>>,
    ) -> Result<ExitStatus, Self::Error>
    where
        E: Debug,
        E: Display,
        E: Send + Sync + 'static,
    {
        self.wait_checked_as(|context| match succeeded(context.status()) {
            Ok(()) => Ok(context.status()),
            Err(user_error) => Err(context.maybe_error_msg(user_error).into()),
        })
    }

    /// Wait for the process to exit. If the command exits with a non-zero status
    /// code, an error is raised containing information about the command that was run.
    ///
    /// See [`CommandExt::status_checked`] and [`Child::wait`] for more information.
    #[track_caller]
    fn wait_checked(&mut self) -> Result<ExitStatus, Self::Error> {
        self.wait_checked_with(|status| {
            if status.success() {
                Ok(())
            } else {
                Err(None::<String>)
            }
        })
    }

    /// Log the command that will be run.
    ///
    /// With the `tracing` feature enabled, this will emit a debug-level log with message
    /// `Executing command` and a `command` field containing the displayed command (by default,
    /// shell-quoted).
    fn log(&self) -> Result<(), Self::Error>;
}

impl ChildExt for ChildContext<Child> {
    type Error = Error;

    fn output_checked_as<O, R, E>(
        self,
        succeeded: impl Fn(OutputContext<O>) -> Result<R, E>,
    ) -> Result<R, E>
    where
        O: Debug,
        O: OutputLike,
        O: 'static,
        O: TryFrom<Output>,
        <O as TryFrom<Output>>::Error: Display + Send + Sync,
        E: From<Self::Error>,
    {
        self.log()?;
        let command = dyn_clone::clone_box(self.command.borrow());
        match self.child.wait_with_output() {
            Ok(output) => match output.try_into() {
                Ok(output) => succeeded(OutputContext { output, command }),
                Err(error) => Err(Error::from(OutputConversionError {
                    command,
                    inner: Box::new(error),
                })
                .into()),
            },
            Err(inner) => Err(Error::from(ExecError { command, inner }).into()),
        }
    }

    fn try_wait_checked_as<R, E>(
        &mut self,
        succeeded: impl Fn(TryWaitContext) -> Result<R, E>,
    ) -> Result<R, E>
    where
        E: From<Self::Error>,
    {
        let command = dyn_clone::clone_box(self.command.borrow());
        match self.child.try_wait() {
            Ok(status) => succeeded(TryWaitContext { status, command }),
            Err(inner) => Err(Error::from(WaitError { inner, command }).into()),
        }
    }

    fn wait_checked_as<R, E>(
        &mut self,
        succeeded: impl Fn(OutputContext<ExitStatus>) -> Result<R, E>,
    ) -> Result<R, E>
    where
        E: From<Self::Error>,
    {
        self.log()?;
        let command = dyn_clone::clone_box(self.command.borrow());
        match self.child.wait() {
            Ok(status) => succeeded(OutputContext {
                output: status,
                command,
            }),
            Err(inner) => Err(Error::from(ExecError { command, inner }).into()),
        }
    }

    fn log(&self) -> Result<(), Self::Error> {
        #[cfg(feature = "tracing")]
        {
            tracing::debug!(command = %self.command, "Executing command");
        }
        Ok(())
    }
}