use std::path::{Path, PathBuf};
use openmoat_hosts::{Host, InstallSpec};
use super::{Lock, key};
fn install(host: Host) -> Option<&'static InstallSpec> {
host.spec().install.as_ref()
}
fn shapes_drift(install: &InstallSpec) -> bool {
!install.relaxed_keys.is_empty() || !install.unpinned_keys.is_empty()
}
fn legacy_owner(stored: &Path) -> Option<Host> {
let name = stored.file_name()?;
let named: Vec<Host> = Host::ALL
.into_iter()
.filter(|host| install(*host).is_some_and(|i| shapes_drift(i) && name == i.config_file))
.collect();
if let Some(host) = named.iter().find(|host| placed(stored, **host)) {
return Some(*host);
}
let anywhere: Vec<&Host> = named
.iter()
.filter(|host| install(**host).is_some_and(|i| !i.variable_names_home()))
.collect();
match anywhere.as_slice() {
[host] => Some(**host),
_ => None,
}
}
fn placed(stored: &Path, host: Host) -> bool {
install(host).is_some_and(|i| stored.ends_with(Path::new(i.dir_name).join(i.config_file)))
}
impl Lock {
pub(super) fn owners(&self) -> Vec<(PathBuf, Host)> {
self.owners_with(&[])
}
pub(super) fn owners_with(&self, installed: &[(PathBuf, Host)]) -> Vec<(PathBuf, Host)> {
self.entries
.keys()
.filter_map(|stored| {
let host = self.hook_owner(stored)?;
let kept = self.hook_owners.is_some()
|| self.form_host(stored) == Some(host)
|| placed(Path::new(stored), host)
|| installed
.iter()
.any(|(p, h)| *h == host && key(p) == *stored);
kept.then(|| (PathBuf::from(stored), host))
})
.collect()
}
pub(super) fn hook_owner(&self, stored: &str) -> Option<Host> {
match &self.hook_owners {
Some(owners) => owners.get(stored)?.parse().ok(),
None => self
.form_host(stored)
.or_else(|| legacy_owner(Path::new(stored))),
}
}
pub(super) fn unpinned(&self, stored: &str) -> &'static [&'static str] {
unpinned_of(self.hook_owner(stored))
}
pub(super) fn relaxing(&self, stored: &str) -> Option<&'static InstallSpec> {
install(self.hook_owner(stored)?).filter(|i| !i.relaxed_keys.is_empty())
}
}
pub(super) fn unpinned_of(owner: Option<Host>) -> &'static [&'static str] {
owner.and_then(install).map_or(&[], |i| i.unpinned_keys)
}
#[cfg(test)]
pub(super) fn assumed(path: &Path) -> Option<Host> {
legacy_owner(path)
}
#[cfg(test)]
mod tests;