Skip to content

Commit

Permalink
Add isort.order-by-type boolean setting
Browse files Browse the repository at this point in the history
The default `isort` behavior is `order-by-type = true`.
When imports are ordered by type:

1. `CONSTANT_VARIABLES` are first.
2. `CamelCaseClasses` are second.
3. `everything_else` is third.

- https://pycqa.github.io/isort/docs/configuration/options.html#order-by-type

When `order-by-type = false` imports are ordered alphabetically (case-insensitive).

eg.

`order-by-type = false`

```py
import BAR
import bar
import FOO
import foo
import StringIO
from module import Apple, BASIC, Class, CONSTANT, function
```

`order-by-type = true`

```py
import BAR
import bar
import FOO
import foo
import StringIO
from module import BASIC, CONSTANT, Apple, Class, function
```
  • Loading branch information
mattoberle committed Jan 3, 2023
1 parent 6907df4 commit f7722b9
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 6 deletions.
32 changes: 28 additions & 4 deletions src/isort/mod.rs
Expand Up @@ -371,7 +371,7 @@ fn categorize_imports<'a>(
block_by_type
}

fn sort_imports(block: ImportBlock) -> OrderedImportBlock {
fn sort_imports(block: ImportBlock, order_by_type: bool) -> OrderedImportBlock {
let mut ordered = OrderedImportBlock::default();

// Sort `StmtKind::Import`.
Expand Down Expand Up @@ -446,7 +446,9 @@ fn sort_imports(block: ImportBlock) -> OrderedImportBlock {
comments,
aliases
.into_iter()
.sorted_by_cached_key(|(alias, _)| member_key(alias.name, alias.asname))
.sorted_by_cached_key(|(alias, _)| {
member_key(alias.name, alias.asname, order_by_type)
})
.collect::<Vec<(AliasData, CommentSet)>>(),
)
})
Expand All @@ -461,7 +463,7 @@ fn sort_imports(block: ImportBlock) -> OrderedImportBlock {
.map(|module| module_key(module, None)),
aliases
.first()
.map(|(alias, _)| member_key(alias.name, alias.asname)),
.map(|(alias, _)| member_key(alias.name, alias.asname, order_by_type)),
)
}),
);
Expand All @@ -481,6 +483,7 @@ pub fn format_imports(
extra_standard_library: &BTreeSet<String>,
combine_as_imports: bool,
force_wrap_aliases: bool,
order_by_type: bool,
) -> String {
let trailer = &block.trailer;
let block = annotate_imports(&block.imports, comments);
Expand All @@ -503,7 +506,7 @@ pub fn format_imports(
// Generate replacement source code.
let mut is_first_block = true;
for import_block in block_by_type.into_values() {
let import_block = sort_imports(import_block);
let import_block = sort_imports(import_block, order_by_type);

// Add a blank line between every section.
if is_first_block {
Expand Down Expand Up @@ -645,4 +648,25 @@ mod tests {
insta::assert_yaml_snapshot!(snapshot, checks);
Ok(())
}

#[test_case(Path::new("order_by_type.py"))]
fn order_by_type(path: &Path) -> Result<()> {
let snapshot = format!("order_by_type_false_{}", path.to_string_lossy());
let mut checks = test_path(
Path::new("./resources/test/fixtures/isort")
.join(path)
.as_path(),
&Settings {
isort: isort::settings::Settings {
order_by_type: false,
..isort::settings::Settings::default()
},
src: vec![Path::new("resources/test/fixtures/isort").to_path_buf()],
..Settings::for_rule(CheckCode::I001)
},
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(snapshot, checks);
Ok(())
}
}
1 change: 1 addition & 0 deletions src/isort/plugins.rs
Expand Up @@ -80,6 +80,7 @@ pub fn check_imports(
&settings.isort.extra_standard_library,
settings.isort.combine_as_imports,
settings.isort.force_wrap_aliases,
settings.isort.order_by_type,
);

// Expand the span the entire range, including leading and trailing space.
Expand Down
28 changes: 27 additions & 1 deletion src/isort/settings.rs
Expand Up @@ -69,6 +69,17 @@ pub struct Options {
"#
)]
pub known_third_party: Option<Vec<String>>,
#[option(
doc = r#"
Order imports by type, which is determined by case, in addition to alphabetically.
"#,
default = r#"true"#,
value_type = "bool",
example = r#"
order-by-type = true
"#
)]
pub order_by_type: Option<bool>,
#[option(
doc = r#"
A list of modules to consider standard-library, in addition to those known to Ruff in
Expand All @@ -83,12 +94,13 @@ pub struct Options {
pub extra_standard_library: Option<Vec<String>>,
}

#[derive(Debug, Hash, Default)]
#[derive(Debug, Hash)]
pub struct Settings {
pub combine_as_imports: bool,
pub force_wrap_aliases: bool,
pub known_first_party: BTreeSet<String>,
pub known_third_party: BTreeSet<String>,
pub order_by_type: bool,
pub extra_standard_library: BTreeSet<String>,
}

Expand All @@ -99,9 +111,23 @@ impl Settings {
force_wrap_aliases: options.force_wrap_aliases.unwrap_or_default(),
known_first_party: BTreeSet::from_iter(options.known_first_party.unwrap_or_default()),
known_third_party: BTreeSet::from_iter(options.known_third_party.unwrap_or_default()),
order_by_type: options.order_by_type.unwrap_or_default(),
extra_standard_library: BTreeSet::from_iter(
options.extra_standard_library.unwrap_or_default(),
),
}
}
}

impl Default for Settings {
fn default() -> Self {
Self {
combine_as_imports: false,
force_wrap_aliases: false,
known_first_party: BTreeSet::new(),
known_third_party: BTreeSet::new(),
order_by_type: true,
extra_standard_library: BTreeSet::new(),
}
}
}
@@ -0,0 +1,20 @@
---
source: src/isort/mod.rs
expression: checks
---
- kind: UnsortedImports
location:
row: 1
column: 0
end_location:
row: 13
column: 0
fix:
content: "import glob\nimport os\nimport shutil\nimport tempfile\nimport time\nfrom subprocess import PIPE, Popen, STDOUT\n\nimport BAR\nimport bar\nimport FOO\nimport foo\nimport StringIO\nfrom module import Apple, BASIC, Class, CONSTANT, function\n"
location:
row: 1
column: 0
end_location:
row: 13
column: 0

5 changes: 4 additions & 1 deletion src/isort/sorting.rs
Expand Up @@ -18,9 +18,12 @@ pub fn module_key<'a>(
pub fn member_key<'a>(
name: &'a str,
asname: Option<&'a String>,
order_by_type: bool,
) -> (Prefix, String, Option<&'a String>) {
(
if name.len() > 1 && string::is_upper(name) {
if !order_by_type {
Prefix::Variables
} else if name.len() > 1 && string::is_upper(name) {
// Ex) `CONSTANT`
Prefix::Constants
} else if name.chars().next().map_or(false, char::is_uppercase) {
Expand Down

0 comments on commit f7722b9

Please sign in to comment.