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 a8a359f19c..1ed151c97d 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 @@ -186,6 +186,28 @@ if True: else: pass +if True: + pass +# comment +else: + pass + +if True: + pass + +# comment +else: + pass + +if True: + pass + + +# comment +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 559b7e605b..a5004da717 100644 --- a/crates/ruff_python_formatter/src/comments/format.rs +++ b/crates/ruff_python_formatter/src/comments/format.rs @@ -86,9 +86,13 @@ impl Format> for FormatLeadingAlternateBranchComments<'_> { if let Some(first_leading) = self.comments.first() { // Leading comments only preserves the lines after the comment but not before. // Insert the necessary lines. - if lines_before(first_leading.start(), f.context().source()) > 1 { - write!(f, [empty_line()])?; - } + write!( + f, + [empty_lines(lines_before( + first_leading.start(), + f.context().source() + ))] + )?; write!(f, [leading_comments(self.comments)])?; } else if let Some(last_preceding) = self.last_node { 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 dbafb690c0..f85326b157 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 @@ -192,6 +192,28 @@ if True: else: pass +if True: + pass +# comment +else: + pass + +if True: + pass + +# comment +else: + pass + +if True: + pass + + +# comment +else: + pass + + # Regression test for https://github.com/astral-sh/ruff/issues/5337 if parent_body: if current_body: @@ -400,6 +422,28 @@ if True: else: pass +if True: + pass +# comment +else: + pass + +if True: + pass + +# comment +else: + pass + +if True: + pass + + +# comment +else: + pass + + # Regression test for https://github.com/astral-sh/ruff/issues/5337 if parent_body: if current_body: