From ff376ef27c7f045fe1e8683ab7ee913815a2948c Mon Sep 17 00:00:00 2001 From: Joakim Hulthe Date: Wed, 30 Jun 2021 14:26:17 +0200 Subject: [PATCH] Add fallback if /etc/hostname doesn't exist --- manager/src/builder.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/manager/src/builder.rs b/manager/src/builder.rs index 9282771..3a63d56 100644 --- a/manager/src/builder.rs +++ b/manager/src/builder.rs @@ -6,19 +6,16 @@ use futures::future::join_all; use std::ffi::OsStr; use std::io::ErrorKind; use std::path::PathBuf; +use std::process::Command; +use std::str::from_utf8; use tokio::fs::{copy, create_dir, read_dir, read_to_string, write}; use tokio::join; pub const TEMPLATE_EXTENSION: &str = "tpl"; pub async fn build_tree(cfg: &Config) -> Result<(), Errors> { - let hostname_path: PathBuf = "/etc/hostname".into(); - let hostname = read_to_string(&hostname_path) - .await - .with_location(&hostname_path)?; - let mut env = Env::new(); - env.insert("hostname".into(), Value::Str(hostname)); + env.insert("hostname".into(), Value::Str(get_hostname().await)); for flag in &cfg.flags { env.insert(flag.to_string(), Value::Bool(true)); @@ -118,3 +115,24 @@ async fn file(cfg: &Config, env: &Env, relative: PathBuf) -> Result<(), Error> { Ok(()) } + +async fn get_hostname() -> String { + async fn read_hostname_file() -> Option { + read_to_string("/etc/hostname").await.ok() + } + + // TODO: should be async + fn run_hostname_cmd() -> Option { + Command::new("hostname") + .output() + .ok() + .and_then(|out| from_utf8(&out.stdout).ok().map(str::to_string)) + } + + read_hostname_file() + .await + .or_else(|| run_hostname_cmd()) + .unwrap_or_else(|| String::new()) + .trim() + .to_string() +}