From 1007267d576170a45f7da101413779b3d0ba5fe6 Mon Sep 17 00:00:00 2001 From: Romil Patel <59288311+romilp619@users.noreply.github.com> Date: Sun, 6 Dec 2026 16:28:33 +0530 Subject: [PATCH] Fix array-of-tables sorting in serialized TOML Keep both in-memory representations synchronized and preserve table boundaries when an unterminated final table is moved. Assisted-by: ChatGPT --- CHANGELOG.md | 2 ++ tests/test_items.py | 32 ++++++++++++++++++++++++++++++++ tomlkit/container.py | 3 +++ tomlkit/items.py | 6 ++++++ 4 files changed, 43 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d2e8c49c..33ef204f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ ### Fixed +- Sort arrays of tables consistently in memory and in the serialized TOML, even when the original final table has no terminating newline. + - `item()` and `dumps()` now write the underlying characters of a `str` subclass instead of calling its `__str__` method, so `str`-based `Enum` members and custom string wrappers round-trip again instead of being serialized as e.g. `"Color.RED"` or producing invalid TOML. This was a regression from the single-pass escaping added in 0.15.3. ([#725](https://github.com/python-poetry/tomlkit/issues/725)) - The parser now rejects numbers with non-ASCII digits, such as `1٠` or `10`. Previously `int()` and `float()` converted them, so an invalid document parsed to a wrong value. ([#728](https://github.com/python-poetry/tomlkit/pull/728)) - Fix deleting one of several nested dotted keys inside an inline table writing invalid TOML: deleting `c` from `x = {a.b.c = 1, a.b.d = 2}` gave `x = {a.b = {}, a.b.d = 2}`, which defines `a.b` twice. The emptied part is now removed from the document, as it already was for a single-level dotted key. ([#732](https://github.com/python-poetry/tomlkit/pull/732)) diff --git a/tests/test_items.py b/tests/test_items.py index fee4b68e..a55c6fdc 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -189,6 +189,38 @@ def test_aot_unwrap() -> None: assert_is_ppo(vu, str) +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("newline", ["\n", "\r\n"]) +def test_aot_sort_keeps_all_views_in_sync(reverse: bool, newline: str) -> None: + doc = parse( + newline.join( + [ + "[[task]]", + "rank = 3 # third", + "[[task]]", + "rank = 1 # first", + "[[task]]", + "rank = 2 # second", + ] + ) + ) + tasks = doc["task"] + + tasks.sort(key=lambda task: task["rank"], reverse=reverse) + + expected_ranks = [3, 2, 1] if reverse else [1, 2, 3] + assert [task["rank"] for task in tasks] == expected_ranks + assert [task["rank"] for task in tasks[:]] == expected_ranks + assert [task["rank"] for task in tasks.unwrap()] == expected_ranks + rendered = doc.as_string() + assert [task["rank"] for task in parse(rendered)["task"]] == expected_ranks + assert "rank = 3 # third" in rendered + assert "rank = 1 # first" in rendered + assert "rank = 2 # second" + newline in rendered + if newline == "\r\n": + assert "\n" not in rendered.replace("\r\n", "") + + def test_aot_set_item() -> None: d = item(["A", {"b": "B"}, ["c", "D"]]) d[0] = "C" diff --git a/tomlkit/container.py b/tomlkit/container.py index 36720007..f6784dc6 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -781,6 +781,9 @@ def _render_aot(self, key: Key, aot: AoT, prefix: str | None = None) -> str: cur = "" _key = decode(_key) for table in aot.body: + # A table moved from EOF may not have a terminating newline. + if cur and not cur.endswith("\n") and "\n" not in table.trivia.indent: + cur += "\r\n" if table.trivia.trail.endswith("\r\n") else "\n" cur += self._render_aot_table(table, prefix=_key) return cur diff --git a/tomlkit/items.py b/tomlkit/items.py index 9d6cd607..61f5c635 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -2618,6 +2618,12 @@ def insert(self, index: int, value: dict[str, Any]) -> None: # type: ignore[ove self._body.insert(index, value) list.insert(self, index, value) + def sort( + self, *, key: Callable[[Table], Any] | None = None, reverse: bool = False + ) -> None: + """Sort tables in place, including their serialized order.""" + self[:] = sorted(self, key=key, reverse=reverse) + def invalidate_display_name(self) -> None: """Call ``invalidate_display_name`` on the contained tables""" for child in self: