use super::{errors::ConfigError, CipherStashConfigFile, CipherStashSecretConfigFile};
use std::{
fs::File,
io::{BufWriter, Write},
};
#[derive(Debug)]
pub struct DockerEnvFile {
regular: CipherStashConfigFile,
secret: CipherStashSecretConfigFile,
}
impl DockerEnvFile {
pub const DEFAULT_FILE_NAME: &str = ".env.proxy.docker";
pub fn new(regular: CipherStashConfigFile, secret: CipherStashSecretConfigFile) -> Self {
Self { regular, secret }
}
pub fn persist(
self,
file_path: impl AsRef<std::path::Path> + Clone,
) -> Result<(), ConfigError> {
let mut writer = BufWriter::new(File::create(&file_path).map_err(ConfigError::invalid)?);
self.regular
.env_data()?
.iter()
.chain(self.secret.env_data()?.iter())
.map(|(key, value)| format!("{key}={value}"))
.try_for_each(|line| {
writeln!(&mut writer, "{line}").map_err(|e| ConfigError::io(&e, file_path.clone()))
})?;
writer.flush().map_err(|e| ConfigError::io(&e, file_path))
}
}