Skip to content
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
16 changes: 14 additions & 2 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from contextlib import contextmanager
from typing import IO, Dict, Iterable, Iterator, Mapping, Optional, Tuple, Union

from .parser import Binding, parse_stream
from .parser import Binding, Original, _newline, parse_stream
from .variables import parse_variables

# A type alias for a string path to be used for the paths in this file.
Expand All @@ -29,12 +29,24 @@ def _load_dotenv_disabled() -> bool:
return value in {"1", "true", "t", "yes", "y"}


def _statement_line(original: Original) -> int:
"""
Return the line on which the statement in `original` starts.

`original.line` is where the chunk of text starts, which includes any
blank lines before the statement itself.
"""
string = original.string
leading = string[: len(string) - len(string.lstrip())]
return original.line + len(_newline.findall(leading))


def with_warn_for_invalid_lines(mappings: Iterator[Binding]) -> Iterator[Binding]:
for mapping in mappings:
if mapping.error:
logger.warning(
"python-dotenv could not parse statement starting at line %s",
mapping.original.line,
_statement_line(mapping.original),
)
yield mapping

Expand Down
23 changes: 23 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,29 @@ def test_dotenv_values_file_stream(dotenv_path):
assert result == {"a": "b"}


@pytest.mark.parametrize(
"string,line",
[
("x y", 1),
("a=b\nx y", 2),
("a=b\n\n\nx y\n", 4),
("# comment\n\n \nx y\n", 4),
("a=b\r\n\r\nx y\r\n", 3),
("a=b\r\rx y\r", 3),
("a=b\n\nc='unterminated\nd=e\n", 3),
],
)
def test_dotenv_values_invalid_line_warning_reports_statement_line(string, line):
logger = logging.getLogger("dotenv.main")

with mock.patch.object(logger, "warning") as mock_warning:
dotenv.dotenv_values(stream=io.StringIO(string))

mock_warning.assert_called_once_with(
"python-dotenv could not parse statement starting at line %s", line
)


@pytest.mark.parametrize(
"string,expected",
[
Expand Down
Loading