fix: mark __main__ as first-party import (#8805)

## Summary

Fixes #8750. `import __main__` is now considered a first-party import,
and is grouped accordingly by the linter and formatter.

## Test Plan

Added a test based off code supplied in the linked issue.
This commit is contained in:
Ezra Shaw 2023-11-22 00:52:28 +13:00 committed by GitHub
parent 6ca2aaa245
commit bf729e7a77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 71 additions and 0 deletions

View file

@ -0,0 +1,11 @@
import os
import __main__
import third_party
import first_party
os.a
third_party.a
__main__.a
first_party.a

View file

@ -106,6 +106,11 @@ pub(crate) fn categorize<'a>(
&ImportSection::Known(ImportType::FirstParty),
Reason::SourceMatch(src),
)
} else if matches!(level, None | Some(0)) && module_name == "__main__" {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::KnownFirstParty,
)
} else {
(
&ImportSection::Known(ImportType::ThirdParty),

View file

@ -1033,6 +1033,30 @@ mod tests {
Ok(())
}
#[test_case(Path::new("main_first_party.py"))]
fn main_is_first_party(path: &Path) -> Result<()> {
let snapshot = format!("sections_{}", path.to_string_lossy());
let diagnostics = test_path(
Path::new("isort").join(path).as_path(),
&LinterSettings {
src: vec![test_resource_path("fixtures/isort")],
isort: super::settings::Settings {
known_modules: KnownModules::new(
vec![pattern("first_party")],
vec![],
vec![],
vec![],
FxHashMap::default(),
),
..super::settings::Settings::default()
},
..LinterSettings::for_rule(Rule::UnsortedImports)
},
)?;
assert_messages!(snapshot, diagnostics);
Ok(())
}
#[test]
fn detect_same_package() -> Result<()> {
let diagnostics = test_path(

View file

@ -0,0 +1,31 @@
---
source: crates/ruff_linter/src/rules/isort/mod.rs
---
main_first_party.py:1:1: I001 [*] Import block is un-sorted or un-formatted
|
1 | / import os
2 | |
3 | | import __main__
4 | | import third_party
5 | |
6 | | import first_party
7 | |
8 | | os.a
| |_^ I001
9 | third_party.a
10 | __main__.a
|
= help: Organize imports
Safe fix
1 1 | import os
2 2 |
3 |-import __main__
4 3 | import third_party
5 4 |
5 |+import __main__
6 6 | import first_party
7 7 |
8 8 | os.a