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

Expose parse errors via Dotenv::iter. #5

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 20 additions & 16 deletions src/dotenv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,28 +59,32 @@ impl<'a> Iter<'a> {
Value::List(list) => Some(list.into_iter().flat_map(|it| self.resolve(it)).collect()),
}
}

pub fn try_next(&mut self) -> crate::Result<Option<(&'a str, String)>> {
while !self.input.is_empty() {
match parse(self.input) {
Ok((rest, maybe)) => {
self.input = rest; // set next input

if let Some((key, value)) = maybe {
if let Some(value) = self.resolve(value) {
self.resolved.insert(key, value.clone());
return Ok(Some((key, value)));
}
}
}
Err(err) => return Err(err.into()),
}
}
Ok(None)
}
}

impl<'a> Iterator for Iter<'a> {
type Item = (&'a str, String);

fn next(&mut self) -> Option<Self::Item> {
while let Ok((rest, maybe)) = parse(self.input) {
self.input = rest; // set next input

if let Some((key, value)) = maybe {
if let Some(value) = self.resolve(value) {
self.resolved.insert(key, value.clone());
return Some((key, value));
}
}

if rest.is_empty() {
break;
}
}

None
self.try_next().unwrap_or_default()
}
}

Expand Down
13 changes: 11 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::io;
pub enum Error {
Io(io::Error),
Env(env::VarError),
Parse(String),
}

impl Error {
Expand All @@ -27,8 +28,9 @@ impl Error {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Io(err) => err.fmt(fmt),
Error::Env(err) => err.fmt(fmt),
Error::Io(err) => fmt::Display::fmt(&err, fmt),
Error::Env(err) => fmt::Display::fmt(&err, fmt),
Error::Parse(err) => fmt::Display::fmt(&err, fmt),
}
}
}
Expand All @@ -38,6 +40,7 @@ impl error::Error for Error {
match self {
Error::Io(err) => Some(err),
Error::Env(err) => Some(err),
Error::Parse(_) => None,
}
}
}
Expand All @@ -53,3 +56,9 @@ impl From<env::VarError> for Error {
Error::Env(err)
}
}

impl<E: fmt::Debug> From<nom::Err<E>> for Error {
fn from(err: nom::Err<E>) -> Self {
Error::Parse(format!("{err}"))
}
}
1 change: 0 additions & 1 deletion tests/fixtures/sample-basic.env
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ DOUBLE_AND_SINGLE_QUOTES_INSIDE_BACKTICKS=`double "quotes" and single 'quotes' w
EXPAND_NEWLINES="expand\nnew\nlines"
DONT_EXPAND_UNQUOTED=dontexpand\nnewlines
DONT_EXPAND_SQUOTED='dontexpand\nnewlines'
DONT_EXPAND_SQUOTED='dontexpand\nnewlines'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assumed this duplicated line was unintentional (it was the only one in all the examples) and it got in the way of fixing tests to assert all expected values were observed. If this was intentional though, I can go back to work on handling this differently.

# COMMENTS=work
INLINE_COMMENTS=inline comments # work #very #well
INLINE_COMMENTS_SINGLE_QUOTES='inline comments outside of #singlequotes' # work
Expand Down
19 changes: 19 additions & 0 deletions tests/test-dotenv-try-next.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
mod fixtures;
use fixtures::*;

#[test]
fn test_propagate_env_parse_errors() -> anyhow::Result<()> {
let (_t, mut exps) = with_basic_dotenv()?;

// This is an example of how a consumer that cares about invalid `.env` files can handle them using the
// `Iter::try_next` API (see: https://github.com/arniu/dotenvs-rs/issues/4)
let env = dotenv::from_filename(".env")?;
let mut iter = env.iter();
while let Some((key, value)) = iter.try_next()? {
let expected = exps.remove(key).unwrap();
assert_eq!(expected, value, "check {}", key);
}
assert!(exps.is_empty());

Ok(())
}
37 changes: 37 additions & 0 deletions tests/test-sample-bad.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use dotenv::Error;

const BAD_ENV: &str = r#"
A=foo bar
B="notenough
C='toomany''
D=valid
export NOT_SET
E=valid
"#;

#[test]
fn test_bad_env() -> anyhow::Result<()> {
let env = dotenv::from_read(BAD_ENV.as_bytes())?;

assert_eq!(
vec![
("A", "foo bar".into()),
("B", "\"notenough".into()),
("C", "toomany".into())
],
env.iter().collect::<Vec<_>>()
);

let mut iter = env.iter();
assert_eq!(Some(("A", "foo bar".into())), iter.try_next()?);
assert_eq!(Some(("B", "\"notenough".into())), iter.try_next()?);
assert_eq!(Some(("C", "toomany".into())), iter.try_next()?);

// TODO: Use assert_matches! when it stabilizes: https://github.com/rust-lang/rust/issues/82775
assert!(matches!(
iter.try_next().unwrap_err(),
Error::Parse(err) if err == "Parsing Error: Error { input: \"'\\nD=valid\\nexport NOT_SET\\nE=valid\\n\", code: Tag }"
));

Ok(())
}
7 changes: 4 additions & 3 deletions tests/test-sample-basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ use fixtures::*;

#[test]
fn test_sample() -> anyhow::Result<()> {
let (_t, exps) = with_basic_dotenv()?;
let (_t, mut exps) = with_basic_dotenv()?;
for (key, value) in dotenv::from_filename(".env")?.iter() {
let expected = exps.get(key).unwrap();
assert_eq!(expected, &value, "check {}", key);
let expected = exps.remove(key).unwrap();
assert_eq!(expected, value, "check {}", key);
}
assert!(exps.is_empty());

Ok(())
}
7 changes: 4 additions & 3 deletions tests/test-sample-expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ use fixtures::*;

#[test]
fn test_sample() -> anyhow::Result<()> {
let (_t, exps) = with_expand_dotenv()?;
let (_t, mut exps) = with_expand_dotenv()?;
for (key, value) in dotenv::from_filename(".env")?.iter() {
let expected = exps.get(key).unwrap();
assert_eq!(expected, &value, "check {}", key);
let expected = exps.remove(key).unwrap();
assert_eq!(expected, value, "check {}", key);
}
assert!(exps.is_empty());

Ok(())
}
7 changes: 4 additions & 3 deletions tests/test-sample-multiline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ use fixtures::*;

#[test]
fn test_sample() -> anyhow::Result<()> {
let (_t, exps) = with_multiline_dotenv()?;
let (_t, mut exps) = with_multiline_dotenv()?;
for (key, value) in dotenv::from_filename(".env")?.iter() {
let expected = exps.get(key).unwrap();
assert_eq!(expected, &value, "check {}", key);
let expected = exps.remove(key).unwrap();
assert_eq!(expected, value, "check {}", key);
}
assert!(exps.is_empty());

Ok(())
}