Skip BOM when determining Locator's line starts (#6159)

## Summary

If a file has a BOM, the import sorter _always_ reports the imports as
unsorted. The acute issue is that we detect that the line has leading
content (before the imports), which we always consider a violation.
Rather than fixing that one site, this PR instead makes `.line_start`
BOM-aware.

Fixes https://github.com/astral-sh/ruff/issues/6155.
This commit is contained in:
Charlie Marsh 2023-07-29 07:47:13 -04:00 committed by GitHub
parent 44bdf20221
commit badbfb2d3e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 32 additions and 0 deletions

View file

@ -0,0 +1,2 @@
import bar
import foo

View file

@ -0,0 +1,2 @@
import foo
import bar

View file

@ -314,6 +314,8 @@ mod tests {
#[test_case(Path::new("add_newline_before_comments.py"))]
#[test_case(Path::new("as_imports_comments.py"))]
#[test_case(Path::new("bom_sorted.py"))]
#[test_case(Path::new("bom_unsorted.py"))]
#[test_case(Path::new("combine_as_imports.py"))]
#[test_case(Path::new("combine_import_from.py"))]
#[test_case(Path::new("comments.py"))]

View file

@ -0,0 +1,4 @@
---
source: crates/ruff/src/rules/isort/mod.rs
---

View file

@ -0,0 +1,18 @@
---
source: crates/ruff/src/rules/isort/mod.rs
---
bom_unsorted.py:1:1: I001 [*] Import block is un-sorted or un-formatted
|
1 | import foo
| _^
2 | | import bar
|
= help: Organize imports
Fix
1 |-import foo
2 |-import bar
1 |+import bar
2 |+import foo

View file

@ -76,7 +76,11 @@ impl<'a> Locator<'a> {
if let Some(index) = memrchr2(b'\n', b'\r', bytes) {
// SAFETY: Safe because `index < offset`
TextSize::try_from(index).unwrap().add(TextSize::from(1))
} else if self.contents.starts_with('\u{feff}') {
// Skip the BOM.
'\u{feff}'.text_len()
} else {
// Start of file.
TextSize::default()
}
}