Skip to content
Closed
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
12 changes: 9 additions & 3 deletions Lib/configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,9 +1087,15 @@ def _write_section(self, fp, section_name, section_items, delimiter, unnamed=Fal
value = self._interpolation.before_write(self, section_name, key, value)
if value is not None or not self._allow_no_value:
# Convert all possible line-endings into '\n\t'
value = delimiter + str(value).replace('\r\n', '\n').replace(
'\r', '\n'
).replace('\n', '\n\t')
str_value = str(value).replace('\r\n', '\n').replace('\r', '\n')
for continuation in str_value.split('\n')[1:]:
if continuation and continuation[0] in ' \t':
raise InvalidWriteError(
f"Cannot write value for key {key!r}; "
f"continuation line has leading whitespace "
f"that would be silently stripped on read-back"
)
value = delimiter + str_value.replace('\n', '\n\t')
else:
value = ""
fp.write(f"{key}{value}\n")
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2498,6 +2498,14 @@ def test_section_bracket_in_key(self):
cfg.write(output)
output.close()

def test_leading_whitespace_in_multiline_value(self):
cfg = configparser.ConfigParser()
cfg.add_section('section1')
cfg.set('section1', 'key', 'line1\n\tline2')
output = io.StringIO()
with self.assertRaises(configparser.InvalidWriteError):
cfg.write(output)
output.close()

class ReDoSTestCase(unittest.TestCase):
"""Regression tests for quadratic regex backtracking (gh-146333)."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:mod:`configparser` now raises :exc:`~configparser.InvalidWriteError` when
writing a value whose continuation lines contain leading whitespace, since
that whitespace would be silently stripped on read-back.
Loading