serenade_config/
dotenv.rs1use std::collections::HashSet;
4use std::path::{Path, PathBuf};
5
6use crate::ConfigError;
7
8pub fn load_dotenv(project_dir: impl AsRef<Path>, environment: &str) -> Result<(), ConfigError> {
23 let project_dir = project_dir.as_ref();
24 let env = environment.trim();
25 let preexisting: HashSet<String> = std::env::vars().map(|(key, _)| key).collect();
26
27 let mut files = vec![PathBuf::from(".env")];
28 if env != "prod" {
29 files.push(PathBuf::from(".env.local"));
30 }
31 if !env.is_empty() {
32 files.push(PathBuf::from(format!(".env.{env}")));
33 files.push(PathBuf::from(format!(".env.{env}.local")));
34 }
35
36 for relative in files {
37 let path = project_dir.join(&relative);
38 if !path.is_file() {
39 continue;
40 }
41 let iter = dotenvy::from_path_iter(&path).map_err(|source| ConfigError::Dotenv {
42 path: path.clone(),
43 message: source.to_string(),
44 })?;
45 for item in iter {
46 let (key, value) = item.map_err(|source| ConfigError::Dotenv {
47 path: path.clone(),
48 message: source.to_string(),
49 })?;
50 if preexisting.contains(&key) {
51 continue;
52 }
53 unsafe {
55 std::env::set_var(key, value);
56 }
57 }
58 }
59 Ok(())
60}