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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
32 changes: 32 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions tomlkit/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading