use nix::unistd;
#[must_use]
pub fn local_hostname() -> String {
let raw = unistd::gethostname()
.ok()
.and_then(|os| os.into_string().ok())
.unwrap_or_default();
sanitize_hostname(&raw)
}
fn sanitize_hostname(raw: &str) -> String {
let cleaned: String = raw
.chars()
.map(|c| if c.is_ascii_graphic() { c } else { '_' })
.collect();
if cleaned.is_empty() {
"localhost".to_string()
} else {
cleaned
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hostname_is_non_empty_ascii() {
let h = local_hostname();
assert!(!h.is_empty());
for c in h.chars() {
assert!(
c.is_ascii_graphic(),
"non-ASCII-graphic char in hostname: {c:?}"
);
}
}
#[test]
fn sanitize_replaces_non_graphic_and_falls_back_when_empty() {
assert_eq!(sanitize_hostname(""), "localhost");
assert_eq!(sanitize_hostname("a b\tc"), "a_b_c");
assert_eq!(sanitize_hostname(" "), "___");
assert_eq!(sanitize_hostname("node-1.dc"), "node-1.dc");
}
}