use std::path::{Path, PathBuf};
use isoloom_manifest::contract::OUTPUT_DIR;
use isoloom_manifest::{Manifest, Part, Placeholder, RunVar};
use crate::Result;
use crate::error::Error;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LoadedManifest {
pub manifest: Manifest,
pub path: PathBuf,
pub dir: PathBuf,
}
pub fn load_manifest(path: &Path) -> Result<LoadedManifest> {
let path = std::path::absolute(path).map_err(Error::io(path, "read"))?;
let bytes = std::fs::read(&path).map_err(Error::io(&path, "read"))?;
let text = std::str::from_utf8(&bytes).map_err(|e| Error::Malformed {
at: path.display().to_string(),
reason: format!("not UTF-8 at byte {}", e.valid_up_to()),
})?;
let manifest = isoloom_manifest::parse(text).map_err(|source| Error::Manifest { path: path.clone(), source })?;
let dir = path.parent().map_or_else(|| path.clone(), Path::to_path_buf);
Ok(LoadedManifest { manifest, path, dir })
}
pub const MANIFEST_FILE: &str = "run.json";
#[must_use]
pub fn is_outputs_folder(name: &str) -> bool {
let Some(rest) = name.strip_prefix(OUTPUT_DIR) else {
return false;
};
let Some(n) = rest.strip_prefix('-') else {
return rest.is_empty();
};
!n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()) && n.parse::<u8>().is_ok_and(|n| isoloom_manifest::Instance::new(n).is_ok())
}
pub(crate) fn names_run_var(manifest: &Manifest, wanted: impl Fn(RunVar) -> bool) -> bool {
manifest
.templates()
.iter()
.any(|(_, t)| t.parts().iter().any(|p| matches!(p, Part::Placeholder(Placeholder::Run(v)) if wanted(*v))))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_outputs_folder_is_one_isoloom_generates_into() {
let spec = "version: 1\nname: one\nnetworks:\n app: { cidr: 10.80.0.0/24 }\nmachines:\n web: { app: { image: nginx }, networks: { app: 10 } }\n";
let lab = isoloom_targets::Lab::parse(spec).unwrap();
let docker = lab.possible().into_iter().find(|t| t.id() == "docker").unwrap();
let manifest_of = |files: Vec<isoloom_targets::GeneratedFile>| {
files
.into_iter()
.map(|f| f.path)
.find(|p| p.ends_with("/run.json") && p.contains("/docker/"))
.unwrap()
};
let mut paths = vec![manifest_of(isoloom_targets::generate(&lab, docker).unwrap())];
let instances: Vec<u8> = (1..=u8::MAX).take_while(|n| isoloom_manifest::Instance::new(*n).is_ok()).collect();
paths.extend(
instances
.iter()
.map(|n| manifest_of(isoloom_targets::generate_instance(&lab, docker, *n).unwrap())),
);
for path in &paths {
let (folder, rest) = path.split_once('/').unwrap();
assert!(is_outputs_folder(folder), "{path}");
assert_eq!(rest, format!("docker/{MANIFEST_FILE}"), "{path}");
}
for n in [0, instances.len() + 1] {
let n = u8::try_from(n).unwrap();
assert!(isoloom_targets::generate_instance(&lab, docker, n).is_err(), "Isoloom makes no instance {n}");
}
for other in [
".isoloom-0",
".isoloom-100",
".isoloom-02",
".isoloom-+2",
".isoloom-",
".isoloom-old",
".isoloomfoo",
"isoloom",
".isoloom-2/",
] {
assert!(!is_outputs_folder(other), "{other}");
}
}
#[test]
fn a_missing_file_is_an_io_error_naming_it() {
let err = load_manifest(Path::new("no/such/run.json")).unwrap_err();
assert_eq!(err.code(), crate::ErrorCode::Io);
assert!(err.to_string().contains("run.json couldn't be read"), "{err}");
}
#[test]
fn a_manifest_that_isnt_utf8_is_invalid_naming_the_byte() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("run.json");
let mut bytes = crate::testing::WEB_PORTAL.as_bytes().to_vec();
let at = crate::testing::WEB_PORTAL.find("web-portal").unwrap();
bytes[at] = 0xff;
std::fs::write(&path, &bytes).unwrap();
let err = load_manifest(&path).unwrap_err();
assert_eq!(err.code(), crate::ErrorCode::ManifestInvalid, "{err}");
assert!(err.to_string().ends_with(&format!("run.json: not UTF-8 at byte {at}")), "{err}");
}
}