allan2 / dotenvy

A well-maintained fork of the Rust dotenv crate
MIT License
625 stars 39 forks source link

Add a function to load an `.env` but ignore if the file doesn't exist. #106

Open cprussin opened 4 weeks ago

cprussin commented 4 weeks ago

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?

allan2 commented 4 weeks ago

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.

cprussin commented 4 weeks ago

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.