use std::path::Path;
use crate::Result;
use crate::events::WarningCode;
use crate::formats::Seen;
use crate::project::platform::Protocol;
const FILE: &str = "host-ports.json";
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Kept {
pub(crate) machine: String,
pub(crate) guest: u16,
pub(crate) protocol: Protocol,
pub(crate) host: u16,
}
pub(super) fn kept(state_dir: &Path) -> Result<Vec<Kept>> {
crate::store::read_json(&state_dir.join(FILE))
}
pub(super) fn keep(state_dir: &Path, seen: &Seen, warn: &(dyn Fn(WarningCode, &str) + Send + Sync)) -> Result<()> {
let mut kept = kept(state_dir)?;
let before = kept.clone();
for machine in &seen.machines {
for p in &machine.published {
let (guest, protocol, host) = (p.guest.get(), p.protocol.unwrap_or(Protocol::Tcp), p.host.get());
match kept
.iter_mut()
.find(|k| k.machine == machine.name && k.guest == guest && k.protocol == protocol)
{
Some(k) if k.host != host => {
let proto = crate::encoding::wire_name(&protocol);
warn(
WarningCode::PortsMoved,
&format!("`{}`'s port {guest}/{proto} moved from host port {} to {host}", machine.name, k.host),
);
k.host = host;
}
Some(_) => {}
None => kept.push(Kept {
machine: machine.name.clone(),
guest,
protocol,
host,
}),
}
}
}
if kept == before {
return Ok(());
}
crate::store::write_json(&state_dir.join(FILE), &kept)
}
pub(super) fn forget(state_dir: &Path) -> Result<()> {
crate::store::remove(&state_dir.join(FILE))
}
pub(crate) fn var_name(machine: &str, guest: u16, protocol: Protocol) -> String {
let name: String = machine
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_uppercase() } else { '_' })
.collect();
let proto = match protocol {
Protocol::Tcp => "TCP",
Protocol::Udp => "UDP",
};
format!("HOST_PORT_{name}_{guest}_{proto}")
}
pub(super) fn env(kept: &[Kept]) -> Vec<(String, String)> {
let named: Vec<(String, &Kept)> = kept.iter().map(|k| (var_name(&k.machine, k.guest, k.protocol), k)).collect();
named
.iter()
.filter(|(name, k)| !named.iter().any(|(other, o)| other == name && o.machine != k.machine))
.map(|(name, k)| (name.clone(), k.host.to_string()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn k(machine: &str, guest: u16, host: u16) -> Kept {
Kept {
machine: machine.to_owned(),
guest,
protocol: Protocol::Tcp,
host,
}
}
#[test]
fn a_kept_ports_variable_names_its_machine_guest_port_and_protocol() {
assert_eq!(var_name("web", 80, Protocol::Tcp), "HOST_PORT_WEB_80_TCP");
assert_eq!(var_name("web-1.stack", 53, Protocol::Udp), "HOST_PORT_WEB_1_STACK_53_UDP");
assert_eq!(var_name("web·1", 8080, Protocol::Tcp), "HOST_PORT_WEB_1_8080_TCP", "one `_` per character");
let vars = env(&[k("web", 80, 2200), k("web-1", 22, 2222), k("web_1", 22, 2223)]);
assert_eq!(
vars,
[("HOST_PORT_WEB_80_TCP".to_owned(), "2200".to_owned())],
"web-1 and web_1 collide: neither"
);
}
}