Coverage for src/pullapprove/trust/comments.py: 99%
102 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-28 14:54 -0500
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-28 14:54 -0500
1"""Trust rule: hunks that only touch comments, plus the comment-syntax tables."""
3from __future__ import annotations
5from collections.abc import Callable
7from ..diff import DiffCode, DiffFile, DiffHunk
8from .delta import paired_changed_lines
9from .helpers import (
10 BLOCK_COMMENT_DELIMITERS,
11 LINE_COMMENT_PREFIXES,
12 change_suffix,
13 extension,
14 leading_indent,
15)
16from .labels import Trust
17from .linescan import consume_string
19# Languages whose strings can be backtick-delimited (JS/TS template literals, Go
20# raw strings) — without this a `//` inside one reads as a comment.
21_BACKTICK_LANGS = frozenset("js jsx ts tsx mjs mts cjs cts go".split())
23# Comments that DIRECT TOOLS rather than inform readers: linter suppressions,
24# type-checker escapes, formatter/coverage toggles, compiler and bundler pragmas.
25# Changing one changes how tools treat the surrounding code — a real edit, not
26# comment churn — so a changed comment containing any of these is never trusted.
27# Matched case-insensitively as substrings, deliberately loose: a prose comment
28# that merely *mentions* a marker declines too, which only costs coverage (the
29# hunk is shown), never hides a change. Start with the most common tools; extend
30# as they come up.
31_DIRECTIVE_MARKERS = (
32 # Python
33 "noqa", # flake8/ruff suppression
34 "pylint:", # pylint suppression/config
35 "nopep8", # pep8/autopep8 suppression
36 "skipcq", # DeepSource suppression
37 "type: ignore", # mypy/pyright escape
38 "pragma:", # coverage.py (pragma: no cover)
39 "doctest:", # doctest directive (e.g. doctest: +SKIP)
40 "fmt: off", # black/ruff formatter toggles
41 "fmt: on",
42 "fmt: skip",
43 "yapf:", # yapf formatter toggle
44 "ruff:",
45 "mypy:",
46 "pyright:",
47 "pyre-ignore", # Meta's Pyre type checker
48 "pyre-fixme",
49 "pytype:", # Google's pytype type checker
50 "isort:",
51 "nosec", # bandit
52 "coding:", # PEP 263 encoding declaration
53 "coding=",
54 # JS/TS
55 "eslint-", # eslint-disable / -enable / -disable-next-line / -disable-line
56 "@ts-", # @ts-ignore / @ts-expect-error / @ts-nocheck / @ts-check
57 "prettier-ignore",
58 "biome-ignore",
59 "istanbul ignore",
60 "c8 ignore",
61 "v8 ignore",
62 "sourcemappingurl", # //# sourceMappingURL=…
63 "webpackchunkname", # webpack magic comments
64 "webpackmode",
65 # Go
66 "go:build",
67 "go:generate",
68 "go:embed",
69 "+build",
70 "nolint", # golangci-lint; also covers clang-tidy's NOLINT
71 # Ruby
72 "rubocop:",
73 "frozen_string_literal",
74 "typed:", # sorbet
75 # Shell
76 "shellcheck",
77 # C/C++
78 "clang-format",
79)
82def _has_directive(text: str) -> bool:
83 lowered = text.lower()
84 return any(marker in lowered for marker in _DIRECTIVE_MARKERS)
87def _is_shebang(line: DiffCode) -> bool:
88 """A `#!` interpreter line at file line 1 — execution semantics, not a
89 comment (deeper in a file, `#!` is just comment text)."""
90 return line.content.startswith("#!") and 1 in (
91 line.old_line_number,
92 line.new_line_number,
93 )
96def _string_quotes(ext: str) -> str:
97 """The quote characters that open a string literal in this language."""
98 return "\"'`" if ext in _BACKTICK_LANGS else "\"'"
101def strip_inline_comment(
102 line: str, prefixes: tuple[str, ...], quotes: str = "\"'"
103) -> str:
104 """Drop a trailing line-comment, ignoring prefixes inside string literals.
106 A prefix only starts a comment at line-start or after whitespace — glued to a
107 preceding token it is part of a value, not a comment (YAML/shell treat it that
108 way, and a URL fragment `url: https://x/#frag` must not read as a `#` comment).
109 Requiring the space is conservative elsewhere too: it can only *miss* a
110 space-less comment like `x=1#c`, never hide a real change."""
111 text = line.strip()
112 i, n = 0, len(text)
113 while i < n:
114 if text[i] in quotes:
115 i = consume_string(text, i)
116 elif text.startswith(prefixes, i) and (i == 0 or text[i - 1].isspace()):
117 return text[:i].rstrip()
118 else:
119 i += 1
120 return text
123def _block_comment_step(
124 text: str, delimiters: tuple[str, str], in_block: bool
125) -> tuple[bool, bool]:
126 """Whether *all* of `text` is block comment, and the new in-block state.
128 Walks the line so that code trailing a closed comment (`/* note */ run()`)
129 is recognized as code, not swallowed by the comment.
130 """
131 open_, close = delimiters
132 text = text.strip()
133 while True:
134 if in_block:
135 end = text.find(close)
136 if end == -1:
137 return True, True # comment runs on to the next line
138 text = text[end + len(close) :].strip()
139 in_block = False
140 elif not text:
141 return True, False # nothing but comment(s) on this line
142 elif text.startswith(open_):
143 text = text[len(open_) :]
144 in_block = True
145 else:
146 return False, False # real code on this line
149def _all_comment_lines(
150 side_lines: list[DiffCode],
151 changed: Callable[[DiffCode], bool],
152 prefixes: tuple[str, ...] | None,
153 block: tuple[str, str] | None,
154) -> bool:
155 """True if every changed, non-blank line on this SIDE is a line or block
156 comment. `side_lines` is the hunk's full line sequence for one side of the
157 file (context + this side's changes, in order), so block-comment state is
158 tracked across the lines the way the file actually reads.
160 A block comment opened on a changed line must close before the next context
161 line: if it's still open there, the unchanged code on that context line is
162 now INSIDE the comment — code commented out is a semantic change, not
163 comment churn. The same reasoning closes the bottom of the hunk (`in_block`
164 at the end would swallow code below).
166 KNOWN LIMITATION (shared with `_whitespace`): a comment-prefix line that is
167 actually *inside* a multi-line string literal (a JS template literal, a Python
168 triple-quoted string) reads as a comment here, so editing it can be hidden as
169 a comment change though the string's value changed. The opening delimiter is
170 usually above the hunk, out of view, so we can't detect it from a single hunk;
171 this rare case is accepted rather than guarded with an unreliable heuristic."""
172 in_block = False
173 for line in side_lines:
174 if not changed(line):
175 if in_block:
176 return False # a changed `/*` swallows this unchanged code
177 continue
178 text = line.content.strip()
179 if not text:
180 continue
181 if not in_block and prefixes and text.startswith(prefixes):
182 continue
183 if block:
184 is_comment, in_block = _block_comment_step(text, block, in_block)
185 if is_comment:
186 continue
187 return False
188 return not in_block
191def _inline_comment_change(
192 hunk: DiffHunk, prefixes: tuple[str, ...], quotes: str
193) -> Trust | None:
194 """Label hunks where paired lines differ only in their inline comments."""
195 # The positional pairing gate is shared with the token-delta rules
196 # (delta.paired_changed_lines); this rule then compares raw strings, not
197 # tokens — comments span ~40 languages the tokenizer doesn't model.
198 pairs = paired_changed_lines(hunk)
199 if pairs is None:
200 return None
201 old_has_comment = new_has_comment = False
202 for old, new in pairs:
203 old_code = strip_inline_comment(old.content, prefixes, quotes)
204 new_code = strip_inline_comment(new.content, prefixes, quotes)
205 # Compare with leading indentation (semantic in Python), so a re-indent of
206 # a commented line isn't mistaken for an unchanged-code, comment-only edit.
207 if (
208 not old_code
209 or leading_indent(old.content) + old_code
210 != leading_indent(new.content) + new_code
211 ):
212 return None # the code (or its indentation) changed, not just a comment
213 # The comment remainders (whatever strip_inline_comment dropped). A tool
214 # directive in either one (noqa, eslint-disable, …) means tool behavior
215 # changed, not prose — never trust it.
216 old_comment = old.content.strip()[len(old_code) :]
217 new_comment = new.content.strip()[len(new_code) :]
218 if _has_directive(old_comment) or _has_directive(new_comment):
219 return None
220 old_has_comment = old_has_comment or bool(old_comment)
221 new_has_comment = new_has_comment or bool(new_comment)
222 if new_has_comment and old_has_comment:
223 return Trust.COMMENTS_MODIFIED
224 if new_has_comment:
225 return Trust.COMMENTS_ADDED
226 if old_has_comment:
227 return Trust.COMMENTS_REMOVED
228 return None
231def _comments(file: DiffFile, hunk: DiffHunk) -> Trust | None:
232 ext = extension(file)
233 prefixes = LINE_COMMENT_PREFIXES.get(ext)
234 block = BLOCK_COMMENT_DELIMITERS.get(ext)
235 if not prefixes and not block:
236 return None
237 if not hunk.changed_lines:
238 return None
239 # A shebang selects the interpreter the file runs under — changing it is an
240 # execution change that happens to be spelled in comment syntax.
241 if any(_is_shebang(line) for line in hunk.changed_lines):
242 return None
243 # Each side reads as its own file (context + that side's changes, in order),
244 # so block-comment state threads through context lines correctly.
245 new_side = [line for line in hunk.lines if not line.is_deletion()]
246 old_side = [line for line in hunk.lines if not line.is_addition()]
247 if _all_comment_lines(
248 new_side, DiffCode.is_addition, prefixes, block
249 ) and _all_comment_lines(old_side, DiffCode.is_deletion, prefixes, block):
250 # Every changed line is a comment, so scan them whole for tool directives.
251 if any(_has_directive(line.content) for line in hunk.changed_lines):
252 return None
253 # change_suffix yields added/removed/modified — each a real Trust member.
254 return Trust(f"comments:{change_suffix(hunk)}")
255 # Fallback: paired lines whose only difference is a trailing inline comment.
256 if prefixes:
257 return _inline_comment_change(hunk, prefixes, _string_quotes(ext))
258 return None