2022-06-18 21:56:31 -07:00
|
|
|
use super::*;
|
2018-03-05 13:21:35 -08:00
|
|
|
|
2020-07-19 05:01:46 -07:00
|
|
|
pub(crate) fn load_dotenv(
|
2021-03-30 17:30:32 -07:00
|
|
|
config: &Config,
|
2021-03-28 22:38:07 -07:00
|
|
|
settings: &Settings,
|
2021-03-30 17:30:32 -07:00
|
|
|
working_directory: &Path,
|
2020-07-19 05:01:46 -07:00
|
|
|
) -> RunResult<'static, BTreeMap<String, String>> {
|
2023-10-11 22:04:46 -07:00
|
|
|
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-05-30 16:12:07 -07:00
|
|
|
if !settings.dotenv_load
|
|
|
|
&& dotenv_filename.is_none()
|
|
|
|
&& dotenv_path.is_none()
|
|
|
|
&& !settings.dotenv_required
|
2024-02-27 22:52:43 -08:00
|
|
|
{
|
2021-03-28 22:38:07 -07:00
|
|
|
return Ok(BTreeMap::new());
|
|
|
|
}
|
|
|
|
|
2023-10-11 22:04:46 -07:00
|
|
|
if let Some(path) = dotenv_path {
|
2024-06-13 13:21:00 -07:00
|
|
|
let path = working_directory.join(path);
|
2024-05-30 16:12:07 -07:00
|
|
|
if path.is_file() {
|
2024-06-13 13:21:00 -07:00
|
|
|
return load_from_file(&path);
|
2024-05-30 16:12:07 -07:00
|
|
|
}
|
2021-08-08 22:37:35 -07:00
|
|
|
}
|
|
|
|
|
2024-05-30 16:12:07 -07:00
|
|
|
let filename = dotenv_filename.map_or(".env", |s| s.as_str());
|
2020-07-19 05:01:46 -07:00
|
|
|
|
2021-08-08 22:37:35 -07:00
|
|
|
for directory in working_directory.ancestors() {
|
2023-10-11 22:04:46 -07:00
|
|
|
let path = directory.join(filename);
|
2020-07-19 05:01:46 -07:00
|
|
|
if path.is_file() {
|
2022-02-01 19:16:35 -08:00
|
|
|
return load_from_file(&path);
|
2020-07-19 05:01:46 -07:00
|
|
|
}
|
2018-03-05 13:21:35 -08:00
|
|
|
}
|
2020-07-19 05:01:46 -07:00
|
|
|
|
2024-05-30 16:12:07 -07:00
|
|
|
if settings.dotenv_required {
|
|
|
|
Err(Error::DotenvRequired)
|
|
|
|
} else {
|
|
|
|
Ok(BTreeMap::new())
|
|
|
|
}
|
2018-03-05 13:21:35 -08:00
|
|
|
}
|
2021-08-08 22:37:35 -07:00
|
|
|
|
2022-02-01 19:16: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)?;
|
2021-08-08 22:37:35 -07:00
|
|
|
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)
|
|
|
|
}
|