Skip to main content

agentmux_srv_core/backend/container/mounts/
host_name.rs

1//! The machine's own name inside a container agent's container, so `hostname` there (what a PR title's
2//! `<name>@<host>` uses; the commit trailers already carry it) says which machine the agent is on, not the
3//! container's random id.
4
5/// A host name Docker accepts as a container's hostname: its first label, letters, digits and dashes, at most 63
6/// characters. `None` for a name that has none of those.
7pub(super) fn container_hostname(raw: Option<&str>) -> Option<String> {
8    let first = raw?.trim().split('.').next()?;
9    let name: String = first.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(63).collect();
10    let name = name.trim_matches('-').to_string();
11    (!name.is_empty()).then_some(name)
12}
13
14/// The hostname a new container is given: this machine's name as the fleet writes it (`narko`, lower case), the same
15/// one the commit trailers carry (`AGENTMUX_GIT_HOST`).
16pub(in crate::backend::container) fn host_name_for_new_container() -> Option<String> {
17    container_hostname(crate::identity::github_tokens::host_label().as_deref())
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    #[test]
25    fn a_host_name_becomes_a_hostname_docker_accepts() {
26        assert_eq!(container_hostname(Some("charlie")).as_deref(), Some("charlie"));
27        assert_eq!(container_hostname(Some("Area54.local")).as_deref(), Some("Area54"), "the first label");
28        assert_eq!(container_hostname(Some("  Yas's MacBook_Pro ")).as_deref(), Some("YassMacBookPro"), "odd characters dropped");
29        assert_eq!(container_hostname(Some(&"a".repeat(80))).map(|n| n.len()), Some(63));
30        assert_eq!(container_hostname(Some("-x-")).as_deref(), Some("x"));
31        assert_eq!(container_hostname(Some("___")), None);
32        assert_eq!(container_hostname(Some("")), None);
33        assert_eq!(container_hostname(None), None);
34    }
35}