use super::*;
pub fn resolve_offer_host<'a>(dest: &str, targets: &'a [RemoteTarget]) -> Option<&'a RemoteTarget> {
let host = dest.rsplit('@').next().unwrap_or(dest).trim();
if host.is_empty() {
return None;
}
targets
.iter()
.find(|t| t.alias.eq_ignore_ascii_case(host))
.or_else(|| {
targets.iter().find(|t| {
t.host_name
.as_deref()
.is_some_and(|h| h.eq_ignore_ascii_case(host))
})
})
}
pub fn ssh_reroot_decision<'a>(
argv: &[&str],
targets: &'a [RemoteTarget],
) -> Result<&'a RemoteTarget, String> {
match ssh_destination(argv) {
Some(dest) => resolve_offer_host(&dest, targets).ok_or_else(|| {
format!("{dest} is not in your ~/.ssh/config, so croft cannot open a workspace on it")
}),
None => Err(String::from("This pane is not an SSH session")),
}
}
pub type RefusedHosts = std::collections::BTreeMap<String, std::time::SystemTime>;
pub fn refusal_live(at: std::time::SystemTime, now: std::time::SystemTime) -> bool {
now.duration_since(at)
.is_ok_and(|age| age <= REFUSED_HOST_TTL)
}
pub fn offer_allowed(
host: &str,
disabled: bool,
excluded: &[String],
refused: &RefusedHosts,
now: std::time::SystemTime,
) -> bool {
if disabled {
return false;
}
if excluded.iter().any(|h| h.eq_ignore_ascii_case(host)) {
return false;
}
!refused
.get(&host.to_ascii_lowercase())
.is_some_and(|at| refusal_live(*at, now))
}
pub type CwdReport = (std::path::PathBuf, Option<String>);
pub fn remote_workspace_path(
host: &str,
at_offer: Option<&CwdReport>,
now: Option<&CwdReport>,
) -> Option<String> {
let (path, reporter) = now?;
let reporter = reporter.as_deref().filter(|h| !h.is_empty())?;
if crate::command_history::is_local_host(reporter) {
return None;
}
let fresh = at_offer != now;
if !fresh && !same_host(host, reporter) {
return None;
}
Some(path.to_string_lossy().into_owned())
}
pub(super) fn same_host(alias: &str, reported: &str) -> bool {
let (a, r) = (alias.to_ascii_lowercase(), reported.to_ascii_lowercase());
a == r
|| r.strip_prefix(&a).is_some_and(|rest| rest.starts_with('.'))
|| a.strip_prefix(&r).is_some_and(|rest| rest.starts_with('.'))
}
pub fn ssh_pane_samples(
named: &[(i32, i32, String)],
targets: impl FnOnce() -> Vec<RemoteTarget>,
cmdline: impl Fn(i32) -> Option<Vec<String>>,
) -> Vec<(i32, Option<String>)> {
let mut targets = Some(targets);
let mut config: Vec<RemoteTarget> = Vec::new();
let mut out = Vec::with_capacity(named.len());
for (shell, fg, name) in named {
if shell == fg || !is_ssh_program(name) {
out.push((*shell, None));
continue;
}
let Some(argv) = cmdline(*fg) else {
continue;
};
if let Some(parse) = targets.take() {
config = parse();
}
let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
out.push((*shell, ssh_offer_host(&argv, &config)));
}
out
}
pub fn is_ssh_program(name: &str) -> bool {
let base = name.rsplit('/').next().unwrap_or(name);
SSH_PROGRAMS.contains(&base)
}
pub fn ssh_offer_host(argv: &[&str], targets: &[RemoteTarget]) -> Option<String> {
ssh_reroot_decision(argv, targets)
.ok()
.map(|t| t.alias.clone())
}
pub const REFUSED_HOST_TTL: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
pub fn refused_hosts_path(cache_dir: &Path) -> PathBuf {
cache_dir.join("remote-offer-refused.json")
}
pub fn load_refused_hosts(path: &Path, now: std::time::SystemTime) -> RefusedHosts {
let Ok(raw) = std::fs::read_to_string(path) else {
return Default::default();
};
let Ok(map) = serde_json::from_str::<std::collections::BTreeMap<String, u64>>(&raw) else {
return Default::default();
};
map.into_iter()
.map(|(h, at)| {
(
h.to_ascii_lowercase(),
std::time::UNIX_EPOCH + std::time::Duration::from_secs(at),
)
})
.filter(|(_, at)| refusal_live(*at, now))
.collect()
}
pub fn forget_refused_host(path: &Path, host: &str) -> std::io::Result<()> {
let Ok(raw) = std::fs::read_to_string(path) else {
return Ok(());
};
let mut map: std::collections::BTreeMap<String, u64> =
serde_json::from_str(&raw).unwrap_or_default();
if map.remove(&host.to_ascii_lowercase()).is_none() {
return Ok(());
}
let body = serde_json::to_string_pretty(&map).map_err(std::io::Error::other)?;
std::fs::write(path, body)
}
pub fn remember_refused_host(
path: &Path,
host: &str,
now: std::time::SystemTime,
) -> std::io::Result<()> {
let mut map: std::collections::BTreeMap<String, u64> = std::fs::read_to_string(path)
.ok()
.and_then(|raw| serde_json::from_str(&raw).ok())
.unwrap_or_default();
let now_secs = now
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
map.insert(host.to_ascii_lowercase(), now_secs);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let body = serde_json::to_string_pretty(&map).map_err(std::io::Error::other)?;
std::fs::write(path, body)
}