Files
keep/src/meta_plugin/hostname.rs
Andrew Phillips ea475386d6 fix: remove unused meta_name fields from meta plugin structs
Co-authored-by: aider (openai/andrew/openrouter/deepseek/deepseek-chat-v3.1) <aider@aider.chat>
2025-08-27 21:26:00 -03:00

346 lines
13 KiB
Rust

use crate::meta_plugin::{MetaPlugin, MetaPluginType};
#[derive(Debug, Clone, Default)]
pub struct HostnameMetaPlugin {
is_finalized: bool,
outputs: std::collections::HashMap<String, serde_yaml::Value>,
options: std::collections::HashMap<String, serde_yaml::Value>,
}
impl HostnameMetaPlugin {
pub fn new(
options: Option<std::collections::HashMap<String, serde_yaml::Value>>,
outputs: Option<std::collections::HashMap<String, serde_yaml::Value>>,
) -> HostnameMetaPlugin {
// Start with default options
let mut final_options = std::collections::HashMap::new();
// Set default values
final_options.insert("hostname".to_string(), serde_yaml::Value::String("true".to_string()));
final_options.insert("hostname_full".to_string(), serde_yaml::Value::Bool(true));
final_options.insert("hostname_short".to_string(), serde_yaml::Value::Bool(true));
// Override with provided options
if let Some(opts) = options {
for (key, value) in opts {
// Handle "false" string values by converting them to Bool(false)
if key == "hostname" || key == "hostname_full" || key == "hostname_short" {
if let serde_yaml::Value::String(s) = &value {
if s == "false" {
final_options.insert(key, serde_yaml::Value::Bool(false));
continue;
} else if s == "true" {
final_options.insert(key, serde_yaml::Value::Bool(true));
continue;
}
}
}
final_options.insert(key, value);
}
}
// Determine which outputs are enabled based on options
let hostname_enabled = match final_options.get("hostname") {
Some(serde_yaml::Value::Bool(b)) => *b,
Some(serde_yaml::Value::String(s)) => match s.as_str() {
"true" => true,
"false" => false,
"full" => true,
"short" => true,
_ => true,
},
_ => true,
};
let hostname_full_enabled = final_options.get("hostname_full")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let hostname_short_enabled = final_options.get("hostname_short")
.and_then(|v| v.as_bool())
.unwrap_or(true);
// Start with default outputs, setting disabled ones to None
let mut final_outputs = std::collections::HashMap::new();
// Handle hostname output
if hostname_enabled {
final_outputs.insert("hostname".to_string(), serde_yaml::Value::String("hostname".to_string()));
} else {
final_outputs.insert("hostname".to_string(), serde_yaml::Value::Null);
}
// Handle hostname_full output
if hostname_full_enabled {
final_outputs.insert("hostname_full".to_string(), serde_yaml::Value::String("hostname_full".to_string()));
} else {
final_outputs.insert("hostname_full".to_string(), serde_yaml::Value::Null);
}
// Handle hostname_short output
if hostname_short_enabled {
final_outputs.insert("hostname_short".to_string(), serde_yaml::Value::String("hostname_short".to_string()));
} else {
final_outputs.insert("hostname_short".to_string(), serde_yaml::Value::Null);
}
// Override with provided outputs, but only if they're enabled
if let Some(outs) = outputs {
for (key, value) in outs {
// Only add if the output is enabled
match key.as_str() {
"hostname" => if hostname_enabled {
final_outputs.insert(key, value);
},
"hostname_full" => if hostname_full_enabled {
final_outputs.insert(key, value);
},
"hostname_short" => if hostname_short_enabled {
final_outputs.insert(key, value);
},
_ => {
final_outputs.insert(key, value);
}
}
}
}
HostnameMetaPlugin {
is_finalized: false,
outputs: final_outputs,
options: final_options,
}
}
fn get_hostname(&self) -> String {
// First get the short hostname
let short_hostname = match gethostname::gethostname().into_string() {
Ok(hostname) => hostname,
Err(_) => return "unknown".to_string(),
};
// First try DNS resolution for both IPv4 and IPv6 addresses
// lookup_host should handle both A and AAAA records
if let Ok(addrs_iter) = dns_lookup::lookup_host(&short_hostname) {
// Collect addresses into a Vec to be able to use first()
let addrs: Vec<std::net::IpAddr> = addrs_iter.collect();
// Try each address (both IPv4 and IPv6)
for addr in &addrs {
// Convert to IpAddr for lookup_addr
let ip_addr = match addr {
std::net::IpAddr::V4(ipv4) => std::net::IpAddr::V4(*ipv4),
std::net::IpAddr::V6(ipv6) => std::net::IpAddr::V6(*ipv6),
};
// Perform reverse lookup for each address
match dns_lookup::lookup_addr(&ip_addr) {
Ok(full_hostname) => {
// Only use if it's different from the short hostname and looks like a FQDN
if full_hostname != short_hostname && full_hostname.contains('.') {
return full_hostname;
}
}
Err(_) => continue,
}
}
// If no reverse lookup worked, but we have addresses, try to construct FQDN
// from the first address's domain if the short hostname is part of a domain
if let Some(_first_addr) = addrs.first() {
// For local addresses, we might not get a reverse lookup, so try to infer
// from the system's domain name
if let Ok(domain) = std::process::Command::new("domainname").output() {
if domain.status.success() {
let domain_str = String::from_utf8_lossy(&domain.stdout).trim().to_string();
if !domain_str.is_empty() && domain_str != "(none)" {
return format!("{}.{}", short_hostname, domain_str);
}
}
}
}
}
// Fallback: try to get the FQDN using the system's hostname resolution
// This should give us the full hostname if configured
if let Ok(full_hostname) = std::process::Command::new("hostname")
.arg("-f")
.output()
{
if full_hostname.status.success() {
let full_hostname_str = String::from_utf8_lossy(&full_hostname.stdout).trim().to_string();
if !full_hostname_str.is_empty() && full_hostname_str != short_hostname {
return full_hostname_str;
}
}
}
// Final fallback: return the short hostname
short_hostname
}
}
impl MetaPlugin for HostnameMetaPlugin {
fn is_finalized(&self) -> bool {
self.is_finalized
}
fn set_finalized(&mut self, finalized: bool) {
self.is_finalized = finalized;
}
fn finalize(&mut self) -> crate::meta_plugin::MetaPluginResponse {
// If already finalized, don't process again
if self.is_finalized {
return crate::meta_plugin::MetaPluginResponse {
metadata: Vec::new(),
is_finalized: true,
};
}
// Mark as finalized
self.is_finalized = true;
crate::meta_plugin::MetaPluginResponse {
metadata: Vec::new(),
is_finalized: true,
}
}
fn update(&mut self, _data: &[u8]) -> crate::meta_plugin::MetaPluginResponse {
// If already finalized, don't process more data
if self.is_finalized {
return crate::meta_plugin::MetaPluginResponse {
metadata: Vec::new(),
is_finalized: true,
};
}
crate::meta_plugin::MetaPluginResponse {
metadata: Vec::new(),
is_finalized: false,
}
}
fn meta_type(&self) -> MetaPluginType {
MetaPluginType::Hostname
}
fn initialize(&mut self) -> crate::meta_plugin::MetaPluginResponse {
// If already finalized, don't process again
if self.is_finalized {
return crate::meta_plugin::MetaPluginResponse {
metadata: Vec::new(),
is_finalized: true,
};
}
let metadata = Vec::new();
// Get the full hostname
let full_hostname = self.get_hostname();
let short_hostname = full_hostname.split('.').next().unwrap_or(&full_hostname).to_string();
// Determine which hostnames to include based on options
let hostname_enabled = match self.options.get("hostname") {
Some(serde_yaml::Value::Bool(b)) => *b,
Some(serde_yaml::Value::String(s)) => match s.as_str() {
"true" => true,
"false" => false,
"full" => true,
"short" => true,
_ => true,
},
_ => true,
};
// Ensure that if hostname is explicitly set to false, it's disabled
// This handles cases where it might be set to "false" string which we converted above
let hostname_full_enabled = self.options.get("hostname_full")
.and_then(|v| v.as_bool())
.unwrap_or(true);
let hostname_short_enabled = self.options.get("hostname_short")
.and_then(|v| v.as_bool())
.unwrap_or(true);
// Determine which hostname value to use for the 'hostname' output
let hostname_value = match self.options.get("hostname") {
Some(serde_yaml::Value::String(s)) => match s.as_str() {
"full" => full_hostname.clone(),
"short" => short_hostname.clone(),
_ => {
// For 'true' or any other value, use gethostname()
gethostname::gethostname().into_string().unwrap_or_else(|_| "unknown".to_string())
}
},
_ => {
// Default behavior
gethostname::gethostname().into_string().unwrap_or_else(|_| "unknown".to_string())
}
};
// Update outputs based on enabled status
// Handle hostname output
if hostname_enabled {
if let Some(output_value) = self.outputs.get_mut("hostname") {
*output_value = serde_yaml::Value::String(hostname_value);
}
} else {
self.outputs.insert("hostname".to_string(), serde_yaml::Value::Null);
}
// Handle hostname_full output
if hostname_full_enabled {
if let Some(output_value) = self.outputs.get_mut("hostname_full") {
*output_value = serde_yaml::Value::String(full_hostname.clone());
}
} else {
self.outputs.insert("hostname_full".to_string(), serde_yaml::Value::Null);
}
// Handle hostname_short output
if hostname_short_enabled {
if let Some(output_value) = self.outputs.get_mut("hostname_short") {
*output_value = serde_yaml::Value::String(short_hostname);
}
} else {
self.outputs.insert("hostname_short".to_string(), serde_yaml::Value::Null);
}
// Mark as finalized since this plugin only needs to run once
self.is_finalized = true;
crate::meta_plugin::MetaPluginResponse {
metadata,
is_finalized: true,
}
}
fn outputs(&self) -> &std::collections::HashMap<String, serde_yaml::Value> {
&self.outputs
}
fn outputs_mut(&mut self) -> &mut std::collections::HashMap<String, serde_yaml::Value> {
&mut self.outputs
}
fn default_outputs(&self) -> Vec<String> {
vec![
"hostname".to_string(),
"hostname_full".to_string(),
"hostname_short".to_string(),
]
}
fn options(&self) -> &std::collections::HashMap<String, serde_yaml::Value> {
&self.options
}
fn options_mut(&mut self) -> &mut std::collections::HashMap<String, serde_yaml::Value> {
&mut self.options
}
}