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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use std::fmt::Debug;
use std::fmt::Display;
use std::process::Child;
use std::process::ExitStatus;
use std::process::{Command, Output};

use utf8_command::Utf8Output;

use crate::ChildContext;
use crate::Error;
use crate::ExecError;
use crate::OutputContext;
use crate::OutputConversionError;
use crate::OutputLike;
use crate::Utf8ProgramAndArgs;

/// Extension trait for [`Command`].
///
/// [`CommandExt`] methods check the exit status of the command (or perform user-supplied
/// validation logic) and produced detailed, helpful error messages when they fail:
///
/// ```
/// # use indoc::indoc;
/// use std::process::Command;
/// use command_error::CommandExt;
///
/// let err = Command::new("sh")
///     .args(["-c", "echo puppy; false"])
///     .output_checked_utf8()
///     .unwrap_err();
///
/// assert_eq!(
///     err.to_string(),
///     indoc!(
///         "`sh` failed: exit status: 1
///         Command failed: `sh -c 'echo puppy; false'`
///         Stdout:
///           puppy"
///     )
/// );
/// ```
///
/// With the `tracing` feature enabled, commands will be logged before they run.
///
/// # Method overview
///
/// | Method | Output decoding | Errors |
/// | ------ | --------------- | ------ |
/// | [`output_checked`][CommandExt::output_checked`] | Bytes | If non-zero exit code |
/// | [`output_checked_with`][CommandExt::output_checked_with`] | Arbitrary | Custom |
/// | [`output_checked_as`][CommandExt::output_checked_as`] | Arbitrary | Custom, with arbitrary error type |
/// | [`output_checked_utf8`][CommandExt::output_checked_utf8`] | UTF-8 | If non-zero exit code |
/// | [`output_checked_with_utf8`][CommandExt::output_checked_with_utf8`] | UTF-8 | Custom |
/// | [`status_checked`][CommandExt::status_checked`] | None | If non-zero exit code |
/// | [`status_checked_with`][CommandExt::status_checked_with`] | None | Custom |
/// | [`status_checked_as`][CommandExt::status_checked_as`] | None | Custom, with arbitrary error type |
pub trait CommandExt: Sized {
    /// The error type returned from methods on this trait.
    type Error: From<Error>;

    /// The type of child process produced.
    type Child;

