use std::path::Path;
pub fn check(manifest_dir: &Path) -> Result<(), String> {
let ours = env!("CARGO_PKG_VERSION");
let Some(lock) = find_lock(manifest_dir) else {
return Ok(()); };
let Ok(text) = std::fs::read_to_string(&lock) else {
return Ok(());
};
let Some(theirs) = locked_version(&text, "cosmo-compat") else {
return Ok(()); };
if major(&theirs) != major(ours) {
return Err(format!(
"cosmo-build {ours} needs cosmo-compat {}.x, but the graph resolved {theirs}.\n\
The wrap list here and the translators there are published together;\n\
mixing majors is a link error. Set both to \"{}\" in Cargo.toml.",
major(ours),
major(ours)
));
}
Ok(())
}
fn find_lock(from: &Path) -> Option<std::path::PathBuf> {
let mut dir = Some(from);
while let Some(d) = dir {
let lock = d.join("Cargo.lock");
if lock.is_file() {
return Some(lock);
}
dir = d.parent();
}
None
}
fn locked_version(lock: &str, want: &str) -> Option<String> {
let mut in_package = false;
for line in lock.lines() {
let line = line.trim_end();
if line == "[[package]]" {
in_package = false;
continue;
}
if let Some(name) = line.strip_prefix("name = \"").and_then(|r| r.strip_suffix('"')) {
in_package = name == want;
continue;
}
if in_package {
if let Some(v) = line.strip_prefix("version = \"").and_then(|r| r.strip_suffix('"')) {
return Some(v.to_string());
}
}
}
None
}
fn major(v: &str) -> &str {
v.split('.').next().unwrap_or(v)
}
#[cfg(test)]
mod tests {
use super::*;
const LOCK: &str = r#"
[[package]]
name = "ext"
version = "0.1.0"
dependencies = [
"cosmo-compat",
]
[[package]]
name = "cosmo-compat"
version = "3.0.0"
"#;
#[test]
fn reads_the_locked_version() {
assert_eq!(locked_version(LOCK, "cosmo-compat").as_deref(), Some("3.0.0"));
assert_eq!(locked_version(LOCK, "ext").as_deref(), Some("0.1.0"));
assert_eq!(locked_version(LOCK, "absent"), None);
}
#[test]
fn dependency_listing_is_not_a_package() {
let lock = "[[package]]\nname = \"ext\"\ndependencies = [\n \"cosmo-compat\",\n]\n";
assert_eq!(locked_version(lock, "cosmo-compat"), None);
}
#[test]
fn majors() {
assert_eq!(major("3.0.0"), "3");
assert_eq!(major("12.1.4"), "12");
}
}