|
26 | 26 | # OR OTHER DEALINGS IN THE SOFTWARE. |
27 | 27 | # |
28 | 28 |
|
| 29 | +# stdlib |
| 30 | +import ast |
| 31 | +from abc import ABC, abstractmethod |
| 32 | +from typing import Iterator, List, Tuple, Type, TypeVar |
| 33 | + |
| 34 | +__all__ = ["Visitor", "_P", "Plugin"] |
| 35 | + |
29 | 36 | __author__: str = "Dominic Davis-Foster" |
30 | 37 | __copyright__: str = "2021 Dominic Davis-Foster" |
31 | 38 | __license__: str = "MIT License" |
32 | 39 | __version__: str = "0.0.0" |
33 | 40 | __email__: str = "[email protected]" |
| 41 | + |
| 42 | +_P = TypeVar("_P", bound="Plugin") |
| 43 | + |
| 44 | + |
| 45 | +class Visitor(ast.NodeVisitor): |
| 46 | + """ |
| 47 | + AST node visitor. |
| 48 | + """ |
| 49 | + |
| 50 | + def __init__(self) -> None: |
| 51 | + #: The list of Flake8 errors identified by the visitor. |
| 52 | + self.errors: List[Tuple[int, int, str]] = [] |
| 53 | + |
| 54 | + def report_error(self, node: ast.AST, error: str): |
| 55 | + """ |
| 56 | + Report an error for the given node. |
| 57 | +
|
| 58 | + :param node: |
| 59 | + :param error: |
| 60 | + """ |
| 61 | + |
| 62 | + self.errors.append(( |
| 63 | + node.lineno, |
| 64 | + node.col_offset, |
| 65 | + error, |
| 66 | + )) |
| 67 | + |
| 68 | + |
| 69 | +class Plugin(ABC): |
| 70 | + """ |
| 71 | + Abstract base class for Flake8 plugins. |
| 72 | +
|
| 73 | + :param tree: The abstract syntax tree (AST) to check. |
| 74 | +
|
| 75 | + **Minimum example:** |
| 76 | +
|
| 77 | + .. code=block:: python |
| 78 | +
|
| 79 | + class EncodingsPlugin(Plugin): |
| 80 | + ''' |
| 81 | + A Flake8 plugin to identify incorrect use of encodings. |
| 82 | +
|
| 83 | + :param tree: The abstract syntax tree (AST) to check. |
| 84 | + ''' |
| 85 | +
|
| 86 | + name: str = __name__ |
| 87 | + version: str = __version__ #: The plugin version |
| 88 | + """ |
| 89 | + |
| 90 | + def __init__(self, tree: ast.AST): |
| 91 | + |
| 92 | + #: The abstract syntax tree (AST) being checked. |
| 93 | + self._tree = tree |
| 94 | + |
| 95 | + @property |
| 96 | + @abstractmethod |
| 97 | + def name(self) -> str: |
| 98 | + """ |
| 99 | + The plugin name. |
| 100 | + """ |
| 101 | + |
| 102 | + raise NotImplementedError |
| 103 | + |
| 104 | + @property |
| 105 | + @abstractmethod |
| 106 | + def version(self) -> str: |
| 107 | + """ |
| 108 | + The plugin version. |
| 109 | + """ |
| 110 | + |
| 111 | + raise NotImplementedError |
| 112 | + |
| 113 | + def run(self: _P) -> Iterator[Tuple[int, int, str, Type[_P]]]: |
| 114 | + """ |
| 115 | + Traverse the Abstract Syntax Tree and identify errors. |
| 116 | +
|
| 117 | + Yields a tuple of (line number, column offset, error message, type(self)) |
| 118 | + """ |
| 119 | + |
| 120 | + visitor = Visitor() |
| 121 | + visitor.visit(self._tree) |
| 122 | + |
| 123 | + for line, col, msg in visitor.errors: |
| 124 | + yield line, col, msg, type(self) |
0 commit comments