use std::path::PathBuf;
use printobserver_types::serde_json::{self, Value};
pub fn schema_dir(crate_name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("schemas")
.join(crate_name)
}
fn text_of(schema: &Value) -> String {
let mut text = serde_json::to_string_pretty(schema).expect("a schema serializes");
text.push('\n');
text
}
pub fn reconcile(crate_name: &str, entries: &[(String, Value)]) -> Vec<String> {
let directory = schema_dir(crate_name);
if std::env::var("PRINTOBSERVER_SCHEMAS").is_ok_and(|mode| mode == "write") {
std::fs::create_dir_all(&directory).expect("the schema directory is writable");
for existing in std::fs::read_dir(&directory).expect("the schema directory is readable") {
let path = existing.expect("a readable directory entry").path();
let name = path
.file_name()
.expect("a file name")
.to_string_lossy()
.into_owned();
if !entries.iter().any(|(file, _)| *file == name) {
std::fs::remove_file(&path).expect("a stale schema is removable");
}
}
for (file, schema) in entries {
std::fs::write(directory.join(file), text_of(schema)).expect("a schema is writable");
}
}
let mut findings = Vec::new();
for (file, schema) in entries {
let path = directory.join(file);
match std::fs::read_to_string(&path) {
Err(error) => findings.push(format!("{}: {error}", path.display())),
Ok(found) if found != text_of(schema) => {
findings.push(format!("{} is not what the types generate", path.display()));
}
Ok(_) => {}
}
}
match std::fs::read_dir(&directory) {
Err(error) => findings.push(format!("{}: {error}", directory.display())),
Ok(listing) => {
for existing in listing {
let path = existing.expect("a readable directory entry").path();
let name = path
.file_name()
.expect("a file name")
.to_string_lossy()
.into_owned();
if !entries.iter().any(|(file, _)| *file == name) {
findings.push(format!(
"{} is a schema no declared type generates",
path.display()
));
}
}
}
}
findings
}