From 474d974052b5bd6ade08583bd6470ac737ddec1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Augusto=20C=C3=A9sar?= Date: Thu, 26 Sep 2024 12:58:54 +0200 Subject: [PATCH] fix: correct check for required attribute ### Description Currently, in the current code, the `required` attribute does not work as expected. On the code path where it should "continue if not required" actually just fallback into the error printing and process exiting. Small reproducible example: ```rust #[dotenvy::load(required = false)] #[tokio::main] async fn main() { let _ = env::var("SOME_VAR").unwrap(); } ``` Which errors out with: ``` Failed to load env file from path './.env': error reading './.env':, No such file or directory (os error 2) ``` --- dotenvy-macros/src/lib.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/dotenvy-macros/src/lib.rs b/dotenvy-macros/src/lib.rs index cae16ff4..bf4d9047 100644 --- a/dotenvy-macros/src/lib.rs +++ b/dotenvy-macros/src/lib.rs @@ -35,12 +35,15 @@ pub fn load(attr: TokenStream, item: TokenStream) -> TokenStream { let mut loader = EnvLoader::with_path(#path).sequence(seq); if let Err(e) = unsafe { loader.load_and_modify() } { if let Some(io_err) = e.source().and_then(|src| src.downcast_ref::()) { - if io_err.kind() == io::ErrorKind::NotFound && !#required { - // `required` is false and file not found, so continue + match (io_err.kind(), #required) { + (io::ErrorKind::NotFound, false) => (), + _ => { + eprintln!("Failed to load env file from path '{}': {e}", #path); + process::exit(1); + } } } - eprintln!("Failed to load env file from path '{}': {e}", #path); - process::exit(1); + } };