Skip to content

Commit 1a3085c

Browse files
Prevent repeated whitespace items in arrays (#406)
* prevent repeated whitespace items * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent c5db0b6 commit 1a3085c

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

tests/test_items.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,3 +1008,14 @@ def add_table(parent, name):
10081008
add_table(root, "first")
10091009
add_table(root, "second")
10101010
assert doc.as_string() == "[root.first]\n\n[root.second]\n"
1011+
1012+
1013+
def test_removal_of_arrayitem_with_extra_whitespace():
1014+
expected = 'x = [\n "bar",\n]'
1015+
doc = parse('x = [\n "foo" ,#spam\n "bar",\n]')
1016+
x = doc["x"]
1017+
assert isinstance(x, Array)
1018+
x.remove("foo")
1019+
docstr = doc.as_string()
1020+
parse(docstr)
1021+
assert docstr == expected

tomlkit/parser.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,15 @@ def _parse_array(self) -> Array:
595595
# consume comma
596596
if prev_value and self._current == ",":
597597
self.inc(exception=UnexpectedEofError)
598-
elems.append(Whitespace(","))
598+
# Check if the previous item is Whitespace
599+
if isinstance(elems[-1], Whitespace) and " " in elems[-1].s:
600+
# Preserve the previous whitespace
601+
comma = Whitespace(elems[-1].s + ",")
602+
# Remove the replaced item
603+
del elems[-1]
604+
else:
605+
comma = Whitespace(",")
606+
elems.append(comma)
599607
prev_value = False
600608
continue
601609

0 commit comments

Comments
 (0)