diff --git a/src/pyproject_fmt/formatter/util.py b/src/pyproject_fmt/formatter/util.py index dba1f59..32383f5 100644 --- a/src/pyproject_fmt/formatter/util.py +++ b/src/pyproject_fmt/formatter/util.py @@ -8,6 +8,7 @@ from tomlkit.container import OutOfOrderTableProxy from tomlkit.items import ( AbstractTable, + AoT, Array, Comment, Item, @@ -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): diff --git a/tests/formatter/test_tools.py b/tests/formatter/test_tools.py index 3de4cfe..0497daf 100644 --- a/tests/formatter/test_tools.py +++ b/tests/formatter/test_tools.py @@ -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) diff --git a/whitelist.txt b/whitelist.txt index d335dd8..e1097a0 100644 --- a/whitelist.txt +++ b/whitelist.txt @@ -1,3 +1,4 @@ +Ao autoclass autodoc canonicalize