use std::path::Path;
use crate::db::Db;
use crate::error::{Error, Result};
use crate::model::Observed;
use crate::witness::Witness;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Side {
Bytes(Vec<u8>),
Absent,
Unkept(String),
}
impl Side {
fn bytes(&self) -> Option<&[u8]> {
match self {
Side::Bytes(b) => Some(b),
Side::Absent => Some(&[]),
Side::Unkept(_) => None,
}
}
}
#[derive(Debug, Clone)]
pub struct FileExhibit {
pub path: String,
pub kind: String,
pub before: Side,
pub after: Side,
}
pub fn assemble(db: &Db, witness: &Witness, seq: i64) -> Result<Vec<FileExhibit>> {
let Some(baseline) = db.witnessed().baseline_of(seq)? else {
return Err(Error::invalid(format!(
"hird was not watching task {seq} — no baseline was taken, so nothing was kept"
)));
};
let task = db.tasks().get(seq)?;
let live = task.status.is_active();
Ok(assemble_from(
db,
witness,
&baseline,
db.witnessed().touched(seq)?,
live,
))
}
pub fn assemble_tenure(db: &Db, witness: &Witness, seq: i64, n: i64) -> Result<Vec<FileExhibit>> {
let Some(baseline) = db.witnessed().tenure_baseline(seq, n)? else {
let held = db.witnessed().tenures(seq)?;
return Err(Error::invalid(if held.is_empty() {
format!("task {seq} has no archived holdings — it has never changed hands under the witness")
} else {
format!(
"task {seq} has no archived holding {n}; it has {} — `hird show {seq}` lists them",
held.len()
)
}));
};
let changes = db
.witnessed()
.tenures(seq)?
.into_iter()
.find(|t| t.n == n)
.map(|t| t.changes)
.unwrap_or_default();
Ok(assemble_from(db, witness, &baseline, changes, false))
}
fn assemble_from(
db: &Db,
witness: &Witness,
baseline: &crate::repo::Baseline,
observed: Vec<Observed>,
live: bool,
) -> Vec<FileExhibit> {
observed
.into_iter()
.map(|observed| {
let before = before_side(db, witness, baseline, &observed);
let after = after_side(db, witness, &observed, live);
FileExhibit {
path: observed.path,
kind: observed.kind,
before,
after,
}
})
.collect()
}
fn before_side(
db: &Db,
witness: &Witness,
baseline: &crate::repo::Baseline,
observed: &Observed,
) -> Side {
if observed.kind == "added" {
return Side::Absent;
}
match baseline.tree.entries.get(&observed.path) {
Some(hash) if hash.is_empty() => Side::Absent,
Some(hash) if hash.starts_with("size:") => {
Side::Unkept("too large for the witness to keep".to_string())
}
Some(hash) => match db.witnessed().blob(hash) {
Ok(Some(bytes)) => Side::Bytes(bytes),
_ => Side::Unkept("the version at claim time is no longer kept".to_string()),
},
None => match witness.content_at(&baseline.tree.head, &observed.path) {
Some(bytes) => Side::Bytes(bytes),
None => Side::Unkept(format!(
"not in the repository at the claim's commit ({})",
short(&baseline.tree.head)
)),
},
}
}
fn after_side(db: &Db, witness: &Witness, observed: &Observed, live: bool) -> Side {
if observed.kind == "deleted" {
return Side::Absent;
}
if observed.hash.starts_with("size:") {
return Side::Unkept("too large for the witness to keep".to_string());
}
if live {
return match witness.read(&observed.path) {
Some(bytes) => Side::Bytes(bytes),
None => Side::Unkept("unreadable in the working tree right now".to_string()),
};
}
match db.witnessed().blob(&observed.hash) {
Ok(Some(bytes)) => Side::Bytes(bytes),
_ if witness.fingerprint(&observed.path) == observed.hash => {
match witness.read(&observed.path) {
Some(bytes) => Side::Bytes(bytes),
None => Side::Unkept("the final version was not kept".to_string()),
}
}
_ => Side::Unkept("the final version was not kept".to_string()),
}
}
pub fn salvage(
db: &Db,
witness: &Witness,
seq: i64,
path: &str,
at_claim: bool,
tenure: Option<i64>,
) -> Result<Vec<u8>> {
if let Some(n) = tenure {
return salvage_from(
db,
witness,
seq,
path,
at_claim,
db.witnessed().tenure_baseline(seq, n)?.ok_or_else(|| {
Error::invalid(format!(
"task {seq} has no archived holding {n} — `hird show {seq}` lists what it has"
))
})?,
db.witnessed()
.tenures(seq)?
.into_iter()
.find(|t| t.n == n)
.map(|t| t.changes)
.unwrap_or_default(),
);
}
let Some(baseline) = db.witnessed().baseline_of(seq)? else {
return Err(Error::invalid(format!(
"hird was not watching task {seq} — no baseline was taken, so nothing was kept"
)));
};
let observed = db.witnessed().touched(seq)?;
salvage_from(db, witness, seq, path, at_claim, baseline, observed)
}
fn salvage_from(
db: &Db,
witness: &Witness,
seq: i64,
path: &str,
at_claim: bool,
baseline: crate::repo::Baseline,
observed: Vec<Observed>,
) -> Result<Vec<u8>> {
if at_claim {
return match baseline.tree.entries.get(path) {
Some(hash) if hash.is_empty() => Err(Error::invalid(format!(
"{path} did not exist when task {seq} was claimed"
))),
Some(hash) if hash.starts_with("size:") => Err(Error::invalid(format!(
"{path} was too large for the witness to keep"
))),
Some(hash) => db.witnessed().blob(hash)?.ok_or_else(|| {
Error::invalid(format!(
"the version of {path} at task {seq}'s claim is no longer kept"
))
}),
None => witness
.content_at(&baseline.tree.head, path)
.ok_or_else(|| {
Error::invalid(format!(
"{path} was clean when task {seq} was claimed, and commit {} does not \
have it either",
short(&baseline.tree.head)
))
}),
};
}
let Some(row) = observed.iter().find(|o| o.path == path) else {
let saw: Vec<&str> = observed.iter().map(|o| o.path.as_str()).collect();
return Err(Error::invalid(if saw.is_empty() {
format!("the witness saw nothing move under task {seq}")
} else {
format!(
"the witness never saw {path} move under task {seq}; it saw: {}",
saw.join(", ")
)
}));
};
if row.hash.is_empty() {
return Err(Error::invalid(format!(
"the witness last saw {path} deleted under task {seq}; --baseline has the \
version from before the claim"
)));
}
if row.hash.starts_with("size:") {
return Err(Error::invalid(format!(
"{path} was too large for the witness to keep"
)));
}
db.witnessed().blob(&row.hash)?.ok_or_else(|| {
Error::invalid(format!(
"the last version the witness saw of {path} under task {seq} is no longer kept"
))
})
}
pub fn render(exhibits: &[FileExhibit]) -> String {
let mut out = String::new();
for exhibit in exhibits {
match (&exhibit.before, &exhibit.after) {
(Side::Unkept(reason), _) => {
out.push_str(&format!(
"{} ({}) — before-version {reason}; no diff to show\n",
exhibit.path, exhibit.kind
));
}
(_, Side::Unkept(reason)) => {
out.push_str(&format!(
"{} ({}) — after-version {reason}; no diff to show\n",
exhibit.path, exhibit.kind
));
}
(before, after) => {
let (b, a) = (before.bytes().unwrap_or(&[]), after.bytes().unwrap_or(&[]));
if b == a {
continue;
}
match unified(&exhibit.path, b, a) {
Some(text) => out.push_str(&text),
None => out.push_str(&format!(
"{} ({}) — diff could not be rendered\n",
exhibit.path, exhibit.kind
)),
}
}
}
}
out
}
pub const BRIEF_MAX_BYTES: usize = 24 * 1024;
pub fn clipped(text: &str, max_bytes: usize, seq: i64) -> String {
if text.len() <= max_bytes {
return text.to_string();
}
let mut cut = 0;
for line in text.split_inclusive('\n') {
if cut + line.len() > max_bytes {
break;
}
cut += line.len();
}
format!(
"{}… clipped — `hird diff {seq}` has the whole change\n",
&text[..cut]
)
}
fn unified(path: &str, before: &[u8], after: &[u8]) -> Option<String> {
let stage = std::env::temp_dir().join(format!("hird-exhibit-{}", ulid::Ulid::generate()));
let result = unified_in(&stage, path, before, after);
let _ = std::fs::remove_dir_all(&stage);
result
}
fn unified_in(stage: &Path, path: &str, before: &[u8], after: &[u8]) -> Option<String> {
for (side, content) in [("before", before), ("after", after)] {
let full = stage.join(side).join(path);
std::fs::create_dir_all(full.parent()?).ok()?;
std::fs::write(&full, content).ok()?;
}
let before_rel = format!("before/{path}");
let after_rel = format!("after/{path}");
let output = std::process::Command::new("git")
.args([
"-c",
"core.quotepath=false",
"diff",
"--no-index",
"--no-color",
"--",
&before_rel,
&after_rel,
])
.current_dir(stage)
.env("GIT_OPTIONAL_LOCKS", "0")
.env("GIT_TERMINAL_PROMPT", "0")
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !matches!(output.status.code(), Some(0 | 1)) {
return None;
}
let text = String::from_utf8_lossy(&output.stdout);
Some(
text.replace(&format!("a/{before_rel}"), &format!("a/{path}"))
.replace(&format!("b/{after_rel}"), &format!("b/{path}"))
.replace(&before_rel, &format!("a/{path}"))
.replace(&after_rel, &format!("b/{path}")),
)
}
fn short(head: &str) -> &str {
if head.len() >= 7 {
&head[..7]
} else {
head
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_unified_diff_reads_like_gits_own() {
let text = unified("src/config.rs", b"a\nb\nc\n", b"a\nB\nc\n").unwrap();
assert!(text.contains("a/src/config.rs"), "{text}");
assert!(text.contains("b/src/config.rs"), "{text}");
assert!(text.contains("-b"), "{text}");
assert!(text.contains("+B"), "{text}");
assert!(
!text.contains("before/"),
"temp layout must not leak: {text}"
);
assert!(
!text.contains("a/a/"),
"git's own prefix must not stack: {text}"
);
}
#[test]
fn an_addition_diffs_from_nothing() {
let text = unified("new.rs", b"", b"fn new() {}\n").unwrap();
assert!(text.contains("+fn new() {}"), "{text}");
}
#[test]
fn binary_content_is_declared_not_dumped() {
let text = unified("blob.bin", &[0u8, 1, 2, 3], &[0u8, 9, 9, 9]).unwrap();
assert!(text.contains("differ"), "{text}");
assert!(!text.contains("before/"), "{text}");
}
#[test]
fn clipping_names_itself_and_points_home() {
let long = "line one\nline two\nline three\n";
let clipped = clipped(long, 10, 42);
assert!(clipped.starts_with("line one\n"), "{clipped}");
assert!(clipped.contains("clipped"), "{clipped}");
assert!(clipped.contains("hird diff 42"), "{clipped}");
assert_eq!(super::clipped(long, 1000, 42), long);
}
}