use std::path::Path;
use crate::types::lock::error::LockError;
use crate::types::lock::file::Lockfile;
use crate::types::manifest::PackManifest;
use crate::types::report::Diagnostic;
use crate::types::report::Location;
pub fn check_airsl_presence<'a>(
file: &Path,
lock: &Lockfile,
locked_packs: impl IntoIterator<Item = &'a PackManifest>,
) -> Result<(), Diagnostic> {
let needed = locked_packs
.into_iter()
.any(|manifest| manifest.requires().airsl().is_some());
let error = match (needed, lock.airsl().is_some()) {
(true, false) => LockError::AirslMissing,
(false, true) => LockError::AirslUnneeded,
(true, true) | (false, false) => return Ok(()),
};
Err(Diagnostic::new(Location::file(file), error))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::lock::file::LockContents;
use crate::types::manifest::PackVersion;
type TestResult = Result<(), Box<dyn std::error::Error>>;
const LOCK_FILE: &str = "agentstacks.lock";
fn manifest(requires: &str) -> Result<PackManifest, Box<dyn std::error::Error>> {
let text = format!(
"[pack]\nname = \"core\"\nversion = \"1.0.0\"\napi = 0\ndescription = \"d\"\n{requires}"
);
PackManifest::parse(Path::new("packs/core/pack.toml"), &text).map_err(|diagnostics| {
let shown: Vec<String> = diagnostics
.into_sorted()
.iter()
.map(ToString::to_string)
.collect();
shown.join("; ").into()
})
}
fn needing() -> Result<PackManifest, Box<dyn std::error::Error>> {
manifest("[requires]\nairsl = \">=0.1.4\"\n")
}
fn lock(airsl: bool) -> Result<Lockfile, Box<dyn std::error::Error>> {
Lockfile::new(
Path::new(LOCK_FILE),
LockContents {
airsl: airsl.then(|| PackVersion::new("0.1.4")).transpose()?,
..LockContents::default()
},
)
.map_err(|d| format!("{:?}", d.into_sorted()).into())
}
fn shown(result: Result<(), Diagnostic>) -> Option<String> {
result.err().map(|diagnostic| diagnostic.to_string())
}
#[test]
fn airsl_presence_refuses_a_missing_section() -> TestResult {
let packs = [manifest("")?, needing()?];
assert_eq!(
shown(check_airsl_presence(
Path::new(LOCK_FILE),
&lock(false)?,
&packs
))
.as_deref(),
Some("agentstacks.lock: [airsl] missing, but locked packs require airsl")
);
Ok(())
}
#[test]
fn airsl_presence_refuses_an_unneeded_section() -> TestResult {
let expected = Some("agentstacks.lock: [airsl] present, but no locked pack requires airsl");
let plain = [manifest("")?];
assert_eq!(
shown(check_airsl_presence(
Path::new(LOCK_FILE),
&lock(true)?,
&plain
))
.as_deref(),
expected
);
assert_eq!(
shown(check_airsl_presence(Path::new(LOCK_FILE), &lock(true)?, [])).as_deref(),
expected
);
Ok(())
}
#[test]
fn airsl_presence_accepts_consistent_locks() -> TestResult {
let needing = [needing()?];
check_airsl_presence(Path::new(LOCK_FILE), &lock(true)?, &needing)
.map_err(|d| d.to_string())?;
let plain = [manifest("")?];
check_airsl_presence(Path::new(LOCK_FILE), &lock(false)?, &plain)
.map_err(|d| d.to_string())?;
Ok(())
}
}