forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhass_imports.py
52 lines (41 loc) · 1.66 KB
/
hass_imports.py
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
"""Plugin for checking imports."""
from __future__ import annotations
from astroid import Import, ImportFrom, Module
from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker
from pylint.lint import PyLinter
class HassImportsFormatChecker(BaseChecker): # type: ignore[misc]
"""Checker for imports."""
__implements__ = IAstroidChecker
name = "hass_imports"
priority = -1
msgs = {
"W0011": (
"Relative import should be used",
"hass-relative-import",
"Used when absolute import should be replaced with relative import",
),
}
options = ()
def __init__(self, linter: PyLinter | None = None) -> None:
super().__init__(linter)
self.current_module: str | None = None
def visit_module(self, node: Module) -> None:
"""Called when a Import node is visited."""
self.current_module = node.name
def visit_import(self, node: Import) -> None:
"""Called when a Import node is visited."""
for module, _alias in node.names:
if module.startswith(f"{self.current_module}."):
self.add_message("hass-relative-import", node=node)
def visit_importfrom(self, node: ImportFrom) -> None:
"""Called when a ImportFrom node is visited."""
if node.level is not None:
return
if node.modname == self.current_module or node.modname.startswith(
f"{self.current_module}."
):
self.add_message("hass-relative-import", node=node)
def register(linter: PyLinter) -> None:
"""Register the checker."""
linter.register_checker(HassImportsFormatChecker(linter))