diff --git a/CHANGELOG.md b/CHANGELOG.md index d2e8c49c..ebf3d562 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - `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)) +- Fix `String.__add__` (and `+=`) writing invalid TOML or a different value: a literal string that cannot hold the result (e.g. `'it' + "'s"`) now becomes a basic string, a `String` of another quoting style is appended by value instead of by its raw text, and appending to a multiline string no longer loses a leading newline, closes the string early on adjacent quotes, or drops whitespace after a line ending backslash. ([#733](https://github.com/python-poetry/tomlkit/pull/733)) ## [0.15.3] - 2026-11-24 diff --git a/tests/test_items.py b/tests/test_items.py index fee4b68e..1c52ccd0 100644 --- a/tests/test_items.py +++ b/tests/test_items.py @@ -14,6 +14,7 @@ from datetime import timedelta from datetime import timezone from datetime import tzinfo +from enum import Enum from typing import Any import pytest @@ -1229,6 +1230,62 @@ def test_string_add_escapes_appended_content() -> None: assert k.as_string() == '"foo bar"' +@pytest.mark.parametrize( + "left, right, expected", + [ + # A literal string that cannot hold the result becomes a basic string. + ("'it'", "'s", '"it\'s"'), + ("'a'", "b\nc", '"ab\\nc"'), + ("'''a'''", "'''", '"""a\'\'\'"""'), + ("'''a''''", "''", '"""a\'\'\'"""'), + # A String of another type is appended by value, not by raw text. + ('"a"', api.value("'b\"c'"), '"ab\\"c"'), + ("'a'", api.value('"b\\tc"'), "'ab\tc'"), + ('"a"', api.value('"""b\nc"""'), '"ab\\nc"'), + # The newline trimmed after the opening delimiter of a multiline + # string is not part of the value. + ('"""x"""', api.value('"""\nb"""'), '"""xb"""'), + ('""""""', "\nb", '"""\n\nb"""'), + ("''''''", "\nb", "'''\n\nb'''"), + # Quotes must not add up to the closing delimiter. + ('"""a"""""', '"', '"""a""\\""""'), + # Whitespace after a line ending backslash must not be trimmed. + ('"""x\\\n"""', " y", '"""x\\\n\\u0020y"""'), + ], +) +def test_string_add_keeps_valid_toml(left: str, right: str, expected: str) -> None: + left_item: Any = api.value(left) + s = left_item + right + + assert s == str(left_item) + str(right) + assert s.as_string() == expected + assert parse(f"k = {s.as_string()}")["k"] == s + + +def test_string_add_literal_fallback_keeps_comment() -> None: + doc = parse("k = 'it' # comment\n") + doc["k"] += "'s" + + assert doc.as_string() == 'k = "it\'s" # comment\n' + + +class _Color(str, Enum): + RED = "red" + + +@pytest.mark.parametrize("left", ['"a"', "'a'", '"""a"""', "'''a'''"]) +def test_string_add_str_enum_appends_its_value(left: str) -> None: + left_item: Any = api.value(left) + s = left_item + _Color.RED + + assert s == "ared" + assert parse(f"k = {s.as_string()}")["k"] == "ared" + + doc = parse(f"k = {left}\n") + doc["k"] += _Color.RED + assert parse(doc.as_string())["k"] == "ared" + + def test_tables_behave_like_dicts() -> None: t = item({"foo": "bar"}) diff --git a/tomlkit/items.py b/tomlkit/items.py index 9d6cd607..1abed070 100644 --- a/tomlkit/items.py +++ b/tomlkit/items.py @@ -404,6 +404,11 @@ def _format_datetime(value: datetime) -> str: # string only a raw line feed or a CRLF pair is a valid line ending; a lone CR is # a control character that a basic string must escape. _BARE_CR = re.compile(r"\r(?!\n)") +# The newline that a multiline string's parser trims after the opening delimiter. +_TRIMMED_NEWLINE = re.compile(r"\A\r?\n") +# A line ending backslash at the end of a multiline basic string's raw text: the +# parser trims all whitespace and newlines that follow it. +_TRAILING_LINE_CONTINUATION = re.compile(r"(? StringType: def __add__(self, other: str) -> String: result = super().__add__(other) - if isinstance(other, String): - original = self._original + other._original + t = self._t + if t.is_literal(): + checked = result.replace("\r\n", "\n") + if any(seq in checked for seq in t.invalid_sequences): + # A literal string cannot escape anything: fall back to the + # basic string of the same kind. + basic = String.from_raw( + result, StringType.select(multiline=t.is_multiline()) + ) + basic._trivia = self._trivia.copy() + return basic + + if isinstance(other, String) and other._t is t: + appended = other._original + if t.is_multiline(): + # The newline after the opening delimiter is no longer trimmed + # once the text is appended to another string. + appended = _TRIMMED_NEWLINE.sub("", appended) else: - escaped = self._t.escaped_sequences - original = self._original + ( - escape_string(other, escaped) if escaped else other - ) + # The raw text of a String of another type is spelled for its own + # delimiters: append its value instead. + # str.__str__ gives the characters of a str subclass such as a + # str-based Enum member, not its own __str__ (see #726). + appended = str.__str__(other) + if t.is_basic(): + appended = escape_string(appended, t.escaped_sequences) + if t is StringType.MLB: + appended = _BARE_CR.sub(r"\\r", appended) + + if t.is_multiline() and not self._original and appended[:1] in ("\n", "\r"): + # Keep a leading newline from being trimmed by the parser. + appended = "\n" + appended + if t is StringType.MLB and appended: + if self._original.endswith('"') and appended[0] == '"': + # Do not let the quotes add up to the closing delimiter. + appended = '\\"' + appended[1:] + elif appended[0] in " \t\r\n" and _TRAILING_LINE_CONTINUATION.search( + self._original + ): + # Whitespace after a line ending backslash would be trimmed. + appended = escape_string(appended[0], [appended[0]]) + appended[1:] - return self._new(result, original) + return self._new(result, self._original + appended) def _new(self, result: str, original: str) -> String: return String(self._t, result, original, self._trivia.copy())