refactor: modularize codebase and improve type safety

This commit is contained in:
2026-02-18 03:39:29 -07:00
parent 57a3287f38
commit 8877c61aed
10 changed files with 358 additions and 327 deletions

View File

@@ -1,13 +1,19 @@
use crate::log::LogLevel;
use crate::spec::Specification;
use crate::tmpl;
use crate::{LogLevel, info, verb};
use serde_json::Value;
use crate::{dbug, info, verb};
use std::io::Write;
pub struct RenderedConfig {
pub struct DeviceConfigBundle {
pub hostname: String,
pub configs: Vec<ConfigVariant>,
pub spec: Specification,
pub platform: String,
}
pub struct ConfigVariant {
pub name: String,
pub configs: Vec<Configuration>,
pub spec: Value,
}
pub struct Configuration {
@@ -15,15 +21,12 @@ pub struct Configuration {
pub data: String,
}
impl RenderedConfig {
pub fn from_spec(
spec: &Specification,
dbg: LogLevel,
) -> Result<Self, Box<dyn std::error::Error>> {
let context = Self::get_context(&spec);
impl DeviceConfigBundle {
pub fn from_spec(spec: Specification) -> Result<Self, Box<dyn std::error::Error>> {
let mut context = Self::get_context(&spec);
let hostname = Self::get_hostname(&context, &spec);
info!(dbg, "Rendering {}", hostname);
info!(&spec.loglevel, "Rendering {}", hostname);
let base_dir = std::path::Path::new("./tmpl").join(spec.get_layer());
let structure_path = base_dir.join("structure.yaml");
@@ -31,28 +34,38 @@ impl RenderedConfig {
.map_err(|e| format!("Failed to parse {}: {}", structure_path.display(), e))?;
let mut renderer = tera::Tera::default();
renderer.add_raw_templates(structure.load_template_data(&base_dir))?;
renderer.add_raw_templates(structure.load_template_data(&base_dir, spec.loglevel))?;
dbug!(&spec.loglevel, "Processing templates for {}", hostname);
let mut configs = Vec::new();
for template_name in &structure.files {
verb!(dbg, " | {}", &template_name);
if !renderer.get_template_names().any(|n| n == template_name) {
continue;
}
match renderer.render(template_name, &context) {
Ok(rendered) => configs.push(Configuration {
name: template_name.clone(),
data: rendered,
}),
Err(e) => Self::log_tera_error(template_name, &e),
let mut config_variants = Vec::new();
for variant in &structure.variations {
context.insert(variant, &true);
let mut configs = Vec::new();
for template_name in &structure.files {
dbug!(&spec.loglevel, " | {}.{}", &template_name, variant);
if !renderer.get_template_names().any(|n| n == template_name) {
continue;
}
match renderer.render(template_name, &context) {
Ok(data) => configs.push(Configuration {
name: template_name.clone(),
data,
}),
Err(e) => Self::log_tera_error(template_name, &e),
}
}
config_variants.push(ConfigVariant {
name: String::from(variant),
configs,
});
context.remove(variant);
}
Ok(Self {
hostname,
configs,
spec: spec.compiled.clone(),
configs: config_variants,
spec,
platform: structure.platform,
})
}
@@ -61,13 +74,7 @@ impl RenderedConfig {
.get("hostname")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| {
spec.device
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
.to_string()
})
.unwrap_or_else(|| spec.components.get_hostname())
}
fn get_context(spec: &Specification) -> tera::Context {
@@ -90,33 +97,43 @@ impl RenderedConfig {
eprintln!("[tera] {}: {}", name, chain);
}
pub fn output(self: Self, outdir: &str, dbg: LogLevel) {
info!(dbg, "Writing Output:");
pub fn output_artifacts(self: Self) {
info!(&self.spec.loglevel, "Writing Output:");
let out_path = std::path::Path::new(outdir).join(self.hostname);
if out_path.exists() {
std::fs::remove_dir_all(&out_path).ok();
let device_outpath = std::path::Path::new(&self.spec.outpath).join(self.hostname);
if device_outpath.exists() {
std::fs::remove_dir_all(&device_outpath).ok();
}
std::fs::create_dir_all(&out_path).ok();
std::fs::create_dir_all(&device_outpath).ok();
let merged_config_path = out_path.join("all.conf");
let mut all_file: std::fs::File = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&merged_config_path)
.expect("unable to open");
for variant_configs in &self.configs {
let out_path = device_outpath.join(&variant_configs.name);
std::fs::create_dir_all(&out_path).ok();
for config in &self.configs {
let template_path = out_path.join(format!("{}.tera", &config.name));
verb!(dbg, " | {}", &template_path.display());
std::fs::write(&template_path, &config.data).ok();
all_file.write_all(&config.data.as_bytes()).ok();
let merged_config_path =
device_outpath.join(format!("all.{}.{}", variant_configs.name, &self.platform));
let mut all_file: std::fs::File = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&merged_config_path)
.expect("unable to open");
for config in &variant_configs.configs {
let config_outpath = out_path.join(format!("{}.{}", &config.name, &self.platform));
std::fs::create_dir_all(&config_outpath).ok();
verb!(&self.spec.loglevel, " | {}", &config_outpath.display());
std::fs::write(&config_outpath, &config.data).ok();
all_file.write_all(&config.data.as_bytes()).ok();
}
info!(&self.spec.loglevel, " | {} ", &merged_config_path.display());
}
let spec: String = yaml_serde::to_string(&self.spec).unwrap();
let compiled_spec_path = out_path.join("compiled-spec.yaml");
verb!(dbg, " | {}", &compiled_spec_path.display());
std::fs::write(&compiled_spec_path, spec).ok();
info!(dbg, " | {} ", &merged_config_path.display());
let compiled_spec_path = device_outpath.join("context.yaml");
verb!(&self.spec.loglevel, " | {}", &compiled_spec_path.display());
std::fs::write(
&compiled_spec_path,
yaml_serde::to_string(&self.spec.compiled).unwrap(),
)
.ok();
}
}