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
20 changes: 20 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,26 @@ def test_modify_array_with_comment() -> None:
assert doc.as_string() == "x = [\n 2\n]"


@pytest.mark.parametrize(
"content, expected",
[
("a = [1\n# end\n]\n", "a = [1,\n# end\n2\n]\n"),
("a = [1,\n# end\n]\n", "a = [1,\n# end\n2,\n]\n"),
(
"a = [1 # one\n, # separator\n# end\n]\n",
"a = [1 # one\n, # separator\n# end\n2\n]\n",
),
],
)
def test_append_after_standalone_array_comment(content: str, expected: str) -> None:
doc = parse(content)
doc["a"].append(2)

rendered = api.dumps(doc)
assert rendered == expected
assert parse(rendered)["a"] == [1, 2]


def test_append_to_multiline_array_with_comment() -> None:
doc = parse(
"""\
Expand Down
12 changes: 12 additions & 0 deletions tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -1677,6 +1677,18 @@ def insert(self, pos: int, value: Any) -> None: # type: ignore[override]
last_item = self._value[idx - 1]
if indent is None:
indent = last_item.indent
# Skip standalone comments when looking for the preceding separator.
for previous in self._value[:idx][::-1]:
if (
(
previous.value is not None
and not isinstance(previous.value, Null)
)
or previous.comma is not None
or (previous.indent is not None and "," in previous.indent.s)
):
last_item = previous
break
if not isinstance(last_item.value, Null) and "\n" in default_indent:
# Copy the comma from the last item if 1) it contains a value and
# 2) the array is multiline
Expand Down
Loading