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
use std::{fmt, io, ops::Deref};

/// [`crate::Process`] stream output
pub enum ProcessItem {
    /// A stdout chunk printed by the process.
    Output(String),
    /// A stderr chunk printed by the process or internal error message
    Error(String),
    /// Indication that the process exit successful
    Exit(String),
}

impl Deref for ProcessItem {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        match self {
            ProcessItem::Output(s) => s,
            ProcessItem::Error(s) => s,
            ProcessItem::Exit(s) => s,
        }
    }
}

impl fmt::Display for ProcessItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl fmt::Debug for ProcessItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Output(out) => write!(f, "[Output] {out}"),
            Self::Error(err) => write!(f, "[Error] {err}"),
            Self::Exit(code) => write!(f, "[Exit] {code}"),
        }
    }
}
impl From<(bool, io::Result<String>)> for ProcessItem {
    fn from(v: (bool, io::Result<String>)) -> Self {
        match v.1 {
            Ok(line) if v.0 => Self::Output(line),
            Ok(line) => Self::Error(line),
            Err(e) => Self::Error(e.to_string()),
        }
    }
}

impl ProcessItem {
    /// Returns `true` if the process item is [`Output`].
    ///
    /// [`Output`]: ProcessItem::Output
    #[must_use]
    pub fn is_output(&self) -> bool {
        matches!(self, Self::Output(..))
    }

    /// Returns `true` if the process item is [`Error`].
    ///
    /// [`Error`]: ProcessItem::Error
    #[must_use]
    pub fn is_error(&self) -> bool {
        matches!(self, Self::Error(..))
    }

    /// Returns `true` if the process item is [`Exit`].
    ///
    /// [`Exit`]: ProcessItem::Exit
    #[must_use]
    pub fn is_exit(&self) -> bool {
        matches!(self, Self::Exit(..))
    }

    /// Return exit code if [`ProcessItem`] is [`ProcessItem::Exit`]
    pub fn as_exit(&self) -> Option<&String> {
        if let Self::Exit(v) = self {
            Some(v)
        } else {
            None
        }
    }

    /// Return inner reference [`String`] value if [`ProcessItem`] is [`ProcessItem::Error`]
    pub fn as_error(&self) -> Option<&String> {
        if let Self::Error(v) = self {
            Some(v)
        } else {
            None
        }
    }

    /// Return inner reference [`String`] value if [`ProcessItem`] is [`ProcessItem::Output`]
    pub fn as_output(&self) -> Option<&String> {
        if let Self::Output(v) = self {
            Some(v)
        } else {
            None
        }
    }
}