use std::collections::BTreeSet;
use isoloom_manifest::{Arch, Native, Provider, Run, Step, VagrantBox};
use super::{READ_LIMIT, Vagrant};
use crate::Result;
use crate::error::Error;
use crate::executor::{Cx, DOWNLOAD_STALL, Echo, call, download, spec_for};
use crate::tool_output::vagrant_fields;
const NOTE: &str = "Downloading the VMs' boxes…";
const THERE_ALREADY: &str = "already exists";
fn id_before(id: &str) -> String {
format!("boxes-{id}")
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Listed {
name: String,
provider: String,
version: String,
arch: Option<String>,
}
fn listed(out: &str) -> Vec<Listed> {
let mut boxes: Vec<Listed> = Vec::new();
for (_, kind, data) in out.lines().filter_map(vagrant_fields) {
let data = data.trim();
match (kind, boxes.last_mut()) {
("box-name", _) => boxes.push(Listed {
name: data.to_owned(),
provider: String::new(),
version: String::new(),
arch: None,
}),
("box-provider", Some(b)) => data.clone_into(&mut b.provider),
("box-version", Some(b)) => data.clone_into(&mut b.version),
("box-architecture", Some(b)) => b.arch = Some(data.to_owned()).filter(|a| !a.is_empty() && a != "unknown"),
_ => {}
}
}
boxes
}
fn is_there(wanted: &VagrantBox, host: Arch, there: &[Listed]) -> bool {
let build = arch_id(wanted.architecture.unwrap_or(host));
there.iter().any(|b| {
b.name == wanted.name.as_str()
&& b.provider == wire(wanted)
&& wanted.version.as_ref().is_none_or(|v| !v.is_exact() || b.version == v.as_str())
&& b.arch.as_deref().is_none_or(|a| a == build)
})
}
fn arch_id(a: Arch) -> &'static str {
match a {
Arch::Amd64 => "amd64",
Arch::Arm64 => "arm64",
}
}
fn wire(b: &VagrantBox) -> &'static str {
match b.provider {
Provider::Qemu => Provider::Libvirt.id(),
other => other.id(),
}
}
fn wanted(cx: &Cx<'_>) -> Vec<VagrantBox> {
let Some(provider) = cx.scope.provider else { return Vec::new() };
let host = cx.run.runner.config.arch;
let mut seen = BTreeSet::new();
cx.run
.manifest()
.machines
.iter()
.filter(|m| !m.on_demand)
.filter_map(|m| match &m.native {
Some(Native::Vagrant { boxes, .. }) => Some(boxes),
_ => None,
})
.flatten()
.filter(|b| b.provider == provider && b.host_architecture.is_none_or(|h| h == host))
.filter(|b| seen.insert((b.name.clone(), b.version.clone(), b.architecture.map(arch_id))))
.cloned()
.collect()
}
fn creates_vms(cx: &Cx<'_>, list: &str, step: &Step) -> bool {
let Run::Argv(_) = &step.run else { return false };
let Ok(spec) = spec_for(cx, list, step) else { return false };
spec.program == "vagrant" && spec.args.first().is_some_and(|a| a == "up") && !spec.args.iter().any(|a| a == "--no-provision")
}
pub(in crate::driver) async fn before_step(vagrant: &Vagrant, cx: &Cx<'_>, list: &str, step: &Step) -> Result<()> {
if !creates_vms(cx, list, step) {
return Ok(());
}
let wanted = wanted(cx);
if wanted.is_empty() {
return Ok(());
}
let id = id_before(step.id.as_str());
let list_spec = vagrant.vagrant(cx, &id, &["box", "list", "--machine-readable"])?;
let there = call(cx, &id, &list_spec, READ_LIMIT, Echo::Quiet)
.await
.ok()
.filter(crate::process::Captured::success)
.map(|out| listed(&out.stdout.join("\n")))
.unwrap_or_default();
let host = cx.run.runner.config.arch;
let missing: Vec<&VagrantBox> = wanted.iter().filter(|b| !is_there(b, host, &there)).collect();
if missing.is_empty() {
return Ok(());
}
cx.events
.stepped(&id, Some(NOTE), async {
for b in missing {
add(vagrant, cx, &id, b).await?;
}
Ok(())
})
.await
}
async fn add(vagrant: &Vagrant, cx: &Cx<'_>, id: &str, b: &VagrantBox) -> Result<()> {
let mut args = vec!["box", "add", b.name.as_str(), "--provider", wire(b)];
if let Some(v) = &b.version {
args.extend(["--box-version", v.as_str()]);
}
if let Some(a) = b.architecture {
args.extend(["--architecture", arch_id(a)]);
}
let spec = vagrant.vagrant(cx, id, &args)?;
let out = download(cx, id, &spec, DOWNLOAD_STALL).await?;
if out.success() {
return Ok(());
}
let reason = out.reason();
if reason.contains(THERE_ALREADY) {
return Ok(());
}
Err(Error::DownloadFailed {
step: id.to_owned(),
reason: cx.events.mask(&reason),
})
}
#[cfg(test)]
mod tests {
use isoloom_manifest::{BoxName, BoxVersion, Provider};
use super::*;
const LIST: &str = "1794406460,,ui,info,bento/debian-12 (virtualbox%!(VAGRANT_COMMA) 202510.26.0%!(VAGRANT_COMMA) (arm64))
1794406460,,box-name,bento/debian-12
1794406460,,box-provider,virtualbox
1794406460,,box-version,202510.26.0
1794406460,,box-architecture,arm64
1794406460,,box-name,generic/alpine319
1794406460,,box-provider,libvirt
1794406460,,box-version,4.3.12
1794406460,,box-info,Author,Ladar Levison
1794406460,,box-name,old/box
1794406460,,box-provider,virtualbox
1794406460,,box-version,1.0.0
1794406460,,box-architecture,unknown
";
fn wanted(name: &str, provider: Provider, version: Option<&str>, arch: Option<Arch>) -> VagrantBox {
VagrantBox {
provider,
name: BoxName::parse(name).unwrap(),
version: version.map(|v| BoxVersion::parse(v).unwrap()),
architecture: arch,
host_architecture: None,
}
}
#[test]
fn the_boxes_vagrant_lists_are_read_with_their_provider_version_and_build() {
let there = listed(LIST);
assert_eq!(there.len(), 3);
assert_eq!(
there[0],
Listed {
name: "bento/debian-12".into(),
provider: "virtualbox".into(),
version: "202510.26.0".into(),
arch: Some("arm64".into()),
}
);
assert_eq!((there[1].arch.as_ref(), there[2].arch.as_ref()), (None, None), "none said, or unknown");
}
#[test]
fn a_qemu_box_is_the_libvirt_format_vagrant_qemu_boots() {
let qemu = wanted("generic/alpine319", Provider::Qemu, None, None);
assert_eq!(wire(&qemu), "libvirt");
assert!(is_there(&qemu, Arch::Amd64, &listed(LIST)), "the libvirt build listed is the one it boots");
assert_eq!(wire(&wanted("bento/debian-12", Provider::Virtualbox, None, None)), "virtualbox");
}
#[test]
fn a_box_is_there_with_its_provider_build_and_exact_version() {
let there = listed(LIST);
let bento = |v, a| wanted("bento/debian-12", Provider::Virtualbox, v, a);
assert!(is_there(&bento(None, None), Arch::Arm64, &there));
assert!(!is_there(&bento(None, None), Arch::Amd64, &there));
assert!(!is_there(&bento(None, Some(Arch::Amd64)), Arch::Arm64, &there), "a pinned build");
assert!(is_there(&bento(Some("202510.26.0"), None), Arch::Arm64, &there));
assert!(!is_there(&bento(Some("202508.03.0"), None), Arch::Arm64, &there), "another version");
assert!(is_there(&bento(Some(">= 202501"), None), Arch::Arm64, &there), "a constraint: any version");
assert!(!is_there(&wanted("bento/debian-12", Provider::Parallels, None, None), Arch::Arm64, &there));
assert!(is_there(
&wanted("generic/alpine319", Provider::Libvirt, None, Some(Arch::Amd64)),
Arch::Arm64,
&there
));
assert!(is_there(&wanted("old/box", Provider::Virtualbox, Some("1.0.0"), None), Arch::Amd64, &there));
}
}