Skip to content

Commit e67098d

Browse files
Preserve literal quotes when replacing table strings (#627)
* Preserve single-line literal quotes when replacing table strings * Avoid repeating the plain-string check during assignment * Keep the Python 3.9 Linux job on Ubuntu 24.04 (#681) (cherry picked from commit cd46e5d) --------- Co-authored-by: KennySimpson <70093673+KennyMcSimpson@users.noreply.github.com>
1 parent 56bf158 commit e67098d

4 files changed

Lines changed: 90 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060

6161
### Fixed
6262

63+
- Preserve single-line literal quotes when replacing a table field with a plain string, falling back to basic quoting when the value requires escaping. ([#325](https://github.com/python-poetry/tomlkit/issues/325))
6364
- Fix `string()` dropping a leading newline of a multiline string on round-trip: a value beginning with a newline is now rendered with an extra leading newline (the one the parser trims after the opening delimiter) so it survives re-parsing.
6465
- Fix invalid serialization with a duplicated comma when removing a non-edge element from a parsed inline table. ([#486](https://github.com/python-poetry/tomlkit/pull/486))
6566
- Fix invalid serialization with a duplicated comma when appending or inserting into a comma-first formatted array. ([#499](https://github.com/python-poetry/tomlkit/pull/499))

‎tests/test_toml_document.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,74 @@
2222
from tomlkit.toml_document import TOMLDocument
2323

2424

25+
@pytest.mark.parametrize(
26+
"content,path",
27+
[
28+
("before = 1\n value = 'old' # keep\nafter = 2\n", ()),
29+
("before = 1\r\nvalue = 'old' # keep\r\nafter = 2\r\n", ()),
30+
("[table]\nbefore = 1\n value = 'old' # keep\nafter = 2\n", ("table",)),
31+
("table = {before = 1, value = 'old', after = 2}\n", ("table",)),
32+
(
33+
"[table.a]\nx = 1\n[other]\ny = 2\n[table]\nvalue = 'old' # keep\n",
34+
("table",),
35+
),
36+
],
37+
)
38+
def test_replace_literal_string_preserves_table_style(
39+
content: str, path: tuple[str, ...]
40+
) -> None:
41+
doc = parse(content)
42+
table: Any = doc
43+
for key in path:
44+
table = table[key]
45+
table["value"] = "new"
46+
assert doc.as_string() == content.replace("'old'", "'new'")
47+
assert table["value"] == dict(table)["value"] == table.unwrap()["value"] == "new"
48+
assert parse(doc.as_string()).unwrap() == doc.unwrap()
49+
50+
# Explicit items retain the caller's quote choice instead of inheriting it.
51+
table["value"] = tomlkit.string("explicit")
52+
assert doc.as_string() == content.replace("'old'", '"explicit"')
53+
table["value"] = tomlkit.string("literal", literal=True)
54+
assert doc.as_string() == content.replace("'old'", "'literal'")
55+
table.update(value="updated")
56+
assert doc.as_string() == content.replace("'old'", "'updated'")
57+
table["value"] = "can't"
58+
assert doc.as_string() == content.replace("'old'", '"can\'t"')
59+
assert parse(doc.as_string()).unwrap() == doc.unwrap()
60+
61+
62+
@pytest.mark.parametrize("value", ["", "unicode λ", "a\\b", 'a"b', "a\tb"])
63+
def test_replace_literal_string_preserves_value(value: str) -> None:
64+
doc = parse("value = 'old'\n")
65+
doc["value"] = value
66+
assert doc.as_string() == f"value = '{value}'\n"
67+
assert parse(doc.as_string())["value"] == value
68+
69+
70+
@pytest.mark.parametrize("value", ["can't", "a\nb", "a\rb", "a\x00b", "a\x7fb"])
71+
def test_replace_literal_string_falls_back_to_basic(value: str) -> None:
72+
doc = parse("value = 'old' # keep\n")
73+
doc["value"] = value
74+
assert doc.as_string() == f"value = {tomlkit.string(value).as_string()} # keep\n"
75+
assert parse(doc.as_string())["value"] == value
76+
77+
78+
@pytest.mark.parametrize("original", ['"old"', "'''old'''", '"""old"""', "1"])
79+
def test_replace_other_items_keeps_default_string_style(original: str) -> None:
80+
doc = parse(f"value = {original}\n")
81+
doc["value"] = "new"
82+
assert doc.as_string() == 'value = "new"\n'
83+
84+
85+
def test_literal_replacement_does_not_change_new_keys_or_arrays() -> None:
86+
doc = parse("value = 'old'\narray = ['old']\n")
87+
doc["new"] = "new"
88+
doc["array"][0] = "new"
89+
doc["value"] = 2
90+
assert doc.as_string() == 'value = 2\narray = ["new"]\nnew = "new"\n'
91+
92+
2593
def test_document_is_a_dict(example: Callable[[str], str]) -> None:
2694
content = example("example")
2795

‎tomlkit/container.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from tomlkit._compat import decode
1515
from tomlkit._types import _CustomDict
1616
from tomlkit._utils import merge_dicts
17+
from tomlkit.exceptions import InvalidStringError
1718
from tomlkit.exceptions import KeyAlreadyPresent
1819
from tomlkit.exceptions import NonExistentKey
1920
from tomlkit.exceptions import TOMLKitError
@@ -23,6 +24,8 @@
2324
from tomlkit.items import Key
2425
from tomlkit.items import Null
2526
from tomlkit.items import SingleKey
27+
from tomlkit.items import String
28+
from tomlkit.items import StringType
2629
from tomlkit.items import Table
2730
from tomlkit.items import Trivia
2831
from tomlkit.items import Whitespace
@@ -918,9 +921,25 @@ def __contains__(self, key: object) -> bool:
918921
OutOfOrderTableProxy(self, idx)
919922
return True
920923

924+
def _item_for_key(
925+
self, key: Key | str, value: object, parent: Item | None = None
926+
) -> Item:
927+
# Inspect plain strings before conversion, so an explicit String keeps
928+
# the caller's chosen quoting style.
929+
if isinstance(value, str) and not isinstance(value, String):
930+
previous = self.get(key)
931+
if isinstance(previous, String) and previous._t is StringType.SLL:
932+
try:
933+
return String.from_raw(value, StringType.SLL)
934+
except InvalidStringError:
935+
# Some values need the escaping provided by a basic string.
936+
pass
937+
return _item(value, _parent=parent)
938+
921939
def __setitem__(self, key: Key | str, value: Any) -> None:
922940
if key in self:
923941
old_key = next(filter(lambda k: k == key, self._map))
942+
value = self._item_for_key(key, value)
924943
self._replace(old_key, key, value)
925944
else:
926945
self.append(key, value)

‎tomlkit/items.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1888,7 +1888,7 @@ def __contains__(self, key: object) -> bool:
18881888

18891889
def __setitem__(self, key: Key | str, value: Any) -> None:
18901890
if not isinstance(value, Item):
1891-
value = item(value, _parent=self)
1891+
value = self._value._item_for_key(key, value, parent=self)
18921892

18931893
is_replace = key in self
18941894
self._value[key] = value
@@ -2240,7 +2240,7 @@ def __setitem__(self, key: Key | str, value: Any) -> None:
22402240
if hasattr(value, "trivia") and value.trivia.comment:
22412241
value.trivia.comment = ""
22422242
if not isinstance(value, Item):
2243-
value = item(value, _parent=self)
2243+
value = self._value._item_for_key(key, value, parent=self)
22442244
self._validate_child(value)
22452245
super().__setitem__(key, value)
22462246

0 commit comments

Comments
 (0)