just/src/load_dotenv.rs

52 lines
1.2 KiB
Rust
Raw Normal View History

use super::*;
2018-03-05 13:21:35 -08:00
const DEFAULT_DOTENV_FILENAME: &str = ".env";
pub(crate) fn load_dotenv(
config: &Config,
settings: &Settings,
working_directory: &Path,
) -> RunResult<'static, BTreeMap<String, String>> {
let dotenv_filename = config
.dotenv_filename
.as_ref()
.or(settings.dotenv_filename.as_ref());
let dotenv_path = config
.dotenv_path
.as_ref()
.or(settings.dotenv_path.as_ref());
2024-02-27 22:52:43 -08:00
if !settings.dotenv_load.unwrap_or_default() && dotenv_filename.is_none() && dotenv_path.is_none()
{
return Ok(BTreeMap::new());
}
if let Some(path) = dotenv_path {
return load_from_file(path);
}
let filename = dotenv_filename.map_or(DEFAULT_DOTENV_FILENAME, |s| s.as_str());
for directory in working_directory.ancestors() {
let path = directory.join(filename);
if path.is_file() {
return load_from_file(&path);
}
2018-03-05 13:21:35 -08:00
}
Ok(BTreeMap::new())
2018-03-05 13:21:35 -08:00
}
fn load_from_file(path: &Path) -> RunResult<'static, BTreeMap<String, String>> {
2022-12-14 20:32:27 -08:00
let iter = dotenvy::from_path_iter(path)?;
let mut dotenv = BTreeMap::new();
for result in iter {
let (key, value) = result?;
if env::var_os(&key).is_none() {
dotenv.insert(key, value);
}
}
Ok(dotenv)
}