use crate::config::Settings;
use crate::ssh::SshClient;
use std::io::Write;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SshTimeouts {
pub exec_timeout_secs: u64,
pub connect_timeout_secs: u64,
}
pub fn ssh_timeouts_from_settings(settings: &Settings) -> SshTimeouts {
SshTimeouts {
exec_timeout_secs: settings.ssh_timeout_secs,
connect_timeout_secs: settings.ssh_connect_timeout_secs,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NotifyPolicy {
#[default]
CliFlagOnly,
Always,
Never,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuntimeCtx {
pub debug: bool,
pub ssh_timeouts: Option<SshTimeouts>,
pub poll_interval_local_secs: u64,
pub poll_interval_remote_secs: u64,
pub retry_base_delay_secs: u64,
pub notify_policy: NotifyPolicy,
}
impl Default for RuntimeCtx {
fn default() -> Self {
Self::from_optional_settings(false, None)
}
}
impl RuntimeCtx {
pub fn from_settings(debug: bool, settings: &Settings) -> Self {
let notify_policy = match std::env::var("FLECHE_NOTIFY_POLICY").ok().as_deref() {
Some("always") => NotifyPolicy::Always,
Some("never") => NotifyPolicy::Never,
_ => NotifyPolicy::CliFlagOnly,
};
Self {
debug,
ssh_timeouts: Some(ssh_timeouts_from_settings(settings)),
poll_interval_local_secs: settings.poll_interval_local_secs,
poll_interval_remote_secs: settings.poll_interval_remote_secs,
retry_base_delay_secs: settings.retry_base_delay_secs,
notify_policy,
}
}
pub fn from_optional_settings(debug: bool, settings: Option<&Settings>) -> Self {
if let Some(settings) = settings {
Self::from_settings(debug, settings)
} else {
Self::from_settings(debug, &Settings::default())
}
}
pub fn ssh(&self, host: &str) -> SshClient {
ssh_client(host, self.debug, self.ssh_timeouts)
}
pub fn should_notify(&self, requested: bool) -> bool {
match self.notify_policy {
NotifyPolicy::CliFlagOnly => requested,
NotifyPolicy::Always => true,
NotifyPolicy::Never => false,
}
}
}
pub fn ssh_client(host: &str, debug: bool, timeouts: Option<SshTimeouts>) -> SshClient {
if let Some(timeouts) = timeouts {
SshClient::with_timeouts(
host,
debug,
timeouts.exec_timeout_secs,
timeouts.connect_timeout_secs,
)
} else {
SshClient::new(host, debug)
}
}
pub fn send_notification(message: &str) {
if std::env::var_os("TMUX").is_some() {
print!("\x1bPtmux;\x1b\x1b]9;fleche: {message}\x07\x1b\\");
} else {
print!("\x1b]9;fleche: {message}\x07");
}
let _ = std::io::stdout().flush();
}