Search for .env file from working directory (#661)

Search for a `.env` file starting in the  working directory, instead of
the invocation directory.
This commit is contained in:
Casey Rodarmor 2020-07-19 05:01:46 -07:00 committed by GitHub
parent 8fad0626f8
commit 05d73a423a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 49 additions and 14 deletions

View File

@ -91,7 +91,7 @@ impl<'src> Justfile<'src> {
} }
let dotenv = if config.load_dotenv { let dotenv = if config.load_dotenv {
load_dotenv()? load_dotenv(&search.working_directory)?
} else { } else {
BTreeMap::new() BTreeMap::new()
}; };

View File

@ -1,25 +1,26 @@
use crate::common::*; use crate::common::*;
pub(crate) fn load_dotenv() -> RunResult<'static, BTreeMap<String, String>> { pub(crate) fn load_dotenv(
// `dotenv::dotenv_iter` should eventually be un-deprecated, see: working_directory: &Path,
) -> RunResult<'static, BTreeMap<String, String>> {
// `dotenv::from_path_iter` should eventually be un-deprecated, see:
// https://github.com/dotenv-rs/dotenv/issues/13 // https://github.com/dotenv-rs/dotenv/issues/13
#![allow(deprecated)] #![allow(deprecated)]
match dotenv::dotenv_iter() { for directory in working_directory.ancestors() {
Ok(iter) => { let path = directory.join(".env");
if path.is_file() {
let iter = dotenv::from_path_iter(&path)?;
let mut dotenv = BTreeMap::new(); let mut dotenv = BTreeMap::new();
for result in iter { for result in iter {
let (key, value) = result.map_err(|dotenv_error| RuntimeError::Dotenv { dotenv_error })?; let (key, value) = result?;
if env::var_os(&key).is_none() { if env::var_os(&key).is_none() {
dotenv.insert(key, value); dotenv.insert(key, value);
} }
} }
Ok(dotenv) return Ok(dotenv);
},
Err(dotenv_error) =>
if dotenv_error.not_found() {
Ok(BTreeMap::new())
} else {
Err(RuntimeError::Dotenv { dotenv_error })
},
} }
}
Ok(BTreeMap::new())
} }

View File

@ -395,3 +395,9 @@ impl<'src> Display for RuntimeError<'src> {
Ok(()) Ok(())
} }
} }
impl<'src> From<dotenv::Error> for RuntimeError<'src> {
fn from(dotenv_error: dotenv::Error) -> RuntimeError<'src> {
RuntimeError::Dotenv { dotenv_error }
}
}

28
tests/dotenv.rs Normal file
View File

@ -0,0 +1,28 @@
use executable_path::executable_path;
use std::{process, str};
use test_utilities::tmptree;
#[test]
fn dotenv() {
let tmp = tmptree! {
".env": "KEY=ROOT",
sub: {
".env": "KEY=SUB",
justfile: "default:\n\techo KEY=$KEY",
},
};
let binary = executable_path("just");
let output = process::Command::new(binary)
.current_dir(tmp.path())
.arg("sub/default")
.output()
.expect("just invocation failed");
assert_eq!(output.status.code().unwrap(), 0);
let stdout = str::from_utf8(&output.stdout).unwrap();
assert_eq!(stdout, "KEY=SUB\n");
}