use std::fmt;
use super::{Call, CliError, argv, said_any};
use crate::process::Captured;
const TOOL: &str = "VBoxManage";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Failure {
NotFound,
Other(String),
}
impl Failure {
pub(crate) fn of(out: &Captured) -> Failure {
if said_any(out, &["vbox_e_object_not_found", "could not find a registered machine"]) {
Failure::NotFound
} else {
Failure::Other(out.reason())
}
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Failure::NotFound => f.write_str("VirtualBox has no such VM"),
Failure::Other(reason) => f.write_str(reason),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum VmState {
AbortedSaved,
Other(String),
}
fn vm_state_of(lines: &[String]) -> Option<VmState> {
let value = lines
.iter()
.find_map(|l| l.trim_end_matches('\r').strip_prefix("VMState="))
.map(|v| v.trim().trim_matches('"'))?;
Some(if value == "aborted-saved" {
VmState::AbortedSaved
} else {
VmState::Other(value.to_owned())
})
}
pub(crate) async fn vm_state(call: &Call<'_>, uuid: &str) -> Result<VmState, CliError<Failure>> {
let out = call.ok(TOOL, argv(["showvminfo", uuid, "--machinereadable"]), Failure::of).await?;
vm_state_of(&out.stdout).ok_or_else(|| CliError::Unexpected {
tool: TOOL,
what: format!("a `showvminfo` of `{uuid}` with no VMState"),
})
}
pub(crate) async fn remote_display(call: &Call<'_>, uuid: &str) -> Result<crate::tool_output::vboxmanage::Vrde, CliError<Failure>> {
let out = call.ok(TOOL, argv(["showvminfo", uuid, "--machinereadable"]), Failure::of).await?;
Ok(crate::tool_output::vboxmanage::remote_display(&out.stdout))
}
pub(crate) async fn discard_state(call: &Call<'_>, uuid: &str) -> Result<(), CliError<Failure>> {
call.ok(TOOL, argv(["discardstate", uuid]), Failure::of).await.map(drop)
}
pub(crate) async fn power_off(call: &Call<'_>, uuid: &str) -> Result<(), CliError<Failure>> {
call.ok(TOOL, argv(["controlvm", uuid, "poweroff"]), Failure::of).await.map(drop)
}
pub(crate) async fn unregister_delete(call: &Call<'_>, uuid: &str) -> Result<(), CliError<Failure>> {
call.ok(TOOL, argv(["unregistervm", uuid, "--delete"]), Failure::of).await.map(drop)
}
pub(crate) async fn vms(call: &Call<'_>) -> Result<Vec<(String, String)>, CliError<Failure>> {
let out = call.ok(TOOL, argv(["list", "vms"]), Failure::of).await?;
Ok(crate::tool_output::vboxmanage::vms(&out.stdout.join("\n")))
}
pub(crate) async fn machine_folder(call: &Call<'_>) -> Result<std::path::PathBuf, CliError<Failure>> {
let out = call.ok(TOOL, argv(["list", "systemproperties"]), Failure::of).await?;
crate::tool_output::vboxmanage::machine_folder(&out.stdout.join("\n")).ok_or_else(|| CliError::Unexpected {
tool: TOOL,
what: "a `list systemproperties` with no default machine folder".to_owned(),
})
}
#[cfg(test)]
mod tests;