Skip to content

Commit

Permalink
Ignore blank lines between comments when counting newlines-after-impo…
Browse files Browse the repository at this point in the history
…rts (#7607)

## Summary

Given:

```python
# -*- coding: utf-8 -*-
import random

# Defaults for arguments are defined here
# args.threshold = None;


logger = logging.getLogger("FastProject")
```

We want to count the number of newlines after `import random`, to ensure
that there's _at least one_, but up to two.

Previously, we used the end range of the statement (then skipped
trivia); instead, we need to use the end of the _last comment_. This is
similar to #7556.

Closes #7604.
  • Loading branch information
charliermarsh authored Sep 22, 2023
1 parent 8bfe9bd commit 5174e8c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,12 @@ def func():


x = 1

# Regression test for: https://github.com/astral-sh/ruff/issues/7604
import os

# Defaults for arguments are defined here
# args.threshold = None;


logger = logging.getLogger("FastProject")
7 changes: 6 additions & 1 deletion crates/ruff_python_formatter/src/statement/suite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,12 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
// a leading comment.
match self.kind {
SuiteKind::TopLevel => {
match lines_after_ignoring_trivia(preceding.end(), source) {
let end = if let Some(last_trailing) = preceding_comments.trailing.last() {
last_trailing.end()
} else {
preceding.end()
};
match lines_after(end, source) {
0..=2 => empty_line().fmt(f)?,
_ => match source_type {
PySourceType::Stub => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ def func():
x = 1
# Regression test for: https://github.com/astral-sh/ruff/issues/7604
import os
# Defaults for arguments are defined here
# args.threshold = None;
logger = logging.getLogger("FastProject")
```

## Output
Expand Down Expand Up @@ -130,6 +139,16 @@ def func():
import sys
x = 1
# Regression test for: https://github.com/astral-sh/ruff/issues/7604
import os
# Defaults for arguments are defined here
# args.threshold = None;
logger = logging.getLogger("FastProject")
```


Expand Down

0 comments on commit 5174e8c

Please sign in to comment.