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: 11 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,17 @@ def test_array_add_line() -> None:
)


def test_array_add_line_with_comment_on_last_line_round_trips() -> None:
# A trailing comment on the last (and only) line of a non-multiline array
# used to swallow the closing bracket, since "#" comments run to the end
# of the physical line and nothing forced a newline before the "]".
t = api.array()
t.add_line("foo", comment="bar")
rendered = t.as_string()
assert rendered == '[\n "foo", # bar\n]'
assert parse(f"a = {rendered}")["a"] == ["foo"]


def test_array_add_line_multiline_comment_is_rejected() -> None:
t = api.array()
with pytest.raises(ValueError, match="line breaks"):
Expand Down
13 changes: 12 additions & 1 deletion tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -1464,7 +1464,18 @@ def multiline(self, multiline: bool) -> Array:

def as_string(self) -> str:
if not self._multiline or not self._value:
return f"[{''.join(v.as_string() for v in self._iter_items())}]"
s = "".join(v.as_string() for v in self._iter_items())
# A trailing "# ..." comment swallows anything that follows it on
# the same line, including the closing bracket. If the rendered
# content ends with a comment that isn't already followed by a
# newline, force one so the array still round-trips as valid TOML.
if (
self._value
and self._value[-1].comment is not None
and not s.endswith(("\n", "\r"))
):
s += "\n" + self.trivia.indent
return f"[{s}]"

s = "[\n"
s += "".join(
Expand Down