use crate::schema::SchemaDocument;
pub(super) fn read_sidecar(
path: &std::path::Path,
expected_name: &str,
) -> Result<Option<SchemaDocument>, String> {
let sidecar = path.with_extension("datacraft");
let json = match std::fs::read_to_string(&sidecar) {
Ok(json) => json,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("sidecar read failed: {e}")),
};
let document =
SchemaDocument::from_json(&json).map_err(|e| format!("sidecar decode failed: {e}"))?;
document
.validate()
.map_err(|e| format!("sidecar validation failed: {e}"))?;
if document.database_name != expected_name {
return Err(format!(
"the sidecar belongs to {:?}, not to {:?}",
document.database_name, expected_name
));
}
Ok(Some(document))
}