-
Notifications
You must be signed in to change notification settings - Fork 903
/
banned_import_alias.rs
71 lines (66 loc) · 1.86 KB
/
banned_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
use rustc_hash::FxHashMap;
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Stmt;
use ruff_text_size::Ranged;
use crate::rules::flake8_import_conventions::settings::BannedAliases;
/// ## What it does
/// Checks for imports that use non-standard naming conventions, like
/// `import tensorflow.keras.backend as K`.
///
/// ## Why is this bad?
/// Consistency is good. Avoid using a non-standard naming convention for
/// imports, and, in particular, choosing import aliases that violate PEP 8.
///
/// For example, aliasing via `import tensorflow.keras.backend as K` violates
/// the guidance of PEP 8, and is thus avoided in some projects.
///
/// ## Example
/// ```python
/// import tensorflow.keras.backend as K
/// ```
///
/// Use instead:
/// ```python
/// import tensorflow as tf
///
/// tf.keras.backend
/// ```
///
/// ## Options
/// - `lint.flake8-import-conventions.banned-aliases`
#[violation]
pub struct BannedImportAlias {
name: String,
asname: String,
}
impl Violation for BannedImportAlias {
#[derive_message_formats]
fn message(&self) -> String {
let BannedImportAlias { name, asname } = self;
format!("`{name}` should not be imported as `{asname}`")
}
}
/// ICN002
pub(crate) fn banned_import_alias(
stmt: &Stmt,
name: &str,
asname: &str,
banned_conventions: &FxHashMap<String, BannedAliases>,
) -> Option<Diagnostic> {
if let Some(banned_aliases) = banned_conventions.get(name) {
if banned_aliases
.iter()
.any(|banned_alias| banned_alias == asname)
{
return Some(Diagnostic::new(
BannedImportAlias {
name: name.to_string(),
asname: asname.to_string(),
},
stmt.range(),
));
}
}
None
}