gendesign/scripts/claude-hooks/check-no-print.py
Light1YT 86e9ea2937 fix(week-review): автофиксы код-ревью — 169 issue (label «week ревью 1»)
Многоагентный аудит + имплементация: один воркер на файл, точечные правки.
Верификация: py_compile (47/47 .py) + tsc --noEmit (0 ошибок). Unit-тесты
не прогонялись (окружение не поднято: rollup native dep / нет pytest-venv).

Полностью исправлено (169): #1336, #1337, #1339, #1340, #1341, #1342, #1343, #1345, #1346, #1348, #1349, #1350, #1351, #1354, #1356, #1358, #1359, #1360, #1362, #1364, #1365, #1366, #1367, #1368, #1369, #1370, #1371, #1372, #1373, #1374, #1375, #1376, #1377, #1378, #1379, #1380, #1381, #1382, #1384, #1385, #1386, #1387, #1388, #1389, #1390, #1391, #1392, #1394, #1395, #1396, #1397, #1399, #1400, #1401, #1402, #1403, #1404, #1408, #1409, #1410, #1411, #1412, #1413, #1414, #1415, #1416, #1417, #1418, #1420, #1423, #1425, #1426, #1427, #1428, #1429, #1430, #1431, #1432, #1433, #1434, #1435, #1437, #1438, #1439, #1440, #1441, #1442, #1443, #1444, #1445, #1446, #1447, #1448, #1449, #1450, #1451, #1452, #1453, #1454, #1455, #1456, #1457, #1458, #1459, #1460, #1461, #1462, #1463, #1464, #1465, #1466, #1467, #1468, #1469, #1471, #1472, #1473, #1474, #1476, #1478, #1479, #1481, #1482, #1483, #1484, #1485, #1487, #1488, #1489, #1490, #1491, #1492, #1493, #1494, #1495, #1496, #1497, #1499, #1500, #1501, #1502, #1504, #1505, #1506, #1507, #1510, #1514, #1515, #1516, #1517, #1518, #1519, #1521, #1522, #1523, #1524, #1525, #1526, #1527, #1528, #1529, #1531, #1532, #1533, #1534, #1535, #1536, #1537, #1538

Частично (9, in-file часть, остаток cross-file): #1361, #1419, #1422, #1424, #1470, #1475, #1477, #1480, #1498
Требуют cross-file (3, не тронуты): #1338, #1363, #1421
Пропущено (1): #1539

Не входило в партию: 22 needs-Leha issue (нужны решения владельца).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 20:21:11 +05:00

116 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""
Claude Code PostToolUse hook — blocks new `print(` calls in backend/**/*.py.
Wired in `.claude/settings.json` hooks.PostToolUse with matcher
"Edit|Write|MultiEdit".
Behavior:
- Reads hook input as JSON from stdin (per Anthropic spec).
- If tool is Edit/Write/MultiEdit and file_path matches backend/**/*.py:
- Scans new content for new `print(` calls.
- Exits with code 2 to block (stderr is forwarded to Claude as feedback).
- Otherwise exits 0 (no-op).
Notes:
- Allows `print(` inside lines containing `# noqa` (escape hatch).
- Skips files under `backend/tests/**` (test code may use print for debugging).
- Skips `backend/scripts/**` (one-off scripts).
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
ALLOW_PATH_PREFIXES = (
"backend/tests/",
"backend/scripts/",
)
WATCH_PATH_PREFIX = "backend/"
# Lookbehind `(?<![\w.])` rejects both word-char prefixes (e.g. `endprint(`)
# and method calls (e.g. `self.print(`, `logger.print(`), which are not the
# builtin `print`.
PRINT_RE = re.compile(r"(?<![\w.])print\s*\(")
def normalize_path(raw: str) -> str:
"""Convert absolute/relative path to repo-relative POSIX-like form."""
parts = Path(raw).parts
# Match the repo-root segment "backend" exactly (not a substring like
# "services-backend"), and anchor on the FIRST such segment so a nested
# "backend" dir does not drop the leading path components.
try:
idx = parts.index("backend")
except ValueError:
return Path(raw).as_posix()
return Path(*parts[idx:]).as_posix()
def main() -> int:
try:
payload = json.load(sys.stdin)
except Exception:
# No input or malformed — skip silently.
return 0
tool_name = payload.get("tool_name") or payload.get("tool") or ""
if tool_name not in {"Edit", "Write", "MultiEdit"}:
return 0
tool_input = payload.get("tool_input") or {}
file_path = tool_input.get("file_path") or tool_input.get("path") or ""
if not file_path:
return 0
norm = normalize_path(file_path)
if not norm.startswith(WATCH_PATH_PREFIX):
return 0
if any(norm.startswith(p) for p in ALLOW_PATH_PREFIXES):
return 0
if not norm.endswith(".py"):
return 0
# Pull the new content. Edit gives `new_string`, Write gives `content`,
# MultiEdit gives an `edits` array of `{old_string, new_string}` entries.
edits = tool_input.get("edits")
if isinstance(edits, list):
new_text = "\n".join(
str(e.get("new_string") or "")
for e in edits
if isinstance(e, dict)
)
else:
new_text = tool_input.get("new_string") or tool_input.get("content") or ""
if not new_text:
return 0
offenders: list[tuple[int, str]] = []
for lineno, line in enumerate(new_text.splitlines(), start=1):
if "# noqa" in line:
continue
# Skip whole-line comments (e.g. `# print(debug)`); regex on raw
# lines cannot see the surrounding syntax otherwise.
if line.lstrip().startswith("#"):
continue
if PRINT_RE.search(line):
offenders.append((lineno, line.strip()))
if not offenders:
return 0
sample = offenders[0]
msg_lines = [
f"Blocked: `print(` introduced in {norm}.",
f"Line {sample[0]}: {sample[1][:120]}",
"GenDesign convention: use `logger.info/warning/error` instead of print().",
"If this is intentional one-off debug, add `# noqa` on the line and retry.",
]
print("\n".join(msg_lines), file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())