use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::Path;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::prefix::is_encrypted;
use crate::{Encryptor, Error, Result, StringEncryptor};
#[derive(Debug, Clone)]
pub struct ConfigLoader<E: StringEncryptor = Encryptor> {
encryptor: E,
}
impl ConfigLoader<Encryptor> {
pub fn new(password: &str) -> Result<Self> {
Ok(Self {
encryptor: Encryptor::new(password)?,
})
}
}
impl<E: StringEncryptor> ConfigLoader<E> {
pub fn with_encryptor(encryptor: E) -> Self {
Self { encryptor }
}
pub fn encryptor(&self) -> &E {
&self.encryptor
}
pub fn load_env_file(&self, path: impl AsRef<Path>) -> Result<HashMap<String, String>> {
self.load_key_values(path.as_ref(), '=')
}
pub fn load_yaml(&self, path: impl AsRef<Path>) -> Result<HashMap<String, String>> {
self.load_key_values(path.as_ref(), ':')
}
fn load_key_values(&self, path: &Path, separator: char) -> Result<HashMap<String, String>> {
let file = fs::File::open(path)?;
let mut config = HashMap::new();
for line in BufReader::new(file).lines() {
let line = line?;
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((key, value)) = line.split_once(separator) else {
continue;
};
let key = key.trim();
let value = value.trim().trim_matches(|c| c == '"' || c == '\'');
let value = if is_encrypted(value) {
self.encryptor
.decrypt_prefixed(value)
.map_err(|err| Error::key_decrypt(key, err))?
} else {
value.to_owned()
};
config.insert(key.to_owned(), value);
}
Ok(config)
}
pub fn load_json<T: DeserializeOwned>(&self, path: impl AsRef<Path>) -> Result<T> {
let data = fs::read_to_string(path)?;
let mut value: Value = serde_json::from_str(&data)?;
self.decrypt_json_value(&mut value);
Ok(serde_json::from_value(value)?)
}
pub fn decrypt_json_value(&self, value: &mut Value) {
match value {
Value::String(s) => {
if is_encrypted(s) {
if let Ok(decrypted) = self.encryptor.decrypt_prefixed(s) {
*s = decrypted;
}
}
}
Value::Array(items) => items.iter_mut().for_each(|v| self.decrypt_json_value(v)),
Value::Object(map) => map.values_mut().for_each(|v| self.decrypt_json_value(v)),
Value::Null | Value::Bool(_) | Value::Number(_) => {}
}
}
pub fn set_to_env(&self, path: impl AsRef<Path>) -> Result<()> {
let config = self.load_env_file(path)?;
for (key, value) in config {
set_env_var(&key, &value)?;
}
Ok(())
}
}
#[allow(unsafe_code, unused_unsafe)]
fn set_env_var(key: &str, value: &str) -> Result<()> {
if key.is_empty() || key.contains('=') || key.contains('\0') || value.contains('\0') {
return Err(Error::InvalidParameter(format!(
"cannot set environment variable {key:?}"
)));
}
unsafe { std::env::set_var(key, value) };
Ok(())
}