use std::path::{Path, PathBuf};
use garde::Validate;
use serde::{Deserialize, Serialize};
use crate::{
generators::GenerationError,
internal::{
garde::{is_file_path, is_sops_args_valid},
sops::SopsFormat,
},
recipe::generator_tree::{GeneratorTreeWithRef, SecretTree},
};
pub use crate::internal::sops::SopsCreationRule;
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FileFormat {
Env,
Json,
Toml,
Yaml,
}
impl FileFormat {
pub fn try_from_str(ext: &str) -> Option<Self> {
let ext = ext.trim_start_matches(".");
match ext {
"env" => Some(Self::Env),
"json" => Some(Self::Json),
"toml" => Some(Self::Toml),
"yaml" | "yml" => Some(Self::Yaml),
_ => None,
}
}
pub fn try_from_path(path: &Path) -> Option<Self> {
Self::try_from_str(path.extension().or(path.file_name())?.to_str()?)
}
}
impl From<FileFormat> for SopsFormat {
fn from(val: FileFormat) -> Self {
match val {
FileFormat::Env => SopsFormat::Env,
FileFormat::Json => SopsFormat::Json,
FileFormat::Toml => SopsFormat::Binary, FileFormat::Yaml => SopsFormat::Yaml,
}
}
}
#[derive(Debug, Serialize, Deserialize, Validate, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct FileRecipe {
#[garde(custom(is_file_path))]
pub path: PathBuf,
#[garde(dive)]
pub content: GeneratorTreeWithRef,
#[garde(skip)]
pub format: Option<FileFormat>,
#[garde(custom(is_sops_args_valid))]
#[serde(default)]
pub sops: SopsCreationRule,
}
impl FileRecipe {
pub fn generate(&self, shared_secrets: &SecretTree) -> Result<SecretTree, GenerationError> {
self.content.generate(shared_secrets)
}
}