use camino::{Utf8Path, Utf8PathBuf};
use serde::{Deserialize, Serialize};
use crate::adapters::fs::sha256_file;
use crate::domain::ownership::Sha256;
use crate::domain::version::CanonVersion;
use crate::error::AppError;
pub const PAYLOAD_RECORD_PATH: &str = "instance/payload-manifest.json";
pub const PAYLOAD_RECORD_SCHEMA: &str = "sdd.payload-manifest/1";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PayloadFile {
pub path: Utf8PathBuf,
pub sha256: Sha256,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadRecord {
pub schema: String,
pub version: CanonVersion,
pub files: Vec<PayloadFile>,
}
impl PayloadRecord {
#[must_use]
pub fn to_json(&self) -> String {
let mut text = serde_json::to_string_pretty(self).unwrap_or_default();
text.push('\n');
text
}
}
pub(crate) fn is_canon_checkout(root: &Utf8Path) -> bool {
std::fs::read_to_string(root.join("Cargo.toml"))
.is_ok_and(|cargo| cargo.contains("name = \"spec-driven-docs\""))
}
pub fn describe(root: &Utf8Path) -> Result<PayloadRecord, AppError> {
let mut files = Vec::new();
for declared in crate::payload_roots::PAYLOAD_ROOTS {
if !root.join(declared).exists() {
continue;
}
for entry in walkdir::WalkDir::new(root.join(declared)).sort_by_file_name() {
let entry = entry.map_err(|source| AppError::Io(std::io::Error::from(source)))?;
if !entry.file_type().is_file() {
continue;
}
let Some(path) = Utf8Path::from_path(entry.path()) else {
continue;
};
let relative = path.strip_prefix(root).unwrap_or(path).to_owned();
if relative == PAYLOAD_RECORD_PATH {
continue;
}
files.push(PayloadFile {
sha256: sha256_file(path)?,
path: relative,
});
}
}
files.sort_by(|left, right| left.path.cmp(&right.path));
Ok(PayloadRecord {
schema: PAYLOAD_RECORD_SCHEMA.to_string(),
version: CanonVersion::current(),
files,
})
}
pub fn regenerate(root: &Utf8Path) -> Result<String, AppError> {
if !is_canon_checkout(root) {
return Err(AppError::Refused("not the canon checkout".to_string()));
}
let record = describe(root)?;
crate::adapters::fs::write_file(&root.join(PAYLOAD_RECORD_PATH), record.to_json().as_bytes())?;
Ok(format!("OK regenerated {PAYLOAD_RECORD_PATH}"))
}