use camino::{Utf8Path, Utf8PathBuf};
use serde::Serialize;
use crate::adapters::history::History;
use crate::candidate::Ownership;
use crate::error::AppError;
pub const SCHEMA: &str = "sdd.stage-compare/1";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum State {
Equal,
Absent,
Differs,
Retired,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Provenance {
Attributed,
Reduced,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum RowOwnership {
Managed,
Integration,
Adopted,
}
impl RowOwnership {
const fn landing(self) -> Ownership {
match self {
Self::Managed => Ownership::Managed,
Self::Integration => Ownership::Integration,
Self::Adopted => Ownership::Adopted,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Managed => "managed",
Self::Integration => "integration",
Self::Adopted => "adopted",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Row {
pub path: String,
pub state: State,
pub ownership: RowOwnership,
pub provenance: Option<Provenance>,
pub vouched: Option<bool>,
pub replaceable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct HistoryState {
pub available: bool,
pub reason: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Report {
pub schema: &'static str,
pub root: Utf8PathBuf,
pub target: Utf8PathBuf,
pub history: HistoryState,
pub rows: Vec<Row>,
}
pub fn compare(root: &Utf8Path, target: &Utf8Path) -> Result<Report, AppError> {
let choices = super::read_choices(root, target)?;
let replaceable = crate::services::upgrader::replaceable(&choices)?;
let target = choices.target.clone();
let recorded = crate::services::installer::recorded(&target);
let (history, history_state) = match History::open(&target) {
Ok(history) => (
Some(history),
HistoryState {
available: true,
reason: None,
},
),
Err(missing) => (
None,
HistoryState {
available: false,
reason: Some(missing.to_string()),
},
),
};
let touches = |path: &Utf8Path| history.as_ref().is_some_and(|held| held.touches(path));
let provenance = |vouched: bool, path: &Utf8Path| match (vouched, touches(path)) {
(true, true) => Provenance::Attributed,
(false, false) => Provenance::Unknown,
_ => Provenance::Reduced,
};
let mut rows = Vec::new();
let mut staged_paths = Vec::new();
for artifact in &choices.artifacts {
let ownership = match artifact.ownership.as_str() {
"managed" => RowOwnership::Managed,
"integration" => RowOwnership::Integration,
"adopted" => RowOwnership::Adopted,
_ => continue,
};
let path = Utf8PathBuf::from(&artifact.path);
staged_paths.push(artifact.path.clone());
let staged = std::fs::read(root.join(super::ARTIFACTS_DIR).join(&path))?;
let Ok(held) = std::fs::read(target.join(&path)) else {
rows.push(Row {
path: artifact.path.clone(),
state: State::Absent,
ownership,
provenance: None,
vouched: None,
replaceable: replaceable.contains(&artifact.path),
});
continue;
};
let vouched = crate::landing::apply::vouches(&recorded, &path, ownership.landing(), &held);
let equal = match ownership {
RowOwnership::Integration => region(&path, &held) == region(&path, &staged),
RowOwnership::Managed | RowOwnership::Adopted => held == staged,
};
rows.push(Row {
path: artifact.path.clone(),
state: if equal { State::Equal } else { State::Differs },
ownership,
provenance: (!equal).then(|| provenance(vouched, &path)),
vouched: Some(vouched),
replaceable: replaceable.contains(&artifact.path),
});
}
for (destination, _) in &recorded.managed {
if staged_paths.contains(destination) {
continue;
}
let path = Utf8PathBuf::from(destination);
let (provenance, vouched) = match std::fs::read(target.join(&path)) {
Ok(held) => {
let vouched = crate::landing::apply::vouches_retired(&recorded, destination, &held);
(Some(provenance(vouched, &path)), Some(vouched))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
(Some(provenance(false, &path)), None)
}
Err(_) => (Some(Provenance::Unknown), None),
};
rows.push(Row {
path: destination.clone(),
state: State::Retired,
ownership: RowOwnership::Managed,
provenance,
vouched,
replaceable: replaceable.contains(destination),
});
}
Ok(Report {
schema: SCHEMA,
root: root.to_owned(),
target,
history: history_state,
rows,
})
}
fn region(path: &Utf8Path, bytes: &[u8]) -> Option<crate::domain::ownership::Sha256> {
use crate::domain::marker;
let text = std::str::from_utf8(bytes).ok()?;
if path == crate::domain::paths::HOOKS_CONFIG_PATH {
marker::block_hash(text)
} else {
marker::block_hash_with(text, marker::AGENTS_BEGIN, marker::AGENTS_END)
}
}