Skip to content

fix: do not treat an inline comment as an empty value - #679

Open
dchaudhari7177 wants to merge 1 commit into
theskumar:mainfrom
dchaudhari7177:fix/empty-value-inline-comment
Open

fix: do not treat an inline comment as an empty value#679
dchaudhari7177 wants to merge 1 commit into
theskumar:mainfrom
dchaudhari7177:fix/empty-value-inline-comment

Conversation

@dchaudhari7177

Copy link
Copy Markdown

Fixes #600.

Problem

An inline comment after an empty unquoted value becomes the value:

>>> dotenv_values(stream=io.StringIO("WITH_VALUE=hello  # c\nEMPTY_VALUE=  # c\n"))
OrderedDict({'WITH_VALUE': 'hello', 'EMPTY_VALUE': '# c'})

EMPTY_VALUE should be '', the same way WITH_VALUE gets its comment stripped.

Cause

_equal_sign is (=[^\S\r\n]*), so it consumes the horizontal whitespace right after =. parse_unquoted_value then strips comments with re.sub(r"\s+#.*", "", part), which requires whitespace before the #. For KEY= # c that whitespace is already gone, the part is # c with the # at position 0, the substitution does not fire, and the comment is returned as the value.

Fix

parse_binding already gets the matched = plus whitespace back from read_regex, so it can tell whether any whitespace followed the =. That flag is threaded to parse_unquoted_value, which treats a part starting with # as a comment only when the whitespace was there.

This keeps the existing rule that # starts a comment only when preceded by whitespace, so a=b#c and the newly-covered a=#c both still parse to a literal value containing the #.

Input Before After
a=b # c b b
a= # c # c `` (empty)
a=#c #c #c
a=b#c b#c b#c
a= `` (empty) `` (empty)

Tests

Four cases added to test_parse_stream, including the no-whitespace a=#c case that pins the unchanged behaviour and a two-binding case confirming the reader is left in the right position.

pytest tests/ passes. The two test_cli.py::test_run_* failures on my machine are pre-existing and Windows-specific (they reproduce on an unmodified checkout).

🤖 Generated with Claude Code

`KEY=  # comment` parsed to `"# comment"` rather than `""`, while
`KEY=value  # comment` correctly parsed to `"value"`.

`_equal_sign` consumes the horizontal whitespace that follows `=`, so by
the time `parse_unquoted_value` runs, its `\s+#.*` strip no longer has
the whitespace it needs to recognise the comment, and the comment text
becomes the value.

Pass down whether that whitespace was present and, when it was, treat a
value that starts with `#` as a comment. `KEY=#c` with no whitespace
still parses to `"#c"`, matching the existing `a=b#c` behaviour.

Fixes theskumar#600

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
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 this pull request may close these issues.

[Bug] Inline comment is included as value when key has empty value (KEY= # comment)

1 participant