use crate::error::{Error, Result};
use crate::history::{LastRun, last_run};
use crate::ports::{ContentStore, RunHistory};
use crate::types::{Digest, Label};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shown {
pub last: LastRun,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
}
pub fn log<H: RunHistory, C: ContentStore>(history: &H, cas: &C, label: &Label) -> Result<Shown> {
let last = last_run(&history.lines()?, label)?;
let stdout = read(cas, last.run.stdout.as_ref(), label)?;
let stderr = read(cas, last.run.stderr.as_ref(), label)?;
Ok(Shown {
last,
stdout,
stderr,
})
}
fn read<C: ContentStore>(cas: &C, digest: Option<&Digest>, label: &Label) -> Result<Vec<u8>> {
digest
.map(|digest| cas.get(digest))
.transpose()?
.flatten()
.ok_or_else(|| Error::MissingOutput {
label: label.clone(),
})
}
#[cfg(test)]
mod tests {
#![expect(
clippy::unwrap_used,
reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
)]
use super::read;
use crate::error::{Error, PortName, Result};
use crate::ports::ContentStore;
use crate::types::{Diagnostic, Digest, FileMode, Label, OutputPath};
struct OneBlob(Vec<u8>);
impl ContentStore for OneBlob {
fn put(&self, _bytes: &[u8]) -> Result<Digest> {
Err(unused())
}
fn contains(&self, digest: &Digest) -> bool {
*digest == Digest::of(&self.0)
}
fn get(&self, digest: &Digest) -> Result<Option<Vec<u8>>> {
Ok(self.contains(digest).then(|| self.0.clone()))
}
fn clear(&self, _at: &OutputPath) -> Result<()> {
Err(unused())
}
fn place(&self, _digest: &Digest, _mode: FileMode, _at: &OutputPath) -> Result<()> {
Err(unused())
}
}
fn unused() -> Error {
Error::Adapter {
port: PortName::ContentStore,
diagnostic: Diagnostic::new("not used by a read"),
}
}
fn label() -> Label {
Label::parse("//:app").unwrap()
}
#[test]
fn a_held_digest_reads_its_bytes() {
let cas = OneBlob(b"out\n".to_vec());
let bytes = read(&cas, Some(&Digest::of(b"out\n")), &label()).unwrap();
assert_eq!(bytes, b"out\n");
}
#[test]
fn a_digest_the_store_does_not_hold_is_missing_output() {
let cas = OneBlob(b"out\n".to_vec());
let err = read(&cas, Some(&Digest::of(b"other")), &label()).unwrap_err();
assert!(matches!(err, Error::MissingOutput { label: named } if named == label()));
}
#[test]
fn no_digest_is_missing_output() {
let cas = OneBlob(Vec::new());
let err = read(&cas, None, &label()).unwrap_err();
assert!(matches!(err, Error::MissingOutput { .. }));
}
}