    /// Run a command, capturing its output. `succeeded` is called and returned to determine if the
    /// command succeeded.
    ///
    /// See [`Command::output`] for more information.
    ///
    /// This is the most general [`CommandExt`] method, and gives the caller full control over
    /// success logic and the output and errors produced.
    ///
    /// ```
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::Output;
    /// # use command_error::CommandExt;
    /// # use command_error::OutputContext;
    /// # mod serde_json {
    /// #     /// Teehee!
    /// #     pub fn from_slice(_input: &[u8]) -> Result<Vec<String>, String> {
    /// #         Err("EOF while parsing a list at line 4 column 11".into())
    /// #     }
    /// # }
    /// let err = Command::new("cat")
    ///     .arg("tests/data/incomplete.json")
    ///     .output_checked_as(|context: OutputContext<Output>| {
    ///         serde_json::from_slice(&context.output().stdout)
    ///             .map_err(|err| context.error_msg(err))
    ///     })
    ///     .unwrap_err();
    ///
    /// assert_eq!(
    ///     err.to_string(),
    ///     indoc!(
    ///         r#"`cat` failed: EOF while parsing a list at line 4 column 11
    ///         exit status: 0
    ///         Command failed: `cat tests/data/incomplete.json`
    ///         Stdout:
    ///           [
    ///               "cuppy",
    ///               "dog",
    ///               "city","#
    ///     )
    /// );
    /// ```
    ///
    /// Note that the closure takes the output as raw bytes but the error message contains the
    /// output decoded as UTF-8. In this example, the decoding only happens in the error case, but
    /// if you request an [`OutputContext<Utf8Output>`], the decoded data will be reused for the
    /// error message.
    ///
    /// The [`OutputContext`] passed to the closure contains information about the command's
    /// [`Output`] (including its [`ExitStatus`]), the command that ran (the program name and its
    /// arguments), and methods for constructing detailed error messages (with or without
    /// additional context information).
    #[track_caller]
    fn output_checked_as<O, R, E>(
        &mut 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,
        E: From<Self::Error>;

    /// Run a command, 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.
    ///
    /// This method is best if you want to consider a command successful if it has a non-zero exit
    /// code, or if its output contains some special string. If you'd like to additionally produce
    /// output that can't be produced with [`TryFrom<Output>`] (such as to deserialize a data
    /// structure), [`CommandExt::output_checked_as`] provides full control over the produced
    /// result.
    ///
    /// See [`Command::output`] for more information.
    ///
    /// ```
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::Output;
    /// # use command_error::CommandExt;
    /// let output = Command::new("sh")
    ///     .args(["-c", "echo puppy && exit 2"])
    ///     .output_checked_with(|output: &Output| {
    ///         if let Some(2) = output.status.code() {
    ///             Ok(())
    ///         } else {
    ///             // Don't add any additional context to the error message:
    ///             Err(None::<String>)
    ///         }
    ///     })
    ///     .unwrap();
    ///
    /// assert_eq!(
    ///     output.status.code(),
    ///     Some(2),
    /// );
    /// ```
    ///
    /// Note that due to the generic error parameter, you'll need to annotate [`None`] return
    /// values with a [`Display`]able type — try [`String`] or any [`std::error::Error`] type in
    /// scope.
    ///
    /// [`Command::output_checked_with`] can also be used to convert the output to any type that
    /// implements [`TryFrom<Output>`] before running `succeeded`:
    ///
    /// ```
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use command_error::CommandExt;
    /// # use utf8_command::Utf8Output;
    /// let err = Command::new("sh")
    ///     .args(["-c", "echo kitty && kill -9 \"$$\""])
    ///     .output_checked_with(|output: &Utf8Output| {
    ///         if output.status.success() && output.stdout.trim() == "puppy" {
    ///             Ok(())
    ///         } else {
    ///             Err(Some("didn't find any puppy!"))
    ///         }
    ///     })
    ///     .unwrap_err();
    ///
    /// assert_eq!(
    ///     err.to_string(),
    ///     indoc!(
    ///         r#"`sh` failed: didn't find any puppy!
    ///         signal: 9 (SIGKILL)
    ///         Command failed: `sh -c 'echo kitty && kill -9 "$$"'`
    ///         Stdout:
    ///           kitty"#
    ///     )
    /// );
    /// ```
    #[track_caller]
    fn output_checked_with<O, E>(
        &mut 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,
        O: 'static,
        E: Debug,
        E: Display,
        E: '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()),
        })
    }

    /// Run a command, capturing its output. If the command exits with a non-zero exit code, an
    /// error is raised.
    ///
    /// Error messages are detailed and contain information about the command that was run and its
    /// output:
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use command_error::CommandExt;
    /// let err = Command::new("ooby-gooby")
    ///     .output_checked()
    ///     .unwrap_err();
    ///
    /// assert_eq!(
    ///     err.to_string(),
    ///     "Failed to execute `ooby-gooby`: No such file or directory (os error 2)"
    /// );
    ///
    /// let err = Command::new("sh")
    ///     .args(["-c", "echo puppy && exit 1"])
    ///     .output_checked()
    ///     .unwrap_err();
    /// assert_eq!(
    ///     err.to_string(),
    ///     indoc!(
    ///         "`sh` failed: exit status: 1
    ///         Command failed: `sh -c 'echo puppy && exit 1'`
    ///         Stdout:
    ///           puppy"
    ///     )
    /// );
    /// ```
    ///
    /// If the command fails, output will be decoded as UTF-8 for display in error messages, but
    /// otherwise no output decoding is performed. To decode output as UTF-8, use
    /// [`CommandExt::output_checked_utf8`]. To decode as other formats, use
    /// [`CommandExt::output_checked_with`].
    ///
    /// See [`Command::output`] for more information.
    #[track_caller]
    fn output_checked(&mut self) -> Result<Output, Self::Error> {
        self.output_checked_with(|output: &Output| {
            if output.status.success() {
                Ok(())
            } else {
                Err(None::<String>)
            }
        })
    }

    /// Run a command, capturing its output and decoding it as UTF-8. If the command exits with a
    /// non-zero exit code or if its output contains invalid UTF-8, an error is raised.
    ///
    /// See [`CommandExt::output_checked`] and [`Command::output`] for more information.
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::ExitStatus;
    /// # use command_error::CommandExt;
    /// # use utf8_command::Utf8Output;
    /// let output = Command::new("echo")
    ///     .arg("puppy")
    ///     .output_checked_utf8()
    ///     .unwrap();
    ///
    /// assert_eq!(
    ///     output,
    ///     Utf8Output {
    ///         status: ExitStatus::default(),
    ///         stdout: "puppy\n".into(),
    ///         stderr: "".into(),
    ///     },
    /// );
    /// ```
    #[track_caller]
    fn output_checked_utf8(&mut self) -> Result<Utf8Output, Self::Error> {
        self.output_checked_with_utf8(|output| {
            if output.status.success() {
                Ok(())
            } else {
                Err(None::<String>)
            }
        })
    }

    /// Run a command, 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`] and [`Command::output`] for more information.
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::ExitStatus;
    /// # use command_error::CommandExt;
    /// # use utf8_command::Utf8Output;
    /// let output = Command::new("sh")
    ///     .args(["-c", "echo puppy; exit 1"])
    ///     .output_checked_with_utf8(|output| {
    ///         if output.stdout.contains("puppy") {
    ///             Ok(())
    ///         } else {
    ///             Err(None::<String>)
    ///         }
    ///     })
    ///     .unwrap();
    ///
    /// assert_eq!(output.stdout, "puppy\n");
    /// assert_eq!(output.status.code(), Some(1));
    /// ```
    #[track_caller]
    fn output_checked_with_utf8<E>(
        &mut self,
        succeeded: impl Fn(&Utf8Output) -> Result<(), Option<E>>,
    ) -> Result<Utf8Output, Self::Error>
    where
        E: Display,
        E: Debug,
        E: 'static,
    {
        self.output_checked_with(succeeded)
    }

    /// Run a command without capturing its output. `succeeded` is called and returned to determine
    /// if the command succeeded.
    ///
    /// This gives the caller full control over success logic and the output and errors produced.
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::ExitStatus;
    /// # use command_error::CommandExt;
    /// # use command_error::OutputContext;
    /// let succeeded = |context: OutputContext<ExitStatus>| {
    ///     match context.status().code() {
    ///         Some(code) => Ok(code),
    ///         None => Err(context.error_msg("no exit code")),
    ///     }
    /// };
    ///
    /// let code = Command::new("true")
    ///     .status_checked_as(succeeded)
    ///     .unwrap();
    /// assert_eq!(code, 0);
    ///
    /// let err = Command::new("sh")
    ///     .args(["-c", "kill \"$$\""])
    ///     .status_checked_as(succeeded)
    ///     .unwrap_err();
    /// assert_eq!(
    ///     err.to_string(),
    ///     indoc!(
    ///         r#"`sh` failed: no exit code
    ///         signal: 15 (SIGTERM)
    ///         Command failed: `sh -c 'kill "$$"'`"#
    ///     )
    /// );
    /// ```
    ///
    /// To error on non-zero exit codes, use [`CommandExt::status_checked`].
    ///
    /// See [`Command::status`] for more information.
    #[track_caller]
    fn status_checked_as<R, E>(
        &mut self,
        succeeded: impl Fn(OutputContext<ExitStatus>) -> Result<R, E>,
    ) -> Result<R, E>
    where
        E: From<Self::Error>;

    /// Run a command without 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.
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::ExitStatus;
    /// # use command_error::CommandExt;
    /// # use command_error::OutputContext;
    /// let status = Command::new("false")
    ///     .status_checked_with(|status| {
    ///         match status.code() {
    ///             // Exit codes 0 and 1 are OK.
    ///             Some(0) | Some(1) => Ok(()),
    ///             // Other exit codes are errors.
    ///             _ => Err(None::<String>)
    ///         }
    ///     })
    ///     .unwrap();
    /// assert_eq!(status.code(), Some(1));
    /// ```
    ///
    /// See [`Command::status`] for more information.
    #[track_caller]
    fn status_checked_with<E>(
        &mut self,
        succeeded: impl Fn(ExitStatus) -> Result<(), Option<E>>,
    ) -> Result<ExitStatus, Self::Error>
    where
        E: Debug,
        E: Display,
        E: 'static,
    {
        self.status_checked_as(|status| match succeeded(status.status()) {
            Ok(()) => Ok(status.status()),
            Err(user_error) => Err(status.maybe_error_msg(user_error).into()),
        })
    }

    /// Run a command without capturing its output. If the command exits with a non-zero status
    /// code, an error is raised containing information about the command that was run:
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::ExitStatus;
    /// # use command_error::CommandExt;
    /// let err = Command::new("sh")
    ///     .args(["-c", "exit 1"])
    ///     .status_checked()
    ///     .unwrap_err();
    ///
    /// assert_eq!(
    ///     err.to_string(),
    ///     indoc!(
    ///         "`sh` failed: exit status: 1
    ///         Command failed: `sh -c 'exit 1'`"
    ///     )
    /// );
    /// ```
    ///
    /// See [`Command::status`] for more information.
    #[track_caller]
    fn status_checked(&mut self) -> Result<ExitStatus, Self::Error> {
        self.status_checked_with(|status| {
            if status.success() {
                Ok(())
            } else {
                Err(None::<String>)
            }
        })
    }

    /// Spawn a command.
    ///
    /// The returned child contains context information about the command that produced it, which
    /// can be used to produce detailed error messages if the child process fails.
    ///
    /// See [`Command::spawn`] for more information.
    ///
    /// ```
    /// # use pretty_assertions::assert_eq;
    /// # use indoc::indoc;
    /// # use std::process::Command;
    /// # use std::process::ExitStatus;
    /// # use command_error::CommandExt;
    /// let err = Command::new("ooga booga")
    ///     .spawn_checked()
    ///     .unwrap_err();
    ///
    /// assert_eq!(
    ///     err.to_string(),
    ///     "Failed to execute `'ooga booga'`: No such file or directory (os error 2)"
    /// );
    /// ```
    #[track_caller]
    fn spawn_checked(&mut self) -> Result<Self::Child, Self::Error>;

    /// 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 command and arguments shell-quoted.
    fn log(&self) -> Result<(), Self::Error>;
}

