Skip to content

Commit

Permalink
Fix ordering for force-sort-within-sections (#8665)
Browse files Browse the repository at this point in the history
Fixes #8661 

## Summary

Imports like `from x import y` don't have an "asname" for the module, so
they were placed before imports like `import x as w` since `None` <
`Some(s)` for any string s.
The fix is to first sort by `first_alias`, since it's `None` for `import
x as w`, and then by `asname`.

## Test Plan

I included the example from the issue to avoid future regressions.
  • Loading branch information
bluthej committed Nov 13, 2023
1 parent 1606067 commit 23c819b
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import encodings
from datetime import timezone as tz
from datetime import timedelta
import datetime as dt
import datetime
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/isort/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,7 @@ mod tests {
}

#[test_case(Path::new("force_sort_within_sections.py"))]
#[test_case(Path::new("force_sort_within_sections_with_as_names.py"))]
fn force_sort_within_sections(path: &Path) -> Result<()> {
let snapshot = format!("force_sort_within_sections_{}", path.to_string_lossy());
let mut diagnostics = test_path(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
source: crates/ruff_linter/src/rules/isort/mod.rs
---
force_sort_within_sections_with_as_names.py:1:1: I001 [*] Import block is un-sorted or un-formatted
|
1 | / import encodings
2 | | from datetime import timezone as tz
3 | | from datetime import timedelta
4 | | import datetime as dt
5 | | import datetime
|
= help: Organize imports

Safe fix
1 |+import datetime
2 |+import datetime as dt
3 |+from datetime import timedelta
4 |+from datetime import timezone as tz
1 5 | import encodings
2 |-from datetime import timezone as tz
3 |-from datetime import timedelta
4 |-import datetime as dt
5 |-import datetime


4 changes: 2 additions & 2 deletions crates/ruff_linter/src/rules/isort/sorting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ pub(crate) struct ModuleKey<'a> {
force_to_top: Option<bool>,
maybe_lowercase_name: Option<NatOrdStr<'a>>,
module_name: Option<NatOrdStr<'a>>,
asname: Option<NatOrdStr<'a>>,
first_alias: Option<MemberKey<'a>>,
asname: Option<NatOrdStr<'a>>,
}

impl<'a> ModuleKey<'a> {
Expand Down Expand Up @@ -110,8 +110,8 @@ impl<'a> ModuleKey<'a> {
force_to_top,
maybe_lowercase_name,
module_name,
asname,
first_alias,
asname,
}
}
}
Expand Down

0 comments on commit 23c819b

Please sign in to comment.