Skip to content

Commit

Permalink
Fix unnecessary newline addition on sub-tables (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamchainz committed Feb 27, 2023
1 parent db78847 commit 80d5c11
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/pyproject_fmt/formatter/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from tomlkit.container import OutOfOrderTableProxy
from tomlkit.items import (
AbstractTable,
AoT,
Array,
Comment,
Item,
Expand Down Expand Up @@ -108,8 +109,15 @@ def sorted_array(

def ensure_newline_at_end(body: Table) -> None:
content = body
while content.value.body and isinstance(content.value.body[-1][1], Table):
content = content.value.body[-1][1]
while True:
if isinstance(content, AoT) and content.value and isinstance(content[-1], (AoT, Table)):
content = content[-1]
elif isinstance(content, Table) and content.value.body and isinstance(content.value.body[-1][1], (AoT, Table)):
content = content.value.body[-1][1]
else: # pragma: no cover
# coverage has a bug on python < 3.10, seeing this line as uncovered
# https://github.com/nedbat/coveragepy/issues/1480
break
whitespace = Whitespace("\n")
insert_body = content.value.body
if insert_body and isinstance(insert_body[-1][1], Whitespace):
Expand Down
37 changes: 37 additions & 0 deletions tests/formatter/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,40 @@ def test_tools_ordering(fmt: Fmt) -> None:
a = 0
"""
fmt(fmt_tools, content, expected)


def test_sub_table_newline(fmt: Fmt) -> None:
content = """
[tool.mypy]
a = 0
[[tool.mypy.overrides]]
a = 1
[tool.something-else]
b = 0
"""
expected = """
[tool.mypy]
a = 0
[[tool.mypy.overrides]]
a = 1
[tool.something-else]
b = 0
"""
fmt(fmt_tools, content, expected)


def test_sub_table_no_op(fmt: Fmt) -> None:
content = """
[tool.mypy]
a = 0
[[tool.mypy.overrides]]
a = 1
[tool.something-else]
b = 0
"""
fmt(fmt_tools, content, content)
1 change: 1 addition & 0 deletions whitelist.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
Ao
autoclass
autodoc
canonicalize
Expand Down

0 comments on commit 80d5c11

Please sign in to comment.