diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/if.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/if.py index 682e85e763..a8a359f19c 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/if.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/if.py @@ -138,6 +138,54 @@ if True: else: pass +if True: + pass + + # comment + +else: + pass + +if True: + pass + + # comment + + +else: + pass + +if True: + pass + + # comment + + + +else: + pass + +if True: + if True: + pass + # comment + + else: + pass +else: + pass + +if True: + if True: + pass + # comment + + + else: + pass +else: + pass + # Regression test for https://github.com/astral-sh/ruff/issues/5337 if parent_body: if current_body: diff --git a/crates/ruff_python_formatter/src/comments/format.rs b/crates/ruff_python_formatter/src/comments/format.rs index 7da0eaf46b..559b7e605b 100644 --- a/crates/ruff_python_formatter/src/comments/format.rs +++ b/crates/ruff_python_formatter/src/comments/format.rs @@ -101,9 +101,7 @@ impl Format> for FormatLeadingAlternateBranchComments<'_> { } else { last_preceding.end() }; - if lines_after(end, f.context().source()) > 1 { - write!(f, [empty_line()])?; - } + write!(f, [empty_lines(lines_after(end, f.context().source()))])?; } Ok(()) diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__if.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__if.py.snap index 02ff05a955..dbafb690c0 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__if.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__if.py.snap @@ -144,6 +144,54 @@ if True: else: pass +if True: + pass + + # comment + +else: + pass + +if True: + pass + + # comment + + +else: + pass + +if True: + pass + + # comment + + + +else: + pass + +if True: + if True: + pass + # comment + + else: + pass +else: + pass + +if True: + if True: + pass + # comment + + + else: + pass +else: + pass + # Regression test for https://github.com/astral-sh/ruff/issues/5337 if parent_body: if current_body: @@ -197,6 +245,7 @@ elif aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + ]: ... + else: ... @@ -305,6 +354,52 @@ if True: else: pass +if True: + pass + + # comment + +else: + pass + +if True: + pass + + # comment + + +else: + pass + +if True: + pass + + # comment + + +else: + pass + +if True: + if True: + pass + # comment + + else: + pass +else: + pass + +if True: + if True: + pass + # comment + + else: + pass +else: + pass + # Regression test for https://github.com/astral-sh/ruff/issues/5337 if parent_body: if current_body: