codeveto 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1094 @@
1
+ """Hygiene pack (SPEC 6.1): conflict markers, leftovers, risky files and weakened gates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import re
7
+ import textwrap
8
+ import warnings
9
+ from collections.abc import Iterator
10
+
11
+ from codeveto import languages, lexers, yamlish
12
+ from codeveto.git import FLAG_IMAGE_PREFIX, FLAG_MODE_CHANGE, FLAG_NUL_BYTES
13
+ from codeveto.lexers import CommentSpan
14
+ from codeveto.model import FileKind, FileStatus, git_lines
15
+ from codeveto.rules.base import FileContext, Hit, Severity, line_windows, rule
16
+ from codeveto.rules.config import json_keys, parse_json
17
+
18
+ _START = "<<<<<<<"
19
+ _BASE = "|||||||"
20
+ _SEPARATOR = "======="
21
+ _END = ">>>>>>>"
22
+
23
+
24
+ def _marker(line: str) -> str | None:
25
+ """The conflict marker ``line`` is, if any (column 0, no indentation).
26
+
27
+ ``<<<<<<<``, ``|||||||`` and ``>>>>>>>`` are exactly seven characters
28
+ followed by a space, a tab or the end of the line (Git appends a label);
29
+ ``=======`` stands alone apart from trailing whitespace.
30
+ """
31
+ head = line[:7]
32
+ if head in (_START, _BASE, _END):
33
+ return head if line[7:8] in ("", " ", "\t", "\r") else None
34
+ if head == _SEPARATOR and not line[7:].strip():
35
+ return head
36
+ return None
37
+
38
+
39
+ def _fence(line: str) -> tuple[str, int] | None:
40
+ """``(char, length)`` of a Markdown code fence line (up to three spaces of indent)."""
41
+ stripped = line.lstrip(" ")
42
+ if len(line) - len(stripped) > 3 or stripped[:3] not in ("```", "~~~"):
43
+ return None
44
+ char = stripped[0]
45
+ length = len(stripped) - len(stripped.lstrip(char))
46
+ if char == "`" and "`" in stripped[length:]:
47
+ return None # an info string may not contain backticks
48
+ return char, length
49
+
50
+
51
+ def _fenced_lines(lines: tuple[str, ...]) -> frozenset[int]:
52
+ """Line numbers inside Markdown fenced code blocks, fences included."""
53
+ inside: set[int] = set()
54
+ opened: tuple[str, int] | None = None
55
+ for number, line in enumerate(lines, start=1):
56
+ fence = _fence(line)
57
+ if opened is None:
58
+ if fence is not None:
59
+ opened = fence
60
+ inside.add(number)
61
+ continue
62
+ inside.add(number)
63
+ if (
64
+ fence is not None
65
+ and fence[0] == opened[0]
66
+ and fence[1] >= opened[1]
67
+ and not line.strip().lstrip(fence[0])
68
+ ):
69
+ opened = None
70
+ return frozenset(inside)
71
+
72
+
73
+ def conflict_blocks(
74
+ lines: tuple[str, ...], skip: frozenset[int] = frozenset()
75
+ ) -> Iterator[tuple[tuple[int, str], ...]]:
76
+ """Complete conflict blocks: ``<<<<<<<`` [``|||||||``] ``=======`` ``>>>>>>>`` in order.
77
+
78
+ Each block is its marker lines as ``(number, marker)``. A new ``<<<<<<<``
79
+ restarts an unfinished block; lines in ``skip`` are never markers.
80
+ """
81
+ block: list[tuple[int, str]] = []
82
+ separated = False
83
+ for number, line in enumerate(lines, start=1):
84
+ if number in skip:
85
+ continue
86
+ marker = _marker(line)
87
+ if marker is None:
88
+ continue
89
+ if marker == _START:
90
+ block, separated = [(number, marker)], False
91
+ elif not block:
92
+ continue
93
+ elif marker == _BASE and not separated:
94
+ block.append((number, marker))
95
+ elif marker == _SEPARATOR and not separated:
96
+ block.append((number, marker))
97
+ separated = True
98
+ elif marker == _END and separated:
99
+ block.append((number, marker))
100
+ yield tuple(block)
101
+ block, separated = [], False
102
+
103
+
104
+ @rule(
105
+ id="hygiene/conflict-marker",
106
+ severity="error",
107
+ title="Merge conflict marker",
108
+ scope="line",
109
+ rationale=(
110
+ "A conflict marker means a merge was committed unresolved: the file holds both "
111
+ "versions and usually no longer builds or parses."
112
+ ),
113
+ hint="Resolve the conflict, keep the intended version and remove every marker line.",
114
+ tags={"hygiene", "merge"},
115
+ )
116
+ def conflict_marker(ctx: FileContext) -> Iterator[Hit]:
117
+ """A complete conflict block with at least one marker on a changed line.
118
+
119
+ The markers must come in Git's order (``<<<<<<<``, optionally the diff3
120
+ ``|||||||``, ``=======``, ``>>>>>>>``), each at column 0, so a lone
121
+ setext heading underline, a mail quote or an indented example (a YAML
122
+ block scalar, a reStructuredText literal block) is not a hit. In Markdown,
123
+ lines inside fenced code blocks are documentation and never markers.
124
+ Fixture files that hold conflicts on purpose are a job for config
125
+ ignores, not for this rule. Every marker line of the block is reported;
126
+ the engine keeps those on changed lines.
127
+ """
128
+ if not ctx.added_lines:
129
+ return
130
+ lines = ctx.lines
131
+ skip = _fenced_lines(lines) if ctx.language == "markdown" else frozenset()
132
+ for block in conflict_blocks(lines, skip):
133
+ for number, marker in block:
134
+ yield Hit(number, column=1, evidence=marker, message=f"Conflict marker {marker}")
135
+
136
+
137
+ # --- Shared helpers ------------------------------------------------------------------------
138
+
139
+ _EXECUTABLE = "100755"
140
+ _REGULAR = "100644"
141
+ _ALL_CLASSES = frozenset(languages.FILE_CLASSES)
142
+ _HYGIENE_CLASSES = _ALL_CLASSES - {"generated", "vendored", "minified"}
143
+
144
+
145
+ def _basename(path: str) -> str:
146
+ return path.rsplit("/", 1)[-1]
147
+
148
+
149
+ def _extension(name: str) -> str:
150
+ dot = name.rfind(".")
151
+ return name[dot:].lower() if dot > 0 else ""
152
+
153
+
154
+ def _file_level(ctx: FileContext) -> bool:
155
+ """May this file take a file-level hit (``line=None``)?"""
156
+ return (
157
+ ctx.change.status
158
+ in (FileStatus.ADDED, FileStatus.DELETED, FileStatus.RENAMED, FileStatus.TYPE_CHANGED)
159
+ or FLAG_MODE_CHANGE in ctx.flags
160
+ or ctx.kind is not FileKind.TEXT
161
+ )
162
+
163
+
164
+ def _whole_file(ctx: FileContext, message: str) -> Hit | None:
165
+ """A hit about the file: file-level when allowed, else spanning every line.
166
+
167
+ The span anchors to the first changed line (or deletion point).
168
+ """
169
+ if _file_level(ctx):
170
+ return Hit(None, message=message)
171
+ last = max(len(ctx.lines), max(ctx.deletion_points, default=0))
172
+ if last < 1:
173
+ return None
174
+ return Hit(1, end_line=last if last > 1 else None, message=message)
175
+
176
+
177
+ def _added_line_with(ctx: FileContext, needles: tuple[str, ...]) -> int | None:
178
+ """First added line that contains one of ``needles``."""
179
+ lines = ctx.lines
180
+ for number in sorted(ctx.added_lines):
181
+ if number <= len(lines) and any(n in lines[number - 1] for n in needles):
182
+ return number
183
+ return None
184
+
185
+
186
+ def _comment_lines(ctx: FileContext) -> Iterator[tuple[CommentSpan, int, str]]:
187
+ """``(span, line, text)`` for each line of each comment (its content only)."""
188
+ text = ctx.new_text or ""
189
+ index = ctx.line_index
190
+ for span in ctx.comments():
191
+ body = text[span.content_start : span.content_end]
192
+ line = index.line_of(span.content_start)
193
+ for part in body.split("\n"):
194
+ yield span, line, part
195
+ line += 1
196
+
197
+
198
+ # --- NUL bytes -----------------------------------------------------------------------------
199
+
200
+
201
+ @rule(
202
+ id="hygiene/nul-in-source",
203
+ severity="error",
204
+ title="NUL byte in a text file",
205
+ scope="line",
206
+ introduced_only=False,
207
+ rationale=(
208
+ "Git and reviewers treat a NUL byte as binary content: diffs hide it, compilers and "
209
+ "interpreters often reject it, and it can smuggle content past review."
210
+ ),
211
+ hint="Remove the NUL byte; write it as an escape sequence if the program needs one.",
212
+ tags={"hygiene", "encoding"},
213
+ )
214
+ def nul_in_source(ctx: FileContext) -> Iterator[Hit]:
215
+ """The first changed line of a file Git intake kept as text that adds a NUL character.
216
+
217
+ Intake keeps a file with NUL bytes as text when its name is source-like,
218
+ it starts with a shebang or it is executable, and flags it ``nul-bytes``.
219
+ One finding per file, at the first such line, counting the others: an
220
+ executable binary reviewed as text has a NUL on nearly every line, and
221
+ thousands of identical findings would bury the rest of the review. A
222
+ changed line whose text (whitespace collapsed) a removed line of the old
223
+ side already had is old content moved or kept, not a new NUL.
224
+ """
225
+ if FLAG_NUL_BYTES not in ctx.flags and "\0" not in (ctx.new_text or ""):
226
+ return
227
+ before: dict[str, int] = {}
228
+ for _, text in ctx.changed_lines("old"):
229
+ if "\0" in text:
230
+ key = " ".join(text.split())
231
+ before[key] = before.get(key, 0) + 1
232
+ first: tuple[int, int | None] | None = None
233
+ lines: set[int] = set()
234
+ for number, text in ctx.changed_lines():
235
+ i = text.find("\0")
236
+ if i < 0 or number in lines:
237
+ continue
238
+ key = " ".join(text.split())
239
+ if before.get(key, 0) > 0:
240
+ before[key] -= 1
241
+ continue
242
+ lines.add(number)
243
+ if first is None:
244
+ first = (number, text.column(i))
245
+ if first is not None:
246
+ more = len(lines) - 1
247
+ message = "NUL byte in a text file" + (
248
+ f" (and on {more} more changed line{'s' if more > 1 else ''})" if more else ""
249
+ )
250
+ yield Hit(first[0], column=first[1], message=message, evidence="NUL")
251
+
252
+
253
+ # --- Debug artifacts -----------------------------------------------------------------------
254
+
255
+ DEBUG_ARTIFACTS = (
256
+ ("core, core.<pid> (binary only)", "core dump"),
257
+ ("*.hprof, *.heapsnapshot, *.cpuprofile", "heap or CPU profile"),
258
+ (
259
+ "npm-debug.log*, yarn-error.log, yarn-debug.log*, pnpm-debug.log*, lerna-debug.log*, "
260
+ "hs_err_pid<pid>.log, replay_pid<pid>.log",
261
+ "crash or debug log",
262
+ ),
263
+ ("*.orig, *.rej", "patch or merge leftover"),
264
+ )
265
+ """Names ``hygiene/debug-artifact`` reports, with what each is."""
266
+
267
+ _CORE = re.compile(r"core(?:\.\d{1,10})?")
268
+ _PROFILE = re.compile(r".{1,255}\.(?:hprof|heapsnapshot|cpuprofile)")
269
+ _CRASH_LOG = re.compile(
270
+ r"(?:npm-debug|yarn-debug|pnpm-debug|lerna-debug)\.log.{0,64}|yarn-error\.log"
271
+ r"|(?:hs_err|replay)_pid\d{1,10}\.log"
272
+ )
273
+ _PATCH_LEFTOVER = re.compile(r".{1,255}\.(?:orig|rej)")
274
+ # ``cargo package`` writes the manifest as the author wrote it next to the normalized one,
275
+ # so every published and vendored crate has one (precision audit: the Cargo registry).
276
+ _PACKAGED_ORIGINALS = frozenset({"Cargo.toml.orig"})
277
+
278
+
279
+ def _debug_artifact(name: str, kind: FileKind) -> str | None:
280
+ if _CORE.fullmatch(name):
281
+ return "core dump" if kind is FileKind.BINARY else None
282
+ if _PROFILE.fullmatch(name):
283
+ return "heap or CPU profile"
284
+ if _CRASH_LOG.fullmatch(name):
285
+ return "crash or debug log"
286
+ if _PATCH_LEFTOVER.fullmatch(name) and name not in _PACKAGED_ORIGINALS:
287
+ return "patch or merge leftover"
288
+ return None
289
+
290
+
291
+ @rule(
292
+ id="hygiene/debug-artifact",
293
+ severity="error",
294
+ title="Debugging leftover committed",
295
+ classes=_HYGIENE_CLASSES - {"test"},
296
+ scope="file",
297
+ kinds=(FileKind.TEXT, FileKind.BINARY, FileKind.LFS_POINTER),
298
+ rationale=(
299
+ "Core dumps, heap profiles, crash logs and patch leftovers never belong in a "
300
+ "repository: they bloat it, and dumps and profiles hold process memory, which can "
301
+ "include secrets and personal data."
302
+ ),
303
+ hint="Remove the file and add its pattern to .gitignore.",
304
+ tags={"hygiene", "leak"},
305
+ )
306
+ def debug_artifact(ctx: FileContext) -> Iterator[Hit]:
307
+ """A file with a :data:`DEBUG_ARTIFACTS` name is added (or renamed into place).
308
+
309
+ ``core`` and ``core.<pid>`` count only as binaries, so a script named
310
+ ``core`` is fine. Test files are skipped: patch tools keep ``.orig`` and
311
+ ``.rej`` fixtures. ``Cargo.toml.orig`` is the original manifest ``cargo
312
+ package`` ships in every crate, not a leftover.
313
+ """
314
+ if ctx.change.status not in (FileStatus.ADDED, FileStatus.RENAMED):
315
+ return
316
+ what = _debug_artifact(_basename(ctx.path), ctx.kind)
317
+ if what is not None:
318
+ yield Hit(None, message=f"Committed {what}")
319
+
320
+
321
+ # --- Symlinks ------------------------------------------------------------------------------
322
+
323
+ _DRIVE = re.compile(r"[A-Za-z]:[\\/]")
324
+
325
+
326
+ def symlink_escapes(path: str, target: str) -> bool:
327
+ """Does a symlink at ``path`` to ``target`` point outside the repository?
328
+
329
+ Absolute targets (POSIX, Windows drive or UNC) always do; a relative one
330
+ does when ``..`` climbs above the root after normalizing.
331
+ """
332
+ if target.startswith(("/", "\\\\")) or _DRIVE.match(target):
333
+ return True
334
+ parts = path.split("/")[:-1]
335
+ for segment in target.replace("\\", "/").split("/"):
336
+ if segment in ("", "."):
337
+ continue
338
+ if segment == "..":
339
+ if not parts:
340
+ return True
341
+ parts.pop()
342
+ else:
343
+ parts.append(segment)
344
+ return False
345
+
346
+
347
+ def _symlink_target(ctx: FileContext) -> str | None:
348
+ if ctx.kind is not FileKind.SYMLINK or ctx.change.status is FileStatus.DELETED:
349
+ return None
350
+ return ctx.change.symlink_target
351
+
352
+
353
+ @rule(
354
+ id="hygiene/symlink-escapes-repo",
355
+ severity="error",
356
+ title="Symlink points outside the repository",
357
+ classes=_ALL_CLASSES,
358
+ scope="file",
359
+ kinds=(FileKind.SYMLINK,),
360
+ rationale=(
361
+ "A symlink to an absolute path or above the repository root makes builds, tools and "
362
+ "CI read or write files outside the checkout, such as credentials in the home "
363
+ "directory."
364
+ ),
365
+ hint="Point the link at a path inside the repository, or copy the file instead.",
366
+ tags={"hygiene", "security"},
367
+ )
368
+ def symlink_escapes_repo(ctx: FileContext) -> Iterator[Hit]:
369
+ """An added, retargeted or moved symlink whose target leaves the repository."""
370
+ target = _symlink_target(ctx)
371
+ if target is not None and symlink_escapes(ctx.path, target):
372
+ yield Hit(None, message="Symlink points outside the repository")
373
+
374
+
375
+ @rule(
376
+ id="hygiene/symlink-added",
377
+ severity="warning",
378
+ title="Symlink added",
379
+ classes=_HYGIENE_CLASSES,
380
+ scope="file",
381
+ kinds=(FileKind.SYMLINK,),
382
+ rationale=(
383
+ "A symlink changes what a path holds without any content showing in the diff, and "
384
+ "behaves differently on Windows checkouts and in archives."
385
+ ),
386
+ hint="Check that the target is intended and that every platform you ship to handles it.",
387
+ tags={"hygiene"},
388
+ )
389
+ def symlink_added(ctx: FileContext) -> Iterator[Hit]:
390
+ """A new symlink (or a file turned into one) whose target stays inside the repository.
391
+
392
+ Targets outside it are ``hygiene/symlink-escapes-repo`` instead.
393
+ """
394
+ target = _symlink_target(ctx)
395
+ if target is None or ctx.change.status not in (FileStatus.ADDED, FileStatus.TYPE_CHANGED):
396
+ return
397
+ if not symlink_escapes(ctx.path, target):
398
+ yield Hit(None, message="Symlink added")
399
+
400
+
401
+ # --- Large files ---------------------------------------------------------------------------
402
+
403
+ LARGE_FILE_BYTES = 512 * 1024
404
+ """Text files above this size are reported by ``hygiene/large-file``."""
405
+
406
+
407
+ @rule(
408
+ id="hygiene/large-file",
409
+ severity="warning",
410
+ title="Large text file",
411
+ classes=_HYGIENE_CLASSES - {"lockfile"},
412
+ scope="file",
413
+ rationale=(
414
+ "A text file over 512 KiB is rarely written by hand: it is usually data, a build "
415
+ "output or a dump; it bloats every clone and nobody reviews it line by line."
416
+ ),
417
+ hint="Generate it at build time, store it with Git LFS, or keep it out of the repository.",
418
+ tags={"hygiene", "size"},
419
+ )
420
+ def large_file(ctx: FileContext) -> Iterator[Hit]:
421
+ """A text file added above 512 KiB, or grown past it. Lockfiles are skipped."""
422
+ size = ctx.size
423
+ if ctx.new_text is None or size is None or size <= LARGE_FILE_BYTES:
424
+ return
425
+ old = ctx.change.old_size
426
+ if old is not None and old > LARGE_FILE_BYTES:
427
+ return
428
+ hit = _whole_file(ctx, f"Text file of {size // 1024} KiB")
429
+ if hit is not None:
430
+ yield hit
431
+
432
+
433
+ # --- Blanket suppressions ------------------------------------------------------------------
434
+
435
+ _PY_BLANKET = re.compile(
436
+ r"(?:^|#)[ \t]{0,8}(?:"
437
+ r"(?:(?:flake8|ruff)[ \t]{0,4}:[ \t]{0,4})?noqa\b(?![ \t]{0,4}:)"
438
+ r"|type:[ \t]{0,4}ignore\b(?![ \t]{0,4}\[)"
439
+ r"|pyright:[ \t]{0,4}ignore\b(?![ \t]{0,4}\[)"
440
+ r"|pylint:[ \t]{0,4}(?:disable[ \t]{0,4}=[ \t]{0,4}all\b|skip-file\b)"
441
+ r"|mypy:[ \t]{0,4}ignore-errors\b"
442
+ r")",
443
+ re.IGNORECASE,
444
+ )
445
+ _JS_BLANKET = re.compile(
446
+ r"[ \t*]{0,16}(?:eslint-disable(?:-next-line|-line)?(?:[ \t]{1,8}--[^\n]{0,500})?"
447
+ r"|@ts-nocheck\b[^\n]{0,500})[ \t*]{0,16}"
448
+ )
449
+ _GO_BLANKET = re.compile(r" ?nolint\b(?!:)")
450
+ _RUST_BLANKET = re.compile(
451
+ r"#!?\[[ \t]{0,4}allow[ \t]{0,4}\([ \t]{0,4}(?:warnings|clippy::all)[ \t]{0,4}\)[ \t]{0,4}\]"
452
+ )
453
+
454
+
455
+ @rule(
456
+ id="hygiene/blanket-suppression",
457
+ severity="warning",
458
+ title="Blanket lint or type suppression",
459
+ languages={"python", "javascript", "typescript", "go", "rust"},
460
+ scope="line",
461
+ rationale=(
462
+ "A suppression without a specific code silences every current and future finding "
463
+ "on that line or file, not just the one it was written for."
464
+ ),
465
+ hint=(
466
+ "Name the code being suppressed (noqa: E501, type: ignore[attr-defined], "
467
+ "eslint-disable-next-line no-console, nolint:errcheck)."
468
+ ),
469
+ tags={"hygiene", "suppression"},
470
+ )
471
+ def blanket_suppression(ctx: FileContext) -> Iterator[Hit]:
472
+ """Suppressions that name no rule.
473
+
474
+ Python ``# noqa``, ``# flake8: noqa``, ``# ruff: noqa``, ``# type: ignore``
475
+ and ``# pyright: ignore`` without codes, ``# pylint: disable=all`` and
476
+ ``skip-file``, ``# mypy: ignore-errors``; JavaScript/TypeScript
477
+ ``eslint-disable`` comments without rule names and ``@ts-nocheck``; Go
478
+ ``//nolint`` without linters; Rust ``#![allow(warnings)]`` and
479
+ ``allow(clippy::all)``. Suppressions that name their codes are fine.
480
+ """
481
+ added = ctx.added_lines
482
+ if not added:
483
+ return
484
+ language = ctx.language
485
+ if language == "rust":
486
+ masked = git_lines(ctx.masked_code)
487
+ for number in sorted(added):
488
+ if number > len(masked):
489
+ continue
490
+ for window in line_windows(masked[number - 1]):
491
+ m = _RUST_BLANKET.search(window)
492
+ if m:
493
+ yield Hit(number, column=window.column(m.start()), evidence=m.group())
494
+ break
495
+ for span, number, part in _comment_lines(ctx):
496
+ if number not in added:
497
+ continue
498
+ evidence: str | None = None
499
+ if language == "python":
500
+ m = _PY_BLANKET.search(part[:4000])
501
+ evidence = m.group().strip("# \t").lower() if m else None
502
+ elif language in ("javascript", "typescript"):
503
+ m = _JS_BLANKET.fullmatch(part[:4000])
504
+ evidence = m.group().strip(" \t*") if m else None
505
+ elif language == "go" and span.kind == "line":
506
+ evidence = "nolint" if _GO_BLANKET.match(part) else None
507
+ if evidence:
508
+ yield Hit(number, evidence=" ".join(evidence.split()))
509
+
510
+
511
+ # --- Weakened quality gates ----------------------------------------------------------------
512
+
513
+ _TSCONFIG = re.compile(r"tsconfig[^/]{0,64}\.json")
514
+ _TS_FLAGS = ("strict", "noImplicitAny", "strictNullChecks")
515
+ _ESLINT_DATA = frozenset({".eslintrc", ".eslintrc.json", ".eslintrc.yml", ".eslintrc.yaml"})
516
+ _ESLINT_CODE = re.compile(r"\.eslintrc\.c?js|eslint\.config\.[cm]?[jt]s")
517
+ _ESLINT_OFF = re.compile(
518
+ r"(?P<q>['\"]?)(?P<name>@?[A-Za-z0-9_][\w/@.-]{0,120})(?P=q)[ \t]{0,4}:[ \t]{0,4}"
519
+ r"\[?[ \t]{0,4}(?:(?P<s>['\"])off(?P=s)|0\b)"
520
+ )
521
+ _RUFF_FILES = frozenset({"pyproject.toml", "ruff.toml", ".ruff.toml"})
522
+ _MYPY_INI = frozenset({"mypy.ini", ".mypy.ini", "setup.cfg"})
523
+ _INI_SECTION = re.compile(r"[ \t]{0,16}\[([^\]\n]{1,200})\]")
524
+ _INI_IGNORE = re.compile(r"[ \t]{0,16}ignore_errors[ \t]{0,8}[=:][ \t]{0,8}(\S{1,16})")
525
+ _TRUE = frozenset({"true", "yes", "on", "1"})
526
+
527
+
528
+ def _get(mapping: object, *keys: str) -> object:
529
+ for key in keys:
530
+ if not isinstance(mapping, dict):
531
+ return None
532
+ mapping = mapping.get(key)
533
+ return mapping
534
+
535
+
536
+ def _hit_at(ctx: FileContext, line: int | None, message: str) -> Iterator[Hit]:
537
+ hit = Hit(line, message=message) if line else _whole_file(ctx, message)
538
+ if hit is not None:
539
+ yield hit
540
+
541
+
542
+ def _ts_weakened(ctx: FileContext) -> Iterator[Hit]:
543
+ new = ctx.new_text or ""
544
+ data, error = parse_json(new, jsonc=True)
545
+ if error is not None:
546
+ return
547
+ old_data = parse_json(ctx.old_text, jsonc=True)[0] if ctx.old_text else None
548
+ lines: dict[str, int] = {}
549
+ for key in json_keys(new, jsonc=True):
550
+ if key.path == ("compilerOptions",) and key.key in _TS_FLAGS:
551
+ lines[key.key] = key.line
552
+ for flag in _TS_FLAGS:
553
+ if _get(data, "compilerOptions", flag) is False and (
554
+ _get(old_data, "compilerOptions", flag) is not False
555
+ ):
556
+ yield from _hit_at(ctx, lines.get(flag), f"TypeScript {flag} turned off")
557
+
558
+
559
+ def _ruff_ignores(data: object, top_level: bool) -> tuple[set[str], set[tuple[str, str]]]:
560
+ tables = [_get(data, "tool", "ruff"), _get(data, "tool", "ruff", "lint")]
561
+ if top_level:
562
+ tables += [data, _get(data, "lint")]
563
+ codes: set[str] = set()
564
+ pairs: set[tuple[str, str]] = set()
565
+ for table in tables:
566
+ if not isinstance(table, dict):
567
+ continue
568
+ for key in ("ignore", "extend-ignore"):
569
+ value = table.get(key)
570
+ if isinstance(value, list):
571
+ codes.update(v for v in value if isinstance(v, str))
572
+ for key in ("per-file-ignores", "extend-per-file-ignores"):
573
+ value = table.get(key)
574
+ if isinstance(value, dict):
575
+ for pattern, items in value.items():
576
+ if isinstance(items, list):
577
+ pairs.update((pattern, v) for v in items if isinstance(v, str))
578
+ return codes, pairs
579
+
580
+
581
+ def _mypy_toml(data: object) -> set[str]:
582
+ mypy = _get(data, "tool", "mypy")
583
+ found: set[str] = set()
584
+ if not isinstance(mypy, dict):
585
+ return found
586
+ if mypy.get("ignore_errors") is True:
587
+ found.add("*")
588
+ overrides = mypy.get("overrides")
589
+ if isinstance(overrides, list):
590
+ for item in overrides:
591
+ if isinstance(item, dict) and item.get("ignore_errors") is True:
592
+ modules = item.get("module")
593
+ names = modules if isinstance(modules, list) else [modules]
594
+ found.update(str(m) for m in names)
595
+ return found
596
+
597
+
598
+ def _toml_weakened(ctx: FileContext) -> Iterator[Hit]:
599
+ data = ctx.toml
600
+ if data is None:
601
+ return
602
+ old: object = ctx.old_toml if ctx.old_text is not None else {}
603
+ if old is None:
604
+ return # the old side did not parse: nothing to compare with
605
+ name = _basename(ctx.path)
606
+ top = name != "pyproject.toml"
607
+ codes, pairs = _ruff_ignores(data, top)
608
+ old_codes, old_pairs = _ruff_ignores(old, top)
609
+ by_line: dict[int, list[str]] = {}
610
+ for code in sorted((codes - old_codes) | {c for _, c in pairs - old_pairs}):
611
+ line = _added_line_with(ctx, (f'"{code}"', f"'{code}'"))
612
+ by_line.setdefault(line or 0, []).append(code)
613
+ for line, found in sorted(by_line.items()):
614
+ yield from _hit_at(ctx, line, "ruff now ignores " + ", ".join(found[:10]))
615
+ if name == "pyproject.toml":
616
+ added = _mypy_toml(data) - _mypy_toml(old)
617
+ if added:
618
+ line = _added_line_with(ctx, ("ignore_errors",))
619
+ message = "mypy ignore_errors turned on for " + ", ".join(sorted(added)[:10])
620
+ yield from _hit_at(ctx, line, message)
621
+
622
+
623
+ def _ini_ignores(text: str | None) -> dict[str, int]:
624
+ """``{mypy section: line}`` of the sections whose ``ignore_errors`` is true."""
625
+ found: dict[str, int] = {}
626
+ section = ""
627
+ for number, line in enumerate(git_lines(text), start=1):
628
+ m = _INI_SECTION.match(line)
629
+ if m:
630
+ section = m.group(1).strip()
631
+ continue
632
+ m = _INI_IGNORE.match(line)
633
+ if m and section.startswith("mypy") and m.group(1).lower() in _TRUE:
634
+ found[section] = number
635
+ return found
636
+
637
+
638
+ def _eslint_off(data: object) -> set[str]:
639
+ found: set[str] = set()
640
+ blocks: list[object] = [data]
641
+ overrides = _get(data, "overrides")
642
+ if isinstance(overrides, list):
643
+ blocks.extend(overrides)
644
+ for block in blocks:
645
+ rules = _get(block, "rules")
646
+ if not isinstance(rules, dict):
647
+ continue
648
+ for name, value in rules.items():
649
+ level = value[0] if isinstance(value, list) and value else value
650
+ if level in ("off", 0, "0") and not isinstance(level, bool):
651
+ found.add(str(name))
652
+ return found
653
+
654
+
655
+ def _eslint_data(path: str, text: str | None) -> object:
656
+ if not text:
657
+ return None
658
+ if not path.endswith((".yml", ".yaml")):
659
+ data, error = parse_json(text, jsonc=True)
660
+ if error is None:
661
+ return data
662
+ if path.endswith(".json"):
663
+ return None
664
+ result = yamlish.parse(text.removeprefix(""))
665
+ if result.errors or not result.documents:
666
+ return None
667
+ return yamlish.to_python(result.documents[0].root)
668
+
669
+
670
+ def _eslint_code_off(lines: tuple[str, ...], masked: tuple[str, ...]) -> set[str]:
671
+ found: set[str] = set()
672
+ for i, line in enumerate(lines):
673
+ code = masked[i] if i < len(masked) else ""
674
+ for m in _ESLINT_OFF.finditer(line[:4000]):
675
+ if code[m.start() : m.end()].strip(): # blank in masked text: a comment
676
+ found.add(m.group("name"))
677
+ return found
678
+
679
+
680
+ def _eslint_weakened(ctx: FileContext, *, code: bool) -> Iterator[Hit]:
681
+ if code:
682
+ masked = git_lines(ctx.masked_code)
683
+ old_off: set[str] = set()
684
+ if ctx.old_text:
685
+ old_spans = lexers.lex(ctx.old_text, ctx.language, path=ctx.old_path or ctx.path)
686
+ old_masked = git_lines(lexers.mask(ctx.old_text, old_spans))
687
+ old_off = _eslint_code_off(ctx.old_lines, old_masked)
688
+ for number in sorted(ctx.added_lines):
689
+ if number > len(ctx.lines) or number > len(masked):
690
+ continue
691
+ line = (ctx.lines[number - 1],)
692
+ for name in sorted(_eslint_code_off(line, (masked[number - 1],)) - old_off):
693
+ yield Hit(number, message=f"ESLint rule {name} turned off")
694
+ return
695
+ new = _eslint_data(ctx.path, ctx.new_text)
696
+ if new is None:
697
+ return
698
+ old = _eslint_data(ctx.old_path or ctx.path, ctx.old_text)
699
+ if ctx.old_text and old is None:
700
+ return # the old side did not parse: nothing to compare with
701
+ for name in sorted(_eslint_off(new) - _eslint_off(old)):
702
+ line = _added_line_with(ctx, (f'"{name}"', f"'{name}'", f"{name}:"))
703
+ yield from _hit_at(ctx, line, f"ESLint rule {name} turned off")
704
+
705
+
706
+ @rule(
707
+ id="hygiene/quality-gate-weakened",
708
+ severity="warning",
709
+ title="Lint or type check weakened",
710
+ scope="file",
711
+ rationale=(
712
+ "Turning off strict type checking, ignoring lint codes or switching rules off lets a "
713
+ "whole class of defects through for every later change, not just this one."
714
+ ),
715
+ hint="Fix the findings instead, or scope the exception to the lines or files that need it.",
716
+ tags={"hygiene", "suppression"},
717
+ )
718
+ def quality_gate_weakened(ctx: FileContext) -> Iterator[Hit]:
719
+ """A lint or type gate is switched off or widened by the change.
720
+
721
+ - ``tsconfig*.json``: ``strict``, ``noImplicitAny`` or ``strictNullChecks``
722
+ set to ``false`` (and not ``false`` before).
723
+ - ruff (``pyproject.toml``, ``ruff.toml``, ``.ruff.toml``): a code new in
724
+ ``ignore``/``extend-ignore`` or in ``per-file-ignores``.
725
+ - ESLint (``.eslintrc*``, ``eslint.config.*``): a rule newly set to
726
+ ``"off"`` or ``0``.
727
+ - mypy (``mypy.ini``, ``.mypy.ini``, ``setup.cfg``, ``pyproject.toml``):
728
+ ``ignore_errors`` newly true, globally or for a module.
729
+ """
730
+ if ctx.new_text is None or (not ctx.added_lines and not ctx.deletion_points):
731
+ return
732
+ name = _basename(ctx.path)
733
+ if _TSCONFIG.fullmatch(name):
734
+ yield from _ts_weakened(ctx)
735
+ elif name in _RUFF_FILES:
736
+ yield from _toml_weakened(ctx)
737
+ elif name in _ESLINT_DATA or _ESLINT_CODE.fullmatch(name):
738
+ yield from _eslint_weakened(ctx, code=bool(_ESLINT_CODE.fullmatch(name)))
739
+ elif name in _MYPY_INI:
740
+ old = _ini_ignores(ctx.old_text)
741
+ for section, line in sorted(_ini_ignores(ctx.new_text).items()):
742
+ if section not in old:
743
+ yield Hit(line, message=f"mypy ignore_errors turned on in [{section}]")
744
+
745
+
746
+ # --- Generated and minified files ----------------------------------------------------------
747
+
748
+ _GENERATED_MARKER = re.compile(r"(?<![\w-])@generated\b|\bDO NOT EDIT\b")
749
+
750
+
751
+ @rule(
752
+ id="hygiene/generated-file-edited",
753
+ severity="warning",
754
+ title="Generated file edited",
755
+ classes=_ALL_CLASSES - {"vendored"},
756
+ scope="file",
757
+ rationale=(
758
+ "Generated files are overwritten the next time the generator runs, so a hand edit "
759
+ "is lost; and a file that declares itself generated tends to be skipped in review."
760
+ ),
761
+ hint=(
762
+ "Change the generator or its input and regenerate; list generated paths in the "
763
+ "trusted config."
764
+ ),
765
+ tags={"hygiene", "generated"},
766
+ )
767
+ def generated_file_edited(ctx: FileContext) -> Iterator[Hit]:
768
+ """An edit to a ``generated``-class file, or an ``@generated``/``DO NOT EDIT`` marker added.
769
+
770
+ The marker counts in a comment on an added line of a file whose old side
771
+ had no marker (new files included). Adding a whole generated-class file
772
+ is not an edit. Vendored code is left alone.
773
+ """
774
+ if ctx.new_text is None:
775
+ return
776
+ if ctx.file_class == "generated":
777
+ if ctx.change.status is not FileStatus.ADDED and (ctx.added_lines or ctx.deletion_points):
778
+ hit = _whole_file(ctx, "Generated file edited by hand")
779
+ if hit is not None:
780
+ yield hit
781
+ return
782
+ if ctx.old_text and _GENERATED_MARKER.search(ctx.old_text):
783
+ return
784
+ for _, number, part in _comment_lines(ctx):
785
+ if number in ctx.added_lines and _GENERATED_MARKER.search(part[:4000]):
786
+ yield Hit(number, message="File marked as generated")
787
+ return
788
+
789
+
790
+ _MINIFIED_SUFFIXES = (".min.js", ".min.mjs", ".min.cjs", ".min.css")
791
+ _MINIFIED_LINE = 2000
792
+
793
+
794
+ def _looks_minified(ctx: FileContext) -> bool:
795
+ lines = ctx.lines
796
+ for number in ctx.added_lines:
797
+ if number <= len(lines) and len(lines[number - 1]) > _MINIFIED_LINE:
798
+ sample = lines[number - 1][:20000]
799
+ spaces = sample.count(" ") + sample.count("\t")
800
+ if spaces * 20 < len(sample):
801
+ return True
802
+ return False
803
+
804
+
805
+ @rule(
806
+ id="hygiene/minified-file",
807
+ severity="warning",
808
+ title="Minified file changed",
809
+ classes={"minified", "source", "text"},
810
+ scope="file",
811
+ rationale=(
812
+ "Minified code cannot be reviewed: what it does, and whether it matches its source, "
813
+ "is hidden in long unreadable lines."
814
+ ),
815
+ hint="Commit the source and build the minified file in CI, or vendor a pinned release.",
816
+ tags={"hygiene", "generated"},
817
+ )
818
+ def minified_file(ctx: FileContext) -> Iterator[Hit]:
819
+ """A ``*.min.js``/``*.min.css`` file added or changed, or JavaScript that looks minified.
820
+
821
+ Looks minified: an added line over 2,000 characters of which under 5%
822
+ are spaces or tabs.
823
+ """
824
+ if ctx.new_text is None or (not ctx.added_lines and not ctx.deletion_points):
825
+ return
826
+ if ctx.file_class == "minified" or ctx.path.endswith(_MINIFIED_SUFFIXES):
827
+ message = "Minified file changed"
828
+ elif ctx.language == "javascript" and ctx.file_class == "source" and _looks_minified(ctx):
829
+ message = "Code looks minified"
830
+ else:
831
+ return
832
+ hit = _whole_file(ctx, message)
833
+ if hit is not None:
834
+ yield hit
835
+
836
+
837
+ # --- Binary files --------------------------------------------------------------------------
838
+
839
+ _NATIVE = frozenset({".so", ".dylib", ".dll", ".exe", ".wasm", ".o", ".a"})
840
+ _ARCHIVE = frozenset({".zip", ".jar", ".whl", ".tar", ".gz", ".tgz", ".7z", ".rar", ".xz", ".zst"})
841
+ _VERSIONED_SO = re.compile(r".{1,200}\.so(?:\.\d{1,6}){1,4}")
842
+
843
+
844
+ def _binary_tier(ctx: FileContext) -> tuple[Severity, str] | None:
845
+ if ctx.kind is FileKind.LFS_POINTER:
846
+ return Severity.NOTE, "Content stored in Git LFS was not reviewed"
847
+ name = _basename(ctx.path)
848
+ ext = _extension(name)
849
+ if ctx.change.new_mode == _EXECUTABLE or ext in _NATIVE or _VERSIONED_SO.fullmatch(name):
850
+ return Severity.ERROR, "Native executable or library was not reviewed"
851
+ if ext in _ARCHIVE:
852
+ return Severity.WARNING, "Archive was not reviewed"
853
+ if FLAG_MODE_CHANGE not in ctx.flags and any(
854
+ f.startswith(FLAG_IMAGE_PREFIX) for f in ctx.flags
855
+ ):
856
+ return None # an image intake recognized: benign
857
+ return Severity.NOTE, "Binary file was not reviewed"
858
+
859
+
860
+ @rule(
861
+ id="hygiene/binary-file",
862
+ severity="error",
863
+ title="Binary file added or changed",
864
+ classes=_ALL_CLASSES,
865
+ scope="file",
866
+ kinds=(FileKind.BINARY, FileKind.LFS_POINTER),
867
+ rationale=(
868
+ "Binary content cannot be reviewed as text. Native executables and libraries run "
869
+ "with the project's privileges and are the classic place to hide a backdoor; "
870
+ "archives hide arbitrary files."
871
+ ),
872
+ hint=(
873
+ "Build binaries from source in CI or download them pinned by checksum; keep "
874
+ "archives out of the repository."
875
+ ),
876
+ tags={"hygiene", "supply-chain"},
877
+ )
878
+ def binary_file(ctx: FileContext) -> Iterator[Hit]:
879
+ """A binary or Git LFS pointer added, changed or moved with changes.
880
+
881
+ ``error`` for native code (the executable bit, ``.so``/``.dylib``/
882
+ ``.dll``/``.exe``/``.wasm``/``.o``/``.a``, versioned ``.so.N``),
883
+ ``warning`` for archives (``.zip``/``.jar``/``.whl``/``.tar``/``.gz``/
884
+ ``.tgz``/``.7z``/``.rar``/``.xz``/``.zst``), ``note`` for every other
885
+ binary and for LFS pointers. Images intake recognized (and that are not
886
+ executable) are benign and silent; so are deletions and pure renames.
887
+ Handling these kinds makes binaries count as reviewed, in every class.
888
+ """
889
+ change = ctx.change
890
+ if change.status is FileStatus.DELETED:
891
+ return
892
+ if (
893
+ change.status is FileStatus.RENAMED
894
+ and change.similarity == 100
895
+ and change.old_mode == change.new_mode
896
+ ):
897
+ return
898
+ tier = _binary_tier(ctx)
899
+ if tier is not None:
900
+ severity, message = tier
901
+ yield Hit(None, message=message, severity=None if severity is Severity.ERROR else severity)
902
+
903
+
904
+ # --- TODOs and commented-out code ----------------------------------------------------------
905
+
906
+ _TODO = re.compile(r"(?<![\w-])(?:TODO|FIXME|XXX|HACK)(?![\w-])")
907
+
908
+
909
+ @rule(
910
+ id="hygiene/todo-added",
911
+ severity="note",
912
+ title="TODO added",
913
+ scope="line",
914
+ rationale="A new TODO or FIXME marks work the change leaves unfinished.",
915
+ hint="Finish it, or link the TODO to a tracked issue.",
916
+ tags={"hygiene"},
917
+ )
918
+ def todo_added(ctx: FileContext) -> Iterator[Hit]:
919
+ """A ``TODO``, ``FIXME``, ``XXX`` or ``HACK`` word in a comment on a changed line."""
920
+ if not ctx.added_lines:
921
+ return
922
+ for _, number, part in _comment_lines(ctx):
923
+ if number not in ctx.added_lines:
924
+ continue
925
+ m = _TODO.search(part[:4000])
926
+ if m:
927
+ yield Hit(number, evidence=" ".join(part[m.start() : m.start() + 200].split()))
928
+
929
+
930
+ _CODE_COMMENT_LANGUAGES = frozenset(
931
+ {"python", "javascript", "typescript", "go", "rust", "java", "kotlin"}
932
+ )
933
+ _C_HARD_END = (";", "{", "}")
934
+ _C_SOFT_END = (")", ",", "(", "[", "]", "=>", "&&", "||")
935
+ _C_KEYWORD = re.compile(
936
+ r"(?:return|if|for|while|else|var|let|const|val|func|fn|defer|break|continue|throw)\b"
937
+ )
938
+ _PROSE = re.compile(r"[A-Za-z]{2,40}(?: [A-Za-z]{2,40}){4}")
939
+ _RUN_LIMIT = 64
940
+
941
+
942
+ def _line_comment_runs(ctx: FileContext) -> Iterator[list[tuple[int, str]]]:
943
+ """Runs of three or more consecutive whole-line line comments: ``(line, content)``."""
944
+ text = ctx.new_text or ""
945
+ index = ctx.line_index
946
+ run: list[tuple[int, str]] = []
947
+ for span in ctx.comments():
948
+ if span.kind != "line":
949
+ continue
950
+ line = index.line_of(span.start)
951
+ if text[index.line_start(line) : span.start].strip():
952
+ continue # code before the comment on its line
953
+ if run and (run[-1][0] != line - 1 or len(run) >= _RUN_LIMIT):
954
+ if len(run) >= 3:
955
+ yield run
956
+ run = []
957
+ content = text[span.content_start : span.content_end]
958
+ run.append((line, content.removeprefix(" ")))
959
+ if len(run) >= 3:
960
+ yield run
961
+
962
+
963
+ def _python_code(body: str) -> bool:
964
+ try:
965
+ with warnings.catch_warnings():
966
+ warnings.simplefilter("ignore")
967
+ tree = ast.parse(textwrap.dedent(body))
968
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
969
+ return False
970
+ if not tree.body:
971
+ return False
972
+ for node in tree.body:
973
+ if isinstance(node, ast.Expr) and isinstance(node.value, (ast.Name, ast.Constant)):
974
+ return False
975
+ if isinstance(node, ast.AnnAssign) and node.value is None:
976
+ return False
977
+ return True
978
+
979
+
980
+ def _c_code(lines: list[str]) -> bool:
981
+ hard = False
982
+ for raw in lines:
983
+ line = raw.strip()
984
+ if not line:
985
+ continue
986
+ if _PROSE.search(line) or ". " in line:
987
+ return False
988
+ if line.endswith(_C_HARD_END) or line.startswith("}"):
989
+ hard = True
990
+ elif not (
991
+ (line.endswith(_C_SOFT_END) and "(" in line) or " = " in line or _C_KEYWORD.match(line)
992
+ ):
993
+ return False
994
+ return hard
995
+
996
+
997
+ _TRIM = 3
998
+ """Prose lines at either end of a run that are tried without (a heading, a TODO)."""
999
+
1000
+
1001
+ def _code_window(contents: list[str], python: bool) -> tuple[int, int] | None:
1002
+ """The widest ``[lo, hi)`` slice of three or more lines that reads as code."""
1003
+ size = len(contents)
1004
+ for trim in range(min(2 * _TRIM, size - 3) + 1):
1005
+ for lo in range(min(trim, _TRIM) + 1):
1006
+ hi = size - (trim - lo)
1007
+ if trim - lo > _TRIM or hi - lo < 3:
1008
+ continue
1009
+ part = contents[lo:hi]
1010
+ if _python_code("\n".join(part)) if python else _c_code(part):
1011
+ return lo, hi
1012
+ return None
1013
+
1014
+
1015
+ @rule(
1016
+ id="hygiene/commented-out-code",
1017
+ severity="note",
1018
+ title="Commented-out code added",
1019
+ languages=_CODE_COMMENT_LANGUAGES,
1020
+ scope="line",
1021
+ rationale=(
1022
+ "Commented-out code rots: nobody knows whether it should come back, and version "
1023
+ "control already keeps the old code."
1024
+ ),
1025
+ hint="Delete it; Git history keeps it if it is ever needed again.",
1026
+ tags={"hygiene"},
1027
+ )
1028
+ def commented_out_code(ctx: FileContext) -> Iterator[Hit]:
1029
+ """Three or more consecutive whole-line comments that read as code.
1030
+
1031
+ Python: the uncommented lines parse as statements (not bare names,
1032
+ constants or ``Name: text`` annotations, which prose produces). C family:
1033
+ every line ends like a statement, holds an assignment or starts with a
1034
+ keyword such as ``return``, at least one ends with ``;``, ``{`` or ``}``,
1035
+ and none reads as a sentence. Up to three prose lines at either end of a
1036
+ run (a heading, a TODO) are left out of it. Doc comments (``///``,
1037
+ ``/** */``), doctests and fenced examples never count.
1038
+ """
1039
+ if not ctx.added_lines:
1040
+ return
1041
+ python = ctx.language == "python"
1042
+ for run in _line_comment_runs(ctx):
1043
+ numbers = [n for n, _ in run]
1044
+ if not any(n in ctx.added_lines for n in numbers):
1045
+ continue
1046
+ contents = [c for _, c in run]
1047
+ if any(c.lstrip().startswith((">>>", "```", "/", "!")) for c in contents):
1048
+ continue
1049
+ found = _code_window(contents, python)
1050
+ if found is not None:
1051
+ lo, hi = found
1052
+ if any(n in ctx.added_lines for n in numbers[lo:hi]):
1053
+ evidence = " ".join(" ".join(contents[lo:hi]).split())[:300]
1054
+ yield Hit(numbers[lo], end_line=numbers[hi - 1], evidence=evidence)
1055
+
1056
+
1057
+ # --- Executable bit ------------------------------------------------------------------------
1058
+
1059
+ _SCRIPT_EXTENSIONS = frozenset(
1060
+ {
1061
+ ".sh", ".bash", ".zsh", ".ksh", ".fish", ".bats", ".command", ".py", ".pyw", ".pl",
1062
+ ".pm", ".rb", ".php", ".js", ".mjs", ".cjs", ".ts", ".lua", ".tcl", ".ps1", ".awk",
1063
+ ".r", ".jl", ".groovy", ".swift", ".exs", ".escript", ".nu",
1064
+ }
1065
+ ) # fmt: skip
1066
+
1067
+
1068
+ @rule(
1069
+ id="hygiene/executable-bit",
1070
+ severity="note",
1071
+ title="Executable bit set on a non-script",
1072
+ scope="file",
1073
+ rationale=(
1074
+ "A file without a shebang that is not a script cannot be run directly; the "
1075
+ "executable bit is usually an accident (a copy from a FAT drive or a Windows tool)."
1076
+ ),
1077
+ hint="Remove it with git update-index --chmod=-x <path>, or add a shebang.",
1078
+ tags={"hygiene"},
1079
+ )
1080
+ def executable_bit(ctx: FileContext) -> Iterator[Hit]:
1081
+ """A text file's mode changed from 100644 to 100755, with no shebang and no script extension."""
1082
+ change = ctx.change
1083
+ if (
1084
+ FLAG_MODE_CHANGE not in ctx.flags
1085
+ or change.old_mode != _REGULAR
1086
+ or change.new_mode != _EXECUTABLE
1087
+ or ctx.new_text is None
1088
+ ):
1089
+ return
1090
+ if ctx.new_text.removeprefix("").startswith("#!"):
1091
+ return
1092
+ if _extension(_basename(ctx.path)) in _SCRIPT_EXTENSIONS:
1093
+ return
1094
+ yield Hit(None, message="Executable bit set on a file without a shebang")