use std::{
fs::create_dir_all,
io::Write,
path::{Path, PathBuf},
};
use garde::Validate;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
generators::GenerationError,
internal::sops::{self, SopsError},
recipe::{
file_recipe::{FileFormat, FileRecipe},
generator_tree::GeneratorTree,
},
};
pub mod file_recipe;
pub mod generator_tree;
#[derive(Debug, Serialize, Deserialize, Validate, PartialEq)]
pub struct Recipe {
#[serde(default)]
#[garde(dive)]
pub shared: GeneratorTree,
#[garde(dive)]
pub files: Vec<FileRecipe>,
}
#[derive(Debug, Error)]
pub enum RecipeError {
#[error("IO error: {0}")]
IOError(#[from] std::io::Error),
#[error("Deserialize error: {0}")]
DeserializeError(#[from] serde_saphyr::Error),
}
#[derive(Debug, Error)]
pub enum RecipeGenerationError {
#[error("IO error: {0}")]
IOError(#[from] std::io::Error),
#[error("Serialize error: {0}")]
SerializeError(String),
#[error("Unknown format for file: {0}")]
FormatError(PathBuf),
#[error("Generation error: {0}")]
GenerationError(#[from] GenerationError),
#[error("Sops error: {0}")]
SopsError(#[from] SopsError),
}
impl From<serde_saphyr::ser::Error> for RecipeGenerationError {
fn from(err: serde_saphyr::ser::Error) -> Self {
RecipeGenerationError::SerializeError(err.to_string())
}
}
impl From<serde_envfile::Error> for RecipeGenerationError {
fn from(err: serde_envfile::Error) -> Self {
RecipeGenerationError::SerializeError(err.to_string())
}
}
impl From<serde_json::Error> for RecipeGenerationError {
fn from(err: serde_json::Error) -> Self {
RecipeGenerationError::SerializeError(err.to_string())
}
}
impl From<toml::ser::Error> for RecipeGenerationError {
fn from(err: toml::ser::Error) -> Self {
RecipeGenerationError::SerializeError(err.to_string())
}
}
impl Recipe {
pub fn from_file(file: &Path) -> Result<Self, RecipeError> {
let file = std::fs::File::open(file)?;
Ok(serde_saphyr::from_reader_valid(file)?)
}
pub fn generate_files(&self) -> Result<(), RecipeGenerationError> {
let shared_secrets = self.shared.generate()?;
for file_recipe in &self.files {
let output_format = if let Some(format) = &file_recipe.format {
format
} else {
&FileFormat::try_from_path(&file_recipe.path)
.ok_or_else(|| RecipeGenerationError::FormatError(file_recipe.path.clone()))?
};
let secret_tree = file_recipe.generate(&shared_secrets)?;
let output_string = match output_format {
FileFormat::Env => serde_envfile::to_string(&secret_tree)?,
FileFormat::Json => serde_json::to_string_pretty(&secret_tree)?,
FileFormat::Toml => toml::to_string(&secret_tree)?,
FileFormat::Yaml => serde_saphyr::to_string(&secret_tree)?,
};
create_dir_all(
file_recipe
.path
.parent()
.unwrap_or_else(|| std::path::Path::new(".")),
)?;
let to_write = if file_recipe.sops.enable {
sops::encrypt(
&file_recipe.path,
output_string,
&file_recipe.sops,
(*output_format).into(),
)?
} else {
output_string
};
let mut file = std::fs::File::create(file_recipe.path.clone())?;
file.write_all(to_write.as_bytes())?;
}
Ok(())
}
}