File size: 3,416 Bytes
25834e9 | 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | #!/usr/bin/env python3
"""Reject multi-line comment blocks in newly ADDED Python lines.
House rule: a backend comment is one line, and only for a constraint the
code cannot show; rationale belongs in the commit message. Only added
lines are judged, so touching a legacy file does not inherit its
comments. A block whose first line ends in ``(keep)`` is allowed, for the
rare table or diagram that needs the room.
"""
from __future__ import annotations
import re
import subprocess
import sys
from functools import lru_cache
_MAX_RUN = 2
_KEEP = re.compile(r"\(keep\)\s*$")
_DIVIDER = re.compile(r"^\s*#\s*[─=—-]{3,}")
_HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
@lru_cache(maxsize=1)
def staged_additions() -> dict[str, list[tuple[int, str]]]:
"""(line number, text) for every line this commit adds, by path."""
try:
diff = subprocess.run(
["git", "diff", "--cached", "-U0", "-M"],
capture_output=True,
text=True,
check=False,
).stdout
except OSError:
return {}
out: dict[str, list[tuple[int, str]]] = {}
current: list[tuple[int, str]] = []
lineno = 0
for line in diff.splitlines():
if line.startswith("+++ "):
current = out.setdefault(line[6:] if line.startswith("+++ b/") else "", [])
continue
hunk = _HUNK.match(line)
if hunk:
lineno = int(hunk.group(1))
continue
if line.startswith("+"):
current.append((lineno, line[1:]))
lineno += 1
return out
def added_lines(path: str) -> list[tuple[int, str]]:
"""Diffed as a whole so a renamed file only reports its changed lines."""
return staged_additions().get(path, [])
def offenders(added: list[tuple[int, str]]) -> list[tuple[int, int]]:
blocks: list[tuple[int, int]] = []
start = prev = None
run = 0
keep = False
for lineno, text in added:
stripped = text.strip()
is_comment = stripped.startswith("#") and not _DIVIDER.match(text)
contiguous = prev is not None and lineno == prev + 1
if is_comment and (start is None or contiguous):
if start is None:
start, run, keep = lineno, 1, bool(_KEEP.search(text))
else:
run += 1
prev = lineno
continue
if start is not None and run > _MAX_RUN and not keep:
blocks.append((start, run))
if is_comment:
start, run, keep, prev = lineno, 1, bool(_KEEP.search(text)), lineno
else:
start, run, keep, prev = None, 0, False, lineno
if start is not None and run > _MAX_RUN and not keep:
blocks.append((start, run))
return blocks
def main(paths: list[str]) -> int:
failed = False
for path in paths:
if not path.endswith(".py"):
continue
for start, length in offenders(added_lines(path)):
failed = True
print(
f"{path}:{start}: {length} new consecutive comment lines "
f"(max {_MAX_RUN}). Say it in one line, or put the "
f"rationale in the commit message."
)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
|