command_error/
output_like.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
use std::borrow::Cow;
use std::process::ExitStatus;
use std::process::Output;

use utf8_command::Utf8Output;

/// A command output type.
pub trait OutputLike {
    /// The command's exit status.
    fn status(&self) -> ExitStatus;

    /// The command's stdout, decoded to UTF-8 on a best-effort basis.
    fn stdout(&self) -> Cow<'_, str>;

    /// The command's stderr, decoded to UTF-8 on a best-effort basis.
    fn stderr(&self) -> Cow<'_, str>;
}

/// A trivial implementation with empty output.
impl OutputLike for ExitStatus {
    fn status(&self) -> ExitStatus {
        *self
    }

    fn stdout(&self) -> Cow<'_, str> {
        Cow::Borrowed("")
    }

    fn stderr(&self) -> Cow<'_, str> {
        Cow::Borrowed("")
    }
}

impl OutputLike for Output {
    fn status(&self) -> ExitStatus {
        self.status
    }

    fn stdout(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.stdout)
    }

    fn stderr(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.stderr)
    }
}

impl OutputLike for Utf8Output {
    fn status(&self) -> ExitStatus {
        self.status
    }

    fn stdout(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.stdout)
    }

    fn stderr(&self) -> Cow<'_, str> {
        Cow::Borrowed(&self.stderr)
    }
}