use std::{fmt, io, ops::Deref};
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "kind"))]
#[derive(Clone)]
pub enum ProcessItem {
Output(String),
Error(String),
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 {
#[must_use]
pub fn is_output(&self) -> bool {
matches!(self, Self::Output(..))
}
#[must_use]
pub fn is_error(&self) -> bool {
matches!(self, Self::Error(..))
}
#[must_use]
pub fn is_exit(&self) -> bool {
matches!(self, Self::Exit(..))
}
#[must_use]
pub fn is_success(&self) -> Option<bool> {
self.as_exit().map(|s| s.trim() == "0")
}
pub fn as_exit(&self) -> Option<&String> {
if let Self::Exit(v) = self {
Some(v)
} else {
None
}
}
pub fn as_error(&self) -> Option<&String> {
if let Self::Error(v) = self {
Some(v)
} else {
None
}
}
pub fn as_output(&self) -> Option<&String> {
if let Self::Output(v) = self {
Some(v)
} else {
None
}
}
}