use crate::{EnvironmentFile}; use std::fmt::Display; use std::fs::File; use std::io::Read; use std::path::Path; #[derive(Debug, thiserror::Error)] #[allow(clippy::enum_variant_names)] pub enum EnvFsError { #[error(transparent)] IoError(#[from] std::io::Error), #[error(transparent)] ParseError(#[from] crate::EnvironmentFileError), #[error("The target environment variable exists, but is not Unicode")] EnvironmentError, } pub fn env_file() -> Result<EnvironmentFile, EnvFsError> { env_file_from_path(".env") } pub fn env_file_suffix(environment: impl Display) -> Result<EnvironmentFile, EnvFsError> { env_file_from_path(format!(".env.{}", environment)) } pub fn env_file_from_path(path: impl AsRef<Path>) -> Result<EnvironmentFile, EnvFsError> { let mut file = File::open(path)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; Ok(buffer.parse()?) } pub fn dotenv() -> Result<(), EnvFsError> { let file = env_file()?; file.apply().map_err(|_| EnvFsError::EnvironmentError) } pub fn dotenv_suffix(environment: impl Display) -> Result<(), EnvFsError> { let file = env_file_suffix(environment)?; file.apply().map_err(|_| EnvFsError::EnvironmentError) } pub fn dotenv_from(path: impl AsRef<Path>) -> Result<(), EnvFsError> { let file = env_file_from_path(path)?; file.apply().map_err(|_| EnvFsError::EnvironmentError) }