importer: skip whitespace between comments at start of file (#6523)

## Summary

When adding an import, such as when fixing `I002`, ruff doesn't skip
whitespace between comments, but isort does. See this issue for more
detail: https://github.com/astral-sh/ruff/issues/6504

This change would fix that by skipping whitespace between comments in
`Insertion.start_of_file()`.

## Test Plan

I added a new test, `comments_and_newlines`, to verify this behavior. I
also ran `cargo test` and no existing tests broke. That being said, this
is technically a breaking change, as it's possible that someone was
relying on the previous behavior.
This commit is contained in:
Presley Graham 2023-08-12 16:37:56 -04:00 committed by GitHub
parent 010293ddcc
commit dbf003fde4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 54 additions and 2 deletions

View file

@ -0,0 +1,6 @@
#!/usr/bin/env python3
# A copyright notice could go here
# A linter directive could go here
x = 1

View file

@ -67,9 +67,13 @@ impl<'a> Insertion<'a> {
TextSize::default()
};
// Skip over commented lines.
// Skip over commented lines, with whitespace separation.
for line in UniversalNewlineIterator::with_offset(locator.after(location), location) {
if line.trim_whitespace_start().starts_with('#') {
let trimmed_line = line.trim_whitespace_start();
if trimmed_line.is_empty() {
continue;
}
if trimmed_line.starts_with('#') {
location = line.full_end();
} else {
break;

View file

@ -762,6 +762,7 @@ mod tests {
}
#[test_case(Path::new("comment.py"))]
#[test_case(Path::new("comments_and_newlines.py"))]
#[test_case(Path::new("docstring.py"))]
#[test_case(Path::new("docstring.pyi"))]
#[test_case(Path::new("docstring_only.py"))]
@ -791,6 +792,7 @@ mod tests {
}
#[test_case(Path::new("comment.py"))]
#[test_case(Path::new("comments_and_newlines.py"))]
#[test_case(Path::new("docstring.py"))]
#[test_case(Path::new("docstring.pyi"))]
#[test_case(Path::new("docstring_only.py"))]

View file

@ -0,0 +1,20 @@
---
source: crates/ruff/src/rules/isort/mod.rs
---
comments_and_newlines.py:1:1: I002 [*] Missing required import: `from __future__ import annotations`
|
1 | #!/usr/bin/env python3
| I002
2 | # A copyright notice could go here
|
= help: Insert required import: `from future import annotations`
Fix
2 2 | # A copyright notice could go here
3 3 |
4 4 | # A linter directive could go here
5 |+from __future__ import annotations
5 6 |
6 7 | x = 1

View file

@ -0,0 +1,20 @@
---
source: crates/ruff/src/rules/isort/mod.rs
---
comments_and_newlines.py:1:1: I002 [*] Missing required import: `from __future__ import annotations as _annotations`
|
1 | #!/usr/bin/env python3
| I002
2 | # A copyright notice could go here
|
= help: Insert required import: `from future import annotations as _annotations`
Fix
2 2 | # A copyright notice could go here
3 3 |
4 4 | # A linter directive could go here
5 |+from __future__ import annotations as _annotations
5 6 |
6 7 | x = 1