use super::{Error, READ_LIMIT, Record, Rerun, Result, STATUS_PATIENCE, ToolCx, Vagrant, Verb, retrying, vagrant};
use crate::Provider;
pub(super) fn key_of(record: &Record, asked: Option<Provider>) -> String {
if asked.is_some_and(|p| p.id() == record.provider) {
format!("vm:{}", record.machine)
} else {
format!("vm:{}@{}", record.machine, record.provider)
}
}
pub(super) fn of_key(key: &str, asked: Option<Provider>) -> Option<(String, Option<String>)> {
let rest = key.strip_prefix("vm:")?;
Some(match rest.split_once('@') {
Some((machine, provider)) => (machine.to_owned(), Some(provider.to_owned())),
None => (rest.to_owned(), asked.map(|p| p.id().to_owned())),
})
}
pub(super) fn ours(name: &str, key: &str) -> bool {
!key.is_empty() && name.split(|c: char| !c.is_alphanumeric()).any(|word| word == key)
}
pub(super) fn own_address(provider: &str) -> bool {
![Provider::Virtualbox, Provider::Qemu, Provider::Utm].iter().any(|p| p.id() == provider)
}
impl Vagrant {
pub(super) async fn address(&self, cx: &ToolCx<'_>, machine: &str) -> Option<String> {
let read = super::read(cx, READ_LIMIT);
match retrying(cx.warn, "ssh-config", Rerun::Read, STATUS_PATIENCE, || vagrant::ssh_host(&read, machine)).await {
Ok(host) => host
.parse::<std::net::IpAddr>()
.map_or(true, |ip| !ip.is_loopback() && !ip.is_unspecified())
.then_some(host),
Err(e) => {
tracing::debug!(machine, error = %e, "the machine's address couldn't be read");
None
}
}
}
}
pub(super) fn verb_word(verb: Verb) -> &'static str {
match verb {
Verb::Halt => "halt",
Verb::Suspend => "suspend",
Verb::Provision => "provision",
Verb::Destroy => "destroy",
}
}
pub(super) fn one(machine: &str) -> Vec<String> {
vec![machine.to_owned()]
}
pub(super) fn checked_user(user: &str) -> Result<&str> {
let fine = !user.is_empty() && user.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
if fine {
Ok(user)
} else {
Err(Error::Unsupported {
what: format!("a console as `{user}`, which isn't an account name (letters, digits, `.`, `_`, `-`),"),
})
}
}