Add a function to load an `.env` but ignore if the file doesn't exist.
Hi, I find the following to be a really useful function that I've started copying around to a few places:
fn load_dotenv() -> dotenvy::Result<()> {
match dotenvy::dotenv() {
Ok(_) => Ok(()),
Err(dotenvy::Error::Io(err)) if (err.kind() == ErrorKind::NotFound) => Ok(()),
Err(e) => Err(e),
}
}
Basically, load a dotenv file, but ignore if the file doesn't exist. However, still return an Err for any other error loading the env file.
Since I've found this to be something I want nearly always I figure it might be valuable to add it to the crate directly. Just curious @allan2, would you accept a PR to add such a function?
Hi @cprussin, I wouldn't accept a PR but only because it is already planned.
Expect a load_opt function with a Result<Option<PathBuf>> signature. It will return Error if there was an error reading the file, return Ok(Some(PathBuf)) if the file is read correctly, and Ok(None) if the file is not found.
Oh that's awesome, thanks @allan2 and sorry I missed that, I searched around but I didn't see that discussion.
Is there anything blocking getting that added? I'm happy to submit the PR adding it if we're just waiting on a contributor. load_opt would be basically the snippet I posted above, except for passing through the PathBuf inside an Option in the first arm and the None in the second arm of course.
Hi @cprussin, there is a new API. See the optional example.
IO is deferred until load and behaviour is configured with EnvSequence. As load returns Result, it will catch IO errors that aren't NotFound.