-
Notifications
You must be signed in to change notification settings - Fork 883
/
unconventional_import_alias.rs
95 lines (84 loc) · 2.71 KB
/
unconventional_import_alias.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use rustc_hash::FxHashMap;
use ruff_diagnostics::{Diagnostic, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_semantic::{Binding, Imported};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;
use crate::renamer::Renamer;
/// ## What it does
/// Checks for imports that are typically imported using a common convention,
/// like `import pandas as pd`, and enforces that convention.
///
/// ## Why is this bad?
/// Consistency is good. Use a common convention for imports to make your code
/// more readable and idiomatic.
///
/// For example, `import pandas as pd` is a common
/// convention for importing the `pandas` library, and users typically expect
/// Pandas to be aliased as `pd`.
///
/// ## Example
/// ```python
/// import pandas
/// ```
///
/// Use instead:
/// ```python
/// import pandas as pd
/// ```
#[violation]
pub struct UnconventionalImportAlias {
name: String,
asname: String,
}
impl Violation for UnconventionalImportAlias {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;
#[derive_message_formats]
fn message(&self) -> String {
let UnconventionalImportAlias { name, asname } = self;
format!("`{name}` should be imported as `{asname}`")
}
fn fix_title(&self) -> Option<String> {
let UnconventionalImportAlias { name, asname } = self;
Some(format!("Alias `{name}` to `{asname}`"))
}
}
/// ICN001
pub(crate) fn unconventional_import_alias(
checker: &Checker,
binding: &Binding,
conventions: &FxHashMap<String, String>,
) -> Option<Diagnostic> {
let Some(import) = binding.as_any_import() else {
return None;
};
let qualified_name = import.qualified_name();
let Some(expected_alias) = conventions.get(qualified_name.as_str()) else {
return None;
};
let name = binding.name(checker.locator());
if binding.is_alias() && name == expected_alias {
return None;
}
let mut diagnostic = Diagnostic::new(
UnconventionalImportAlias {
name: qualified_name,
asname: expected_alias.to_string(),
},
binding.range(),
);
if checker.patch(diagnostic.kind.rule()) {
if !import.is_submodule_import() {
if checker.semantic().is_available(expected_alias) {
diagnostic.try_set_fix(|| {
let scope = &checker.semantic().scopes[binding.scope];
let (edit, rest) =
Renamer::rename(name, expected_alias, scope, checker.semantic())?;
Ok(Fix::suggested_edits(edit, rest))
});
}
}
}
Some(diagnostic)
}