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
11 changes: 8 additions & 3 deletions src/configobj/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1760,7 +1760,7 @@ def _unquote(self, value):
return value


def _quote(self, value, multiline=True):
def _quote(self, value, multiline=True, is_key=False):
"""
Return a safely quoted version of a value.

Expand Down Expand Up @@ -1808,7 +1808,12 @@ def _quote(self, value, multiline=True):
check_for_single = (no_lists_no_quotes or not need_triple) and not hash_triple_quote

if check_for_single:
if not self.list_values:
if is_key and '=' in value:
# A key containing '=' must be quoted, otherwise the first
# '=' is read back as the key/value divider, splitting the
# key and corrupting the value on the next parse.
quot = self._get_single_quote(value)
elif not self.list_values:
# we don't quote if ``list_values=False``
quot = noquot
# for normal values either single or double quotes will do
Expand Down Expand Up @@ -1992,7 +1997,7 @@ def _write_line(self, indent_string, entry, this_entry, comment):
else:
val = repr(this_entry)
return '%s%s%s%s%s' % (indent_string,
self._decode_element(self._quote(entry, multiline=False)),
self._decode_element(self._quote(entry, multiline=False, is_key=True)),
self._a_to_u(' = '),
val,
self._decode_element(comment))
Expand Down
13 changes: 13 additions & 0 deletions src/tests/test_configobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -1295,6 +1295,19 @@ def test_hash_escaping(self, empty_cfg):
empty_cfg.write(collector)
assert collector.getvalue() == b'a = "b # something", "c # something"\n'

def test_key_with_equals_is_quoted(self, empty_cfg):
# issue #273: a key containing '=' was written unquoted, so on the
# next parse the first '=' was read as the key/value divider,
# splitting the key and corrupting the value.
empty_cfg.newlines = '\n'
empty_cfg['a = b'] = 'val'
collector = io.BytesIO()
empty_cfg.write(collector)
assert collector.getvalue() == b'"a = b" = val\n'
# and the written form round-trips back to the original key/value
collector.seek(0)
assert dict(ConfigObj(collector)) == {'a = b': 'val'}

def test_detecting_line_endings_from_existing_files(self):
for expected_line_ending in ('\r\n', '\n'):
with open('temp', 'w') as h:
Expand Down