impl CommandExt for Command {
    type Error = Error;
    type Child = ChildContext<Child>;

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

    fn output_checked_as<O, R, E>(
        &mut 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,
        E: From<Self::Error>,
    {
        self.log()?;
        let displayed: Utf8ProgramAndArgs = (&*self).into();
        match self.output() {
            Ok(output) => match output.try_into() {
                Ok(output) => succeeded(OutputContext {
                    output,
                    command: Box::new(displayed),
                }),
                Err(error) => Err(Error::from(OutputConversionError {
                    command: Box::new(displayed),
                    inner: Box::new(error),
                })
                .into()),
            },
            Err(inner) => Err(Error::from(ExecError {
                command: Box::new(displayed),
                inner,
            })
            .into()),
        }
    }

    fn status_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 displayed: Utf8ProgramAndArgs = (&*self).into();
        let displayed = Box::new(displayed);
        match self.status() {
            Ok(status) => succeeded(OutputContext {
                output: status,
                command: displayed,
            }),
            Err(inner) => Err(Error::from(ExecError {
                command: displayed,
                inner,
            })
            .into()),
        }
    }

    fn spawn_checked(&mut self) -> Result<Self::Child, Self::Error> {
        let displayed: Utf8ProgramAndArgs = (&*self).into();
        match self.spawn() {
            Ok(child) => Ok(ChildContext {
                child,
                command: Box::new(displayed),
            }),
            Err(inner) => Err(Error::from(ExecError {
                command: Box::new(displayed),
                inner,
            })),
        }
    }
}