Skip to content

fix: parse empty unquoted value with inline comment as empty string - #663

Closed
Noethix55555 wants to merge 1 commit into
theskumar:mainfrom
Noethix55555:fix-empty-value-inline-comment
Closed

fix: parse empty unquoted value with inline comment as empty string#663
Noethix55555 wants to merge 1 commit into
theskumar:mainfrom
Noethix55555:fix-empty-value-inline-comment

Conversation

@Noethix55555

Copy link
Copy Markdown
Contributor

Summary

Fixes #600.

An unquoted empty value followed by an inline comment is parsed as the comment text instead of an empty string:

from io import StringIO
from dotenv import dotenv_values

dotenv_values(stream=StringIO("KEY= # comment"))
# before: {'KEY': '# comment'}
# after:  {'KEY': ''}

Root cause

_equal_sign = (=[^\S\r\n]*) consumes the whitespace after =, so the captured unquoted value is # comment with no leading whitespace. parse_unquoted_value strips comments with re.sub(r"\s+#.*", "", part), which requires whitespace before # and therefore does not strip it.

Fix

In parse_binding, after reading the equal sign, if it consumed trailing whitespace (so the value is empty) and the next character is #, treat the value as "" and let the rest of the line be parsed as a comment. When there is no space before # (e.g. KEY=#novalue, KEY=a#b) the # remains part of the value, preserving existing behavior.

Behavior preserved (with tests)

  • KEY=val # comment -> val
  • KEY=a#b -> a#b (no space before #)
  • KEY=#novalue -> #novalue (no space, unchanged)
  • KEY= # comment / KEY= # comment -> '' (the fix)
  • Trailing/leading whitespace handling on normal values unchanged (e.g. a = b -> b, a=b c -> b c)

Tests

Added parametrized cases in tests/test_parser.py (a= #b, a= # b, a=#b) and an end-to-end dotenv_values regression in tests/test_main.py. Verified they fail on main and pass with the fix. Full test suite remains green.

An unquoted empty value followed by an inline comment (e.g. `KEY= # comment`)
was parsed as the comment text because the equal-sign regex consumed the
whitespace after `=`, leaving no whitespace for the comment-stripping rule to
match. When the value is empty (whitespace follows `=`) and starts with `#`,
treat the rest of the line as a comment and the value as empty. Values with no
space before `#` (e.g. `KEY=#novalue`, `KEY=a#b`) are unchanged.

Closes theskumar#600
@theskumar

Copy link
Copy Markdown
Owner

Merged manually into main (f5485a6) with a few extra test cases cherry-picked from the other PRs. Added a CHANGELOG entry in a00cb2e. Thanks @Noethix55555 — clean, minimal fix. 🎉

Closes #600.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants