Skip to content

Commit

Permalink
Fix indent for nested table elements when updating
Browse files Browse the repository at this point in the history
Fixes #106
  • Loading branch information
sdispater committed May 19, 2021
1 parent d34a1fe commit 182d4da
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
21 changes: 21 additions & 0 deletions tests/test_toml_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,24 @@ def test_string_output_order_is_preserved_for_out_of_order_tables():
"""

assert expected == doc.as_string()


def test_updating_nested_value_keeps_correct_indent():
content = """
[Key1]
[key1.Key2]
Value1 = 10
Value2 = 30
"""

doc = parse(content)
doc["key1"]["Key2"]["Value1"] = 20

expected = """
[Key1]
[key1.Key2]
Value1 = 20
Value2 = 30
"""

assert doc.as_string() == expected
4 changes: 3 additions & 1 deletion tomlkit/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -1018,6 +1018,8 @@ def __getitem__(self, key): # type: (Union[Key, str]) -> Item
return self._value[key]

def __setitem__(self, key, value): # type: (Union[Key, str], Any) -> None
fix_indent = key not in self

if not isinstance(value, Item):
value = item(value)

Expand All @@ -1027,7 +1029,7 @@ def __setitem__(self, key, value): # type: (Union[Key, str], Any) -> None
super(Table, self).__setitem__(key, value)

m = re.match("(?s)^[^ ]*([ ]+).*$", self._trivia.indent)
if not m:
if not m or not fix_indent:
return

indent = m.group(1)
Expand Down
6 changes: 4 additions & 2 deletions tomlkit/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1138,9 +1138,11 @@ def _parse_table(
)

if is_aot and i == len(name_parts[1:]) - 1:
table.append(_name, AoT([child], name=table.name, parsed=True))
table.raw_append(
_name, AoT([child], name=table.name, parsed=True)
)
else:
table.append(_name, child)
table.raw_append(_name, child)

table = child
values = table.value
Expand Down

0 comments on commit 182d4da

Please sign in to comment.