rules.py
покрыто: 91 из 9298.9%
1"""Правила линтера: один выход на функцию, тело в 1-2 строки, без continue.23Выходом считается любой из узлов ``return``, ``break`` и ``while`` — по правилам4проекта цикл ``while`` сам является точкой выхода, поэтому функция не может5совмещать его с ``return``. Анализ идёт по AST, поэтому вложенные функции,6лямбды и строки не влияют на подсчёт.7"""89from __future__ import annotations1011import ast12from dataclasses import dataclass13from typing import Iterable, Iterator, Sequence1415DEFAULT_MAX_LINES = 216EXIT_TYPES = (ast.Return, ast.Break, ast.While)17EXIT_NAMES = {ast.Return: "return", ast.Break: "break", ast.While: "while"}1819SEVERITY_ERROR = "error"20SEVERITY_WARNING = "warning"212223class LintError(ValueError):24 """Исходный код не разбирается как Python."""2526 def __init__(self, message: str, line: int = 0, column: int = 0):27 super().__init__(message)28 self.message = message29 self.line = line30 self.column = column313233@dataclass(frozen=True)34class Violation:35 rule: str36 severity: str37 line: int38 column: int39 message: str40 function: str = ""4142 def as_dict(self) -> dict:43 return {44 "rule": self.rule,45 "severity": self.severity,46 "line": self.line,47 "column": self.column,48 "message": self.message,49 "function": self.function,50 }515253def parse(source: str) -> ast.Module:54 try:55 return ast.parse(source)56 except SyntaxError as exc:57 raise LintError(exc.msg or "синтаксическая ошибка", exc.lineno or 0, exc.offset or 0) from exc585960def iter_functions(tree: ast.AST) -> Iterator[ast.AST]:61 for node in ast.walk(tree):62 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):63 yield node646566def _nested_ids(function: ast.AST) -> set[int]:67 nested: set[int] = set()68 for child in ast.walk(function):69 if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)) and child is not function:70 nested.update(id(node) for node in ast.walk(child))71 return nested727374def own_nodes(function: ast.AST, types: tuple[type, ...]) -> list[ast.AST]:75 nested = _nested_ids(function)76 return [node for node in ast.walk(function) if isinstance(node, types) and id(node) not in nested]777879def find_exits(function: ast.AST) -> list[ast.AST]:80 return own_nodes(function, EXIT_TYPES)818283def exit_kinds(exits: Iterable[ast.AST]) -> list[str]:84 return sorted({EXIT_NAMES[type(node)] for node in exits})858687def function_lines(function: ast.AST) -> int:88 end = getattr(function, "end_lineno", None) or function.lineno89 return end - function.lineno + 1909192def function_name(function: ast.AST) -> str:93 return getattr(function, "name", "<lambda>")949596def _exit_message(name: str, exits: list[ast.AST]) -> str:97 kinds = ", ".join(exit_kinds(exits)) or "нет"98 found = f"должно быть ровно одно место выхода, найдено {len(exits)} ({kinds})"99 missing = (100 "нет места выхода: нужен ровно один return, break или while "101 "(или флаг --allow-implicit-exit)"102 )103 return f"у функции «{name}» {found if exits else missing}"104105106def check_single_exit(function: ast.AST, allow_implicit: bool = False) -> list[Violation]:107 """Ровно один выход; неявный return — отдельный режим для служебного кода."""108 exits = find_exits(function)109 name = function_name(function)110 valid = len(exits) == 1 or (allow_implicit and not exits)111 violation = Violation(112 rule="single-exit",113 severity=SEVERITY_ERROR,114 line=function.lineno,115 column=function.col_offset + 1,116 message=_exit_message(name, exits),117 function=name,118 )119 return [] if valid else [violation]120121122def check_size(function: ast.AST, max_lines: int) -> list[Violation]:123 span = function_lines(function)124 name = function_name(function)125 violation = Violation(126 rule="small-function",127 severity=SEVERITY_ERROR,128 line=function.lineno,129 column=function.col_offset + 1,130 message=f"функция «{name}» занимает {span} строк, допустимо {max_lines}",131 function=name,132 )133 return [] if span <= max_lines else [violation]134135136def check_continue(function: ast.AST) -> list[Violation]:137 name = function_name(function)138 return [139 Violation(140 rule="no-continue",141 severity=SEVERITY_WARNING,142 line=node.lineno,143 column=node.col_offset + 1,144 message=f"функция «{name}»: continue — дополнительный выход, перепишите через if/else",145 function=name,146 )147 for node in own_nodes(function, (ast.Continue,))148 ]149150151def lint_code(152 source: str,153 max_lines: int = DEFAULT_MAX_LINES,154 allow_implicit_exit: bool = False,155) -> list[Violation]:156 tree = parse(source)157 violations: list[Violation] = []158 for function in iter_functions(tree):159 violations.extend(check_single_exit(function, allow_implicit_exit))160 violations.extend(check_size(function, max_lines))161 violations.extend(check_continue(function))162 return sorted(violations, key=lambda item: (item.line, item.column, item.rule))163164165def lint_files(166 paths: Sequence[str],167 max_lines: int = DEFAULT_MAX_LINES,168 allow_implicit_exit: bool = False,169) -> dict[str, list[Violation]]:170 from pathlib import Path171172 report: dict[str, list[Violation]] = {}173 for raw in paths:174 path = Path(raw)175 report[str(path)] = lint_code(path.read_text(encoding="utf-8"), max_lines, allow_implicit_exit)176 return report177178179def summary(violations: Iterable[Violation]) -> dict[str, int]:180 counts: dict[str, int] = {}181 for violation in violations:182 counts[violation.rule] = counts.get(violation.rule, 0) + 1183 return counts← ко всем файлам