Add fallback if /etc/hostname doesn't exist

This commit is contained in:
2021-06-30 14:26:17 +02:00
parent ce84eac3c3
commit ff376ef27c

View File

@ -6,19 +6,16 @@ use futures::future::join_all;
use std::ffi::OsStr; use std::ffi::OsStr;
use std::io::ErrorKind; use std::io::ErrorKind;
use std::path::PathBuf; 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::fs::{copy, create_dir, read_dir, read_to_string, write};
use tokio::join; use tokio::join;
pub const TEMPLATE_EXTENSION: &str = "tpl"; pub const TEMPLATE_EXTENSION: &str = "tpl";
pub async fn build_tree(cfg: &Config) -> Result<(), Errors> { 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(); 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 { for flag in &cfg.flags {
env.insert(flag.to_string(), Value::Bool(true)); env.insert(flag.to_string(), Value::Bool(true));
@ -118,3 +115,24 @@ async fn file(cfg: &Config, env: &Env, relative: PathBuf) -> Result<(), Error> {
Ok(()) Ok(())
} }
async fn get_hostname() -> String {
async fn read_hostname_file() -> Option<String> {
read_to_string("/etc/hostname").await.ok()
}
// TODO: should be async
fn run_hostname_cmd() -> Option<String> {
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()
}