Coverage for src/pullapprove/trust/comments.py: 99%
102 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-01 17:47 -0500
« prev ^ index » next coverage.py v7.14.1, created at 2026-07-01 17:47 -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 "type: ignore", # mypy/pyright escape
35 "pragma:", # coverage.py (pragma: no cover)
36 "fmt: off", # black/ruff formatter toggles
37 "fmt: on",
38 "fmt: skip",
39 "ruff:",
40 "mypy:",
41 "pyright:",
42 "isort:",
43 "nosec", # bandit
44 "coding:", # PEP 263 encoding declaration
45 "coding=",
46 # JS/TS
47 "eslint-", # eslint-disable / -enable / -disable-next-line / -disable-line
48 "@ts-", # @ts-ignore / @ts-expect-error / @ts-nocheck / @ts-check
49 "prettier-ignore",
50 "biome-ignore",
51 "istanbul ignore",
52 "c8 ignore",
53 "v8 ignore",
54 "sourcemappingurl", # //# sourceMappingURL=…
55 "webpackchunkname", # webpack magic comments
56 "webpackmode",
57 # Go
58 "go:build",
59 "go:generate",
60 "go:embed",
61 "+build",
62 "nolint", # golangci-lint; also covers clang-tidy's NOLINT
63 # Ruby
64 "rubocop:",
65 "frozen_string_literal",
66 "typed:", # sorbet
67 # Shell
68 "shellcheck",
69 # C/C++
70 "clang-format",
71)
74def _has_directive(text: str) -> bool:
75 lowered = text.lower()
76 return any(marker in lowered for marker in _DIRECTIVE_MARKERS)
79def _is_shebang(line: DiffCode) -> bool:
80 """A `#!` interpreter line at file line 1 — execution semantics, not a
81 comment (deeper in a file, `#!` is just comment text)."""
82 return line.content.startswith("#!") and 1 in (
83 line.old_line_number,
84 line.new_line_number,
85 )
88def _string_quotes(ext: str) -> str:
89 """The quote characters that open a string literal in this language."""
90 return "\"'`" if ext in _BACKTICK_LANGS else "\"'"
93def strip_inline_comment(
94 line: str, prefixes: tuple[str, ...], quotes: str = "\"'"
95) -> str:
96 """Drop a trailing line-comment, ignoring prefixes inside string literals.
98 A prefix only starts a comment at line-start or after whitespace — glued to a
99 preceding token it is part of a value, not a comment (YAML/shell treat it that
100 way, and a URL fragment `url: https://x/#frag` must not read as a `#` comment).
101 Requiring the space is conservative elsewhere too: it can only *miss* a
102 space-less comment like `x=1#c`, never hide a real change."""
103 text = line.strip()
104 i, n = 0, len(text)
105 while i < n:
106 if text[i] in quotes:
107 i = consume_string(text, i)
108 elif text.startswith(prefixes, i) and (i == 0 or text[i - 1].isspace()):
109 return text[:i].rstrip()
110 else:
111 i += 1
112 return text
115def _block_comment_step(
116 text: str, delimiters: tuple[str, str], in_block: bool
117) -> tuple[bool, bool]:
118 """Whether *all* of `text` is block comment, and the new in-block state.
120 Walks the line so that code trailing a closed comment (`/* note */ run()`)
121 is recognized as code, not swallowed by the comment.
122 """
123 open_, close = delimiters
124 text = text.strip()
125 while True:
126 if in_block:
127 end = text.find(close)
128 if end == -1:
129 return True, True # comment runs on to the next line
130 text = text[end + len(close) :].strip()
131 in_block = False
132 elif not text:
133 return True, False # nothing but comment(s) on this line
134 elif text.startswith(open_):
135 text = text[len(open_) :]
136 in_block = True
137 else:
138 return False, False # real code on this line
141def _all_comment_lines(
142 side_lines: list[DiffCode],
143 changed: Callable[[DiffCode], bool],
144 prefixes: tuple[str, ...] | None,
145 block: tuple[str, str] | None,
146) -> bool:
147 """True if every changed, non-blank line on this SIDE is a line or block
148 comment. `side_lines` is the hunk's full line sequence for one side of the
149 file (context + this side's changes, in order), so block-comment state is
150 tracked across the lines the way the file actually reads.
152 A block comment opened on a changed line must close before the next context
153 line: if it's still open there, the unchanged code on that context line is
154 now INSIDE the comment — code commented out is a semantic change, not
155 comment churn. The same reasoning closes the bottom of the hunk (`in_block`
156 at the end would swallow code below).
158 KNOWN LIMITATION (shared with `_whitespace`): a comment-prefix line that is
159 actually *inside* a multi-line string literal (a JS template literal, a Python
160 triple-quoted string) reads as a comment here, so editing it can be hidden as
161 a comment change though the string's value changed. The opening delimiter is
162 usually above the hunk, out of view, so we can't detect it from a single hunk;
163 this rare case is accepted rather than guarded with an unreliable heuristic."""
164 in_block = False
165 for line in side_lines:
166 if not changed(line):
167 if in_block:
168 return False # a changed `/*` swallows this unchanged code
169 continue
170 text = line.content.strip()
171 if not text:
172 continue
173 if not in_block and prefixes and text.startswith(prefixes):
174 continue
175 if block:
176 is_comment, in_block = _block_comment_step(text, block, in_block)
177 if is_comment:
178 continue
179 return False
180 return not in_block
183def _inline_comment_change(
184 hunk: DiffHunk, prefixes: tuple[str, ...], quotes: str
185) -> Trust | None:
186 """Label hunks where paired lines differ only in their inline comments."""
187 # The positional pairing gate is shared with the token-delta rules
188 # (delta.paired_changed_lines); this rule then compares raw strings, not
189 # tokens — comments span ~40 languages the tokenizer doesn't model.
190 pairs = paired_changed_lines(hunk)
191 if pairs is None:
192 return None
193 old_has_comment = new_has_comment = False
194 for old, new in pairs:
195 old_code = strip_inline_comment(old.content, prefixes, quotes)
196 new_code = strip_inline_comment(new.content, prefixes, quotes)
197 # Compare with leading indentation (semantic in Python), so a re-indent of
198 # a commented line isn't mistaken for an unchanged-code, comment-only edit.
199 if (
200 not old_code
201 or leading_indent(old.content) + old_code
202 != leading_indent(new.content) + new_code
203 ):
204 return None # the code (or its indentation) changed, not just a comment
205 # The comment remainders (whatever strip_inline_comment dropped). A tool
206 # directive in either one (noqa, eslint-disable, …) means tool behavior
207 # changed, not prose — never trust it.
208 old_comment = old.content.strip()[len(old_code) :]
209 new_comment = new.content.strip()[len(new_code) :]
210 if _has_directive(old_comment) or _has_directive(new_comment):
211 return None
212 old_has_comment = old_has_comment or bool(old_comment)
213 new_has_comment = new_has_comment or bool(new_comment)
214 if new_has_comment and old_has_comment:
215 return Trust.COMMENTS_MODIFIED
216 if new_has_comment:
217 return Trust.COMMENTS_ADDED
218 if old_has_comment:
219 return Trust.COMMENTS_REMOVED
220 return None
223def _comments(file: DiffFile, hunk: DiffHunk) -> Trust | None:
224 ext = extension(file)
225 prefixes = LINE_COMMENT_PREFIXES.get(ext)
226 block = BLOCK_COMMENT_DELIMITERS.get(ext)
227 if not prefixes and not block:
228 return None
229 if not hunk.changed_lines:
230 return None
231 # A shebang selects the interpreter the file runs under — changing it is an
232 # execution change that happens to be spelled in comment syntax.
233 if any(_is_shebang(line) for line in hunk.changed_lines):
234 return None
235 # Each side reads as its own file (context + that side's changes, in order),
236 # so block-comment state threads through context lines correctly.
237 new_side = [line for line in hunk.lines if not line.is_deletion()]
238 old_side = [line for line in hunk.lines if not line.is_addition()]
239 if _all_comment_lines(
240 new_side, DiffCode.is_addition, prefixes, block
241 ) and _all_comment_lines(old_side, DiffCode.is_deletion, prefixes, block):
242 # Every changed line is a comment, so scan them whole for tool directives.
243 if any(_has_directive(line.content) for line in hunk.changed_lines):
244 return None
245 # change_suffix yields added/removed/modified — each a real Trust member.
246 return Trust(f"comments:{change_suffix(hunk)}")
247 # Fallback: paired lines whose only difference is a trailing inline comment.
248 if prefixes:
249 return _inline_comment_change(hunk, prefixes, _string_quotes(ext))
250 return None