use super::Reads;
pub(super) fn split_nul_paths(stdout: &[u8]) -> Option<Vec<String>> {
stdout
.split(|byte| *byte == 0)
.filter(|record| !record.is_empty())
.map(|record| String::from_utf8(record.to_vec()).ok())
.collect()
}
#[derive(Debug)]
pub(in crate::cli) struct Reply {
pub(super) code: Option<i32>,
pub(super) stdout: Vec<u8>,
pub(super) stderr: Vec<u8>,
}
impl Reply {
pub(super) fn succeeded(&self) -> bool {
self.code == Some(0)
}
pub(super) fn spoke(&self, reads: Reads) -> bool {
match reads {
Reads::Text => !String::from_utf8_lossy(&self.stdout).trim().is_empty(),
Reads::Paths => self
.stdout
.split(|byte| *byte == 0)
.any(|record| !record.is_empty()),
}
}
pub(super) fn said_no(&self) -> bool {
self.code == Some(1) && self.stdout.is_empty() && self.stderr.is_empty()
}
pub(super) fn diagnostic(&self) -> Option<String> {
let wrote = |bytes: &[u8]| {
let text = oakum::discover::child::said(bytes);
(!text.is_empty()).then_some(text)
};
wrote(&self.stderr).or_else(|| (!self.succeeded()).then(|| wrote(&self.stdout)).flatten())
}
pub(super) fn detail(&self) -> String {
let status = match self.code {
Some(code) => format!("exit {code}"),
None => String::from("terminated by a signal"),
};
match self.diagnostic() {
Some(said) => format!("{status}: {said}"),
None => format!("{status} with no diagnostic"),
}
}
}
impl From<std::process::Output> for Reply {
fn from(output: std::process::Output) -> Self {
Self {
code: output.status.code(),
stdout: output.stdout,
stderr: output.stderr,
}
}
}
#[cfg(test)]
impl Reply {
pub(in crate::cli) fn said(stdout: impl Into<Vec<u8>>) -> Self {
Self {
code: Some(0),
stdout: stdout.into(),
stderr: Vec::new(),
}
}
pub(in crate::cli) fn absent() -> Self {
Self {
code: Some(1),
stdout: Vec::new(),
stderr: Vec::new(),
}
}
pub(in crate::cli) fn warned(stderr: &str) -> Self {
Self {
code: Some(0),
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
}
}
pub(in crate::cli) fn said_and_warned(stdout: impl Into<Vec<u8>>, stderr: &str) -> Self {
Self {
code: Some(0),
stdout: stdout.into(),
stderr: stderr.as_bytes().to_vec(),
}
}
pub(in crate::cli) fn failed(code: i32, stderr: &str) -> Self {
assert!(
code != 0,
"a failure exits non-zero; exit 0 is `said` or `warned`"
);
assert!(
!stderr.is_empty(),
"a diagnosed failure writes a diagnostic; exit 1 with nothing written is `absent`"
);
Self {
code: Some(code),
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
}
}
pub(in crate::cli) fn exactly(code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> Self {
Self {
code,
stdout: stdout.to_vec(),
stderr: stderr.to_vec(),
}
}
pub(in crate::cli) fn was_signalled() -> Self {
Self {
code: None,
stdout: Vec::new(),
stderr: Vec::new(),
}
}
}