Load templating variables from file

This commit is contained in:
2021-11-14 20:26:51 +01:00
parent 7cc798fcab
commit 61676bc6ee
5 changed files with 50 additions and 2 deletions

View File

@ -1,8 +1,9 @@
use crate::error::{Error, ErrorLocation, Errors};
use crate::error::{Error, ErrorLocation, Errors, InnerError};
use crate::Config;
use async_recursion::async_recursion;
use blueprint::{parse_template, Env, Value};
use futures::future::join_all;
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::io::ErrorKind;
@ -19,6 +20,29 @@ pub async fn build_tree(cfg: &Config) -> Result<(), Errors> {
env.insert("hostname".into(), Value::Str(get_hostname().await));
env.insert("username".into(), Value::Str(get_username()));
debug!("trying to read {:?}", cfg.variables_path);
if let Ok(s) = read_to_string(&cfg.variables_path).await {
debug!("parsing {:?}", cfg.variables_path);
let variables: HashMap<String, toml::Value> =
toml::de::from_str(&s).with_location(&cfg.variables_path)?;
for (key, toml_value) in variables {
let value = match toml_value {
toml::Value::String(s) => Value::Str(s),
toml::Value::Boolean(b) => Value::Bool(b),
_ => {
return Err(InnerError::TypeErr
.with_location(&cfg.variables_path)
.into())
}
};
env.insert(key, value);
}
} else {
debug!("failed to read {:?}", cfg.variables_path);
}
for flag in &cfg.flags {
env.insert(flag.to_string(), Value::Bool(true));
}

View File

@ -19,6 +19,12 @@ pub enum InnerError {
#[error("Failed to parse template file")]
TemplateErr(#[from] blueprint::Error),
#[error("Failed to parse toml file")]
TomlErr(#[from] toml::de::Error),
#[error("Unsupported variable type")]
TypeErr,
}
impl From<Vec<Error>> for Errors {

View File

@ -26,6 +26,9 @@ struct Opt {
#[structopt(short, long)]
link_dir: Option<PathBuf>,
#[structopt(long = "variables")]
variables_path: Option<PathBuf>,
#[structopt(short, long)]
print_variables: bool,
@ -40,6 +43,7 @@ pub struct Config {
template_dir: PathBuf,
build_dir: PathBuf,
link_dir: PathBuf,
variables_path: PathBuf,
flags: Vec<String>,
}
@ -77,6 +81,9 @@ async fn run() -> Result<(), Errors> {
link_dir: opt
.link_dir
.unwrap_or_else(|| env::var("HOME").expect("$HOME").into()),
variables_path: opt
.variables_path
.unwrap_or_else(|| xdg_dirs.get_config_file("variables.toml")),
flags: opt.flags,
};