Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
cprussin opened this issue Jun 30, 2024 · 3 comments · Fixed by #123
Closed

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

cprussin opened this issue Jun 30, 2024 · 3 comments · Fixed by #123

Comments

@cprussin
Copy link

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
Copy link
Owner

allan2 commented Jun 30, 2024

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
Copy link
Author

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.

@allan2
Copy link
Owner

allan2 commented Sep 4, 2024

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.

@allan2 allan2 mentioned this issue Sep 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants