patchpilot-mcp 0.4.1__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.
patchpilot/diff.py ADDED
@@ -0,0 +1,581 @@
1
+ """Bounded unified diff parsing and review."""
2
+
3
+ import re
4
+ from dataclasses import dataclass, field
5
+ from .common import (
6
+ MAX_FILES,
7
+ MAX_FINDINGS,
8
+ MAX_LINES,
9
+ InputError,
10
+ bounded,
11
+ finding,
12
+ no_input,
13
+ )
14
+
15
+ HUNK = re.compile(r"^@@ -(\d{1,9})(?:,(\d{1,9}))? \+(\d{1,9})(?:,(\d{1,9}))? @@(?:.*)$")
16
+
17
+
18
+ @dataclass
19
+ class ChangedFile:
20
+ old: str
21
+ new: str
22
+ added: int = 0
23
+ removed: int = 0
24
+ hunks: int = 0
25
+ added_lines: list[int] = field(default_factory=list)
26
+ removed_lines: list[int] = field(default_factory=list)
27
+ old_context: list[tuple[int, str]] = field(default_factory=list)
28
+ new_context: list[tuple[int, str]] = field(default_factory=list)
29
+ old_ranges: list[tuple[int, int]] = field(default_factory=list)
30
+ new_ranges: list[tuple[int, int]] = field(default_factory=list)
31
+ old_eof: int | None = None
32
+ new_eof: int | None = None
33
+ old_end: int = -1
34
+ new_end: int = -1
35
+ old_mode: str | None = None
36
+ new_mode: str | None = None
37
+ renamed: bool = False
38
+ rename_from: str | None = None
39
+ rename_to: str | None = None
40
+ header_seen: bool = False
41
+ git_header: bool = False
42
+ new_file: bool = False
43
+ deleted_file: bool = False
44
+
45
+ @property
46
+ def change_kind(self):
47
+ if self.renamed:
48
+ return "renamed"
49
+ if self.old == "/dev/null" or self.new_file:
50
+ return "added"
51
+ if self.new == "/dev/null" or self.deleted_file:
52
+ return "deleted"
53
+ if not self.hunks and self.old_mode != self.new_mode:
54
+ return "mode_changed"
55
+ return "modified"
56
+
57
+ @property
58
+ def path(self) -> str:
59
+ return self.new if self.new != "/dev/null" else self.old
60
+
61
+
62
+ def _path_escape(text, i):
63
+ escapes = {
64
+ "a": 7,
65
+ "b": 8,
66
+ "t": 9,
67
+ "n": 10,
68
+ "v": 11,
69
+ "f": 12,
70
+ "r": 13,
71
+ '"': 34,
72
+ "\\": 92,
73
+ }
74
+ if i >= len(text):
75
+ raise InputError("Truncated quoted path escape")
76
+ ch = text[i]
77
+ i += 1
78
+ if ch in escapes:
79
+ return escapes[ch], i
80
+ digits = ch + text[i : i + 2]
81
+ if len(digits) == 3 and all(c in "01234567" for c in digits):
82
+ value = int(digits, 8)
83
+ if value <= 255:
84
+ return value, i + 2
85
+ raise InputError("Invalid Git C-style path escape")
86
+
87
+
88
+ def _quoted_token(text: str) -> tuple[str, str]:
89
+ if not text.startswith('"'):
90
+ raise InputError("Expected quoted path")
91
+ raw = bytearray()
92
+ i = 1
93
+ while i < len(text):
94
+ ch = text[i]
95
+ i += 1
96
+ if ch == '"':
97
+ try:
98
+ return raw.decode("utf-8"), text[i:]
99
+ except UnicodeError as exc:
100
+ raise InputError("Quoted path is not UTF-8") from exc
101
+ if ch != "\\":
102
+ raw.extend(ch.encode("utf-8"))
103
+ continue
104
+ value, i = _path_escape(text, i)
105
+ raw.append(value)
106
+ raise InputError("Unterminated quoted path")
107
+
108
+
109
+ def _decode_label(value, timestamp):
110
+ if value.startswith('"'):
111
+ value, rest = _quoted_token(value)
112
+ if rest and not (timestamp and rest.startswith("\t")):
113
+ raise InputError("Unexpected text after quoted path")
114
+ elif timestamp:
115
+ value = value.split("\t", 1)[0]
116
+ return value
117
+
118
+
119
+ def label(value: str, side: str = "", *, timestamp: bool = True) -> str:
120
+ value = _decode_label(value, timestamp)
121
+ if not value or len(value) > 1024 or "\x00" in value:
122
+ raise InputError("Empty, overlong or NUL-containing diff path")
123
+ if side and value.startswith(side + "/"):
124
+ value = value[2:]
125
+ if not value:
126
+ raise InputError("Empty diff path")
127
+ return value
128
+
129
+
130
+ def _quoted_git_paths(text):
131
+ old, rest = _quoted_token(text)
132
+ if not rest.startswith(" "):
133
+ raise InputError("Malformed Git file header")
134
+ new = label(rest[1:], timestamp=False)
135
+ old = label(old, "a", timestamp=False) if not old.startswith('"') else old
136
+ return old, new[2:] if new.startswith("b/") else new
137
+
138
+
139
+ def _git_paths(text):
140
+ if text.startswith('"'):
141
+ return _quoted_git_paths(text)
142
+ # Git leaves simple spaces unquoted. Prefer the split with identical paths;
143
+ # rename metadata / actual file headers override the tentative path pair.
144
+ positions = [m.start() for m in re.finditer(r' (?=b/|")', text)]
145
+ if not positions:
146
+ raise InputError("Malformed Git file header")
147
+ candidates = []
148
+ for pos in positions:
149
+ try:
150
+ old = label(text[:pos], "a", timestamp=False)
151
+ new = label(text[pos + 1 :], "b", timestamp=False)
152
+ except InputError:
153
+ continue
154
+ candidates.append((old, new))
155
+ if not candidates:
156
+ raise InputError("Malformed Git paths")
157
+ return next((p for p in candidates if p[0] == p[1]), candidates[-1])
158
+
159
+
160
+ def _apply_rename(current):
161
+ if bool(current.rename_from) != bool(current.rename_to):
162
+ raise InputError("Incomplete rename metadata")
163
+ if not current.rename_from or not current.rename_to:
164
+ return
165
+ current.renamed = True
166
+ if current.header_seen and (
167
+ current.old != current.rename_from or current.new != current.rename_to
168
+ ):
169
+ raise InputError("Rename metadata does not match file headers")
170
+ current.old, current.new = current.rename_from, current.rename_to
171
+
172
+
173
+ def _validate_rename_modes(current):
174
+ if current.renamed and (
175
+ current.new_file
176
+ or current.deleted_file
177
+ or current.rename_from == current.rename_to
178
+ ):
179
+ raise InputError("Invalid rename metadata")
180
+
181
+
182
+ def _validate_modes(current):
183
+ if current.new_file and current.deleted_file:
184
+ raise InputError("Conflicting file modes")
185
+ _validate_rename_modes(current)
186
+ if (
187
+ current.new_file
188
+ and current.old_mode is not None
189
+ or current.deleted_file
190
+ and current.new_mode is not None
191
+ ):
192
+ raise InputError("Conflicting add/delete mode metadata")
193
+
194
+
195
+ def _validate_paired_modes(current):
196
+ if (
197
+ not current.new_file
198
+ and not current.deleted_file
199
+ and bool(current.old_mode) != bool(current.new_mode)
200
+ ):
201
+ raise InputError("Incomplete mode metadata")
202
+
203
+
204
+ def _validate_null_headers(current):
205
+ if current.new_file:
206
+ if current.header_seen and current.old != "/dev/null":
207
+ raise InputError("New file metadata disagrees with header")
208
+ current.old = "/dev/null"
209
+ if current.deleted_file:
210
+ if current.header_seen and current.new != "/dev/null":
211
+ raise InputError("Deleted file metadata disagrees with header")
212
+ current.new = "/dev/null"
213
+ _validate_paired_modes(current)
214
+
215
+
216
+ def _require_file_change(current):
217
+ if not current.hunks and not (
218
+ current.renamed
219
+ or current.new_file
220
+ or current.deleted_file
221
+ or current.old_mode != current.new_mode
222
+ ):
223
+ raise InputError(f"No hunks or supported metadata changes for {current.path}")
224
+
225
+
226
+ def _finish_file(current, files, seen_paths):
227
+ if current is None:
228
+ return
229
+ _apply_rename(current)
230
+ _validate_modes(current)
231
+ _validate_null_headers(current)
232
+ _require_file_change(current)
233
+ if current.path == "/dev/null" or current.path in seen_paths:
234
+ raise InputError("Invalid or repeated file section")
235
+ seen_paths.add(current.path)
236
+ files.append(current)
237
+ if len(files) > MAX_FILES:
238
+ raise InputError(f"Diff exceeds {MAX_FILES} files")
239
+
240
+
241
+ _METADATA = (
242
+ "index ",
243
+ "similarity index ",
244
+ "dissimilarity index ",
245
+ "rename from ",
246
+ "rename to ",
247
+ "old mode ",
248
+ "new mode ",
249
+ "new file mode ",
250
+ "deleted file mode ",
251
+ )
252
+
253
+
254
+ def _metadata_mode(current, row):
255
+ mode = row.rsplit(" ", 1)[1]
256
+ if not re.fullmatch(r"[0-7]{6}", mode):
257
+ raise InputError("Invalid Git mode")
258
+ if row.startswith(("old mode ", "deleted file mode ")):
259
+ if current.old_mode is not None:
260
+ raise InputError("Repeated old mode")
261
+ current.old_mode = mode
262
+ current.deleted_file = row.startswith("deleted file mode ")
263
+ else:
264
+ if current.new_mode is not None:
265
+ raise InputError("Repeated new mode")
266
+ current.new_mode = mode
267
+ current.new_file = row.startswith("new file mode ")
268
+
269
+
270
+ def _metadata_rename(current, row):
271
+ side = "rename_from" if row.startswith("rename from ") else "rename_to"
272
+ if getattr(current, side) is not None:
273
+ raise InputError("Duplicate rename metadata")
274
+ setattr(current, side, label(row.split(" ", 2)[2], timestamp=False))
275
+
276
+
277
+ def _require_metadata_section(current):
278
+ if (
279
+ current is None
280
+ or not current.git_header
281
+ or current.header_seen
282
+ or current.hunks
283
+ ):
284
+ raise InputError("Unexpected Git metadata outside a file section")
285
+
286
+
287
+ def _metadata(current, row):
288
+ _require_metadata_section(current)
289
+ if row.startswith("index "):
290
+ if not re.fullmatch(
291
+ r"index [0-9a-fA-F]{4,64}\.\.[0-9a-fA-F]{4,64}(?: [0-7]{6})?", row
292
+ ):
293
+ raise InputError("Invalid Git index metadata")
294
+ elif row.startswith(("similarity index ", "dissimilarity index ")):
295
+ m = re.fullmatch(r"(?:similarity|dissimilarity) index ([0-9]{1,3})%", row)
296
+ if m is None or int(m.group(1)) > 100:
297
+ raise InputError("Invalid Git similarity metadata")
298
+ elif row.startswith(("rename from ", "rename to ")):
299
+ _metadata_rename(current, row)
300
+ else:
301
+ _metadata_mode(current, row)
302
+
303
+
304
+ def _file_headers(lines, i, current, files, seen_paths):
305
+ if i + 1 >= len(lines) or not lines[i + 1].startswith("+++ "):
306
+ raise InputError(f"Missing new-file header at diff line {i+1}")
307
+ if current is None or current.header_seen:
308
+ _finish_file(current, files, seen_paths)
309
+ current = ChangedFile("", "")
310
+ current.old = label(lines[i][4:], "a")
311
+ current.new = label(lines[i + 1][4:], "b")
312
+ current.header_seen = True
313
+ if current.old == current.new == "/dev/null":
314
+ raise InputError("Invalid null paths")
315
+ return current
316
+
317
+
318
+ def _hunk_ranges(current, match):
319
+ if current is None or not current.header_seen:
320
+ raise InputError("Hunk must follow file headers")
321
+ old, old_count, new, new_count = (
322
+ int(v) if v is not None else 1 for v in match.groups()
323
+ )
324
+ _validate_ranges(old, old_count, new, new_count)
325
+ if old < current.old_end or new < current.new_end:
326
+ raise InputError("Hunks overlap or are out of order")
327
+ current.old_end, current.new_end = old + old_count, new + new_count
328
+ current.old_ranges.append((old, old_count))
329
+ current.new_ranges.append((new, new_count))
330
+ current.hunks += 1
331
+ return old, old_count, new, new_count
332
+
333
+
334
+ def _validate_range_starts(old, old_count, new, new_count):
335
+ if (old == 0 and old_count) or (new == 0 and new_count):
336
+ raise InputError("Nonempty ranges must begin at line 1 or later")
337
+
338
+
339
+ def _validate_ranges(old, old_count, new, new_count):
340
+ if (
341
+ old_count > MAX_LINES
342
+ or new_count > MAX_LINES
343
+ or old + old_count > 10**8
344
+ or new + new_count > 10**8
345
+ or not (old_count or new_count)
346
+ ):
347
+ raise InputError("Hunk count or line number is outside supported bounds")
348
+ _validate_range_starts(old, old_count, new, new_count)
349
+
350
+
351
+ @dataclass
352
+ class _HunkCursor:
353
+ old: int
354
+ old_left: int
355
+ new: int
356
+ new_left: int
357
+ last_kind: str | None = None
358
+ prior_line: bool = False
359
+
360
+ def eof_marker(self, current):
361
+ if self.last_kind in (" ", "-"):
362
+ current.old_eof = self.old - 1
363
+ if self.last_kind in (" ", "+"):
364
+ current.new_eof = self.new - 1
365
+
366
+ def old_line(self, current, kind, value):
367
+ current.old_context.append((self.old, value))
368
+ if kind == "-":
369
+ current.removed_lines.append(self.old)
370
+ current.removed += 1
371
+ self.old += 1
372
+ self.old_left -= 1
373
+
374
+ def new_line(self, current, kind, value, issues):
375
+ current.new_context.append((self.new, value))
376
+ if kind == "+":
377
+ current.added += 1
378
+ current.added_lines.append(self.new)
379
+ if value.endswith((" ", "\t")):
380
+ issues.append(
381
+ finding(
382
+ "TRAILING_WHITESPACE",
383
+ "info",
384
+ "fact",
385
+ current.path,
386
+ self.new,
387
+ "Added line ends in whitespace.",
388
+ "Consider removing it only if the format permits; Markdown or string contents may require it.",
389
+ )
390
+ )
391
+ self.new += 1
392
+ self.new_left -= 1
393
+
394
+ def line(self, current, row, issues, i):
395
+ if not row or row[0] not in " +-":
396
+ raise InputError(f"Invalid hunk body at diff line {i+1}")
397
+ kind, value = row[0], row[1:]
398
+ self.last_kind = kind
399
+ if kind in " -":
400
+ self.old_line(current, kind, value)
401
+ if kind in " +":
402
+ self.new_line(current, kind, value, issues)
403
+ if self.old_left < 0 or self.new_left < 0:
404
+ raise InputError(f"Hunk counts do not match at diff line {i+1}")
405
+ self.prior_line = True
406
+
407
+
408
+ _EOF_MARKER = "\"
409
+
410
+
411
+ def _consume_hunk(lines, i, current, match, issues):
412
+ cursor = _HunkCursor(*_hunk_ranges(current, match))
413
+ i += 1
414
+ while cursor.old_left or cursor.new_left:
415
+ if i >= len(lines):
416
+ raise InputError("Truncated hunk")
417
+ row = lines[i]
418
+ if row == _EOF_MARKER and cursor.prior_line:
419
+ cursor.eof_marker(current)
420
+ cursor.prior_line = False
421
+ else:
422
+ cursor.line(current, row, issues, i)
423
+ i += 1
424
+ if i < len(lines) and lines[i] == _EOF_MARKER and cursor.prior_line:
425
+ cursor.eof_marker(current)
426
+ i += 1
427
+ return i
428
+
429
+
430
+ def parse_diff(text: str) -> tuple[list[ChangedFile], list[dict]]:
431
+ lines = bounded(text, name="diff")
432
+ files, issues = [], []
433
+ current = None
434
+ i = 0
435
+ seen_paths = set()
436
+ while i < len(lines):
437
+ row = lines[i]
438
+ if row.startswith("diff --git "):
439
+ _finish_file(current, files, seen_paths)
440
+ old, new = _git_paths(row[11:])
441
+ current = ChangedFile(old, new, git_header=True)
442
+ i += 1
443
+ elif row.startswith(
444
+ ("Binary files ", "GIT binary patch", "copy from ", "copy to ")
445
+ ):
446
+ raise InputError("Binary and copy diffs are unsupported")
447
+ elif row.startswith(_METADATA):
448
+ _metadata(current, row)
449
+ i += 1
450
+ elif row.startswith("--- "):
451
+ current = _file_headers(lines, i, current, files, seen_paths)
452
+ i += 2
453
+ elif match := HUNK.fullmatch(row):
454
+ i = _consume_hunk(lines, i, current, match, issues)
455
+ elif not row.strip():
456
+ i += 1
457
+ else:
458
+ raise InputError(f"Unsupported diff syntax at input line {i+1}")
459
+ _finish_file(current, files, seen_paths)
460
+ if not files:
461
+ raise InputError("Expected one or more supported diff file sections")
462
+ return files, issues
463
+
464
+
465
+ def _test_path(path: str) -> bool:
466
+ parts = path.lower().replace("\\", "/").split("/")
467
+ base = parts[-1]
468
+ return (
469
+ any(p in {"test", "tests", "__tests__"} for p in parts[:-1])
470
+ or base.startswith("test_")
471
+ or base.endswith(("_test.py", ".test.js", ".spec.js", ".test.ts", ".spec.ts"))
472
+ )
473
+
474
+
475
+ def _review_findings(files, issues, exceeded):
476
+ if exceeded:
477
+ issues.insert(
478
+ 0,
479
+ finding(
480
+ "CHANGE_BUDGET",
481
+ "warning",
482
+ "fact",
483
+ "",
484
+ None,
485
+ "Supplied change exceeds at least one review budget.",
486
+ "Split independent changes or explain why they need one patch.",
487
+ ),
488
+ )
489
+ tests = [f.path for f in files if _test_path(f.path)]
490
+ ordinary = [f.path for f in files if not _test_path(f.path)]
491
+ if ordinary and not tests:
492
+ issues.append(
493
+ finding(
494
+ "NO_TEST_PATH",
495
+ "info",
496
+ "heuristic",
497
+ "",
498
+ None,
499
+ "No paths matching common test naming conventions in this diff.",
500
+ "Consider focused regression coverage and existing nearby tests; test changes may not be necessary.",
501
+ )
502
+ )
503
+ return tests
504
+
505
+
506
+ def _test_plan(f):
507
+ return dict(
508
+ path=f.path,
509
+ targets=f.added_lines[:30],
510
+ omitted_targets=max(0, len(f.added_lines) - 30),
511
+ old_targets=f.removed_lines[:30],
512
+ omitted_old_targets=max(0, len(f.removed_lines) - 30),
513
+ suggestions=(
514
+ [
515
+ "Review renamed paths, import references, or intended mode change and related tests."
516
+ ]
517
+ if not f.hunks
518
+ else (
519
+ ["Review updated assertions and run this test module."]
520
+ if _test_path(f.path)
521
+ else [
522
+ "Exercise intended behavior and unchanged neighboring behavior.",
523
+ "Cover relevant edge cases and error handling; use existing project conventions.",
524
+ ]
525
+ )
526
+ ),
527
+ )
528
+
529
+
530
+ def _file_report(f):
531
+ return dict(
532
+ path=f.path,
533
+ old_path=f.old,
534
+ new_path=f.new,
535
+ added=f.added,
536
+ removed=f.removed,
537
+ hunks=f.hunks,
538
+ added_lines=f.added_lines,
539
+ removed_lines=f.removed_lines,
540
+ change_kind=f.change_kind,
541
+ old_mode=f.old_mode,
542
+ new_mode=f.new_mode,
543
+ )
544
+
545
+
546
+ def review_diff(diff: str, change_budget: int = 300, file_budget: int = 10) -> dict:
547
+ if not 1 <= change_budget <= 10000 or not 1 <= file_budget <= MAX_FILES:
548
+ raise InputError("Budget is outside supported bounds")
549
+ if diff == "":
550
+ return dict(
551
+ no_input(""),
552
+ totals=dict(files=0, added=0, removed=0, churn=0),
553
+ budget=dict(changed_lines=change_budget, files=file_budget, exceeded=False),
554
+ review_effort="routine",
555
+ files=[],
556
+ test_paths=[],
557
+ test_plan=[],
558
+ omitted_findings=0,
559
+ )
560
+ files, issues = parse_diff(diff)
561
+ added = sum(f.added for f in files)
562
+ removed = sum(f.removed for f in files)
563
+ churn = added + removed
564
+ exceeded = churn > change_budget or len(files) > file_budget
565
+ tests = _review_findings(files, issues, exceeded)
566
+ return dict(
567
+ totals=dict(files=len(files), added=added, removed=removed, churn=churn),
568
+ budget=dict(changed_lines=change_budget, files=file_budget, exceeded=exceeded),
569
+ review_effort="elevated" if exceeded else "routine",
570
+ files=list(map(_file_report, files)),
571
+ test_paths=tests,
572
+ test_plan=[_test_plan(f) for f in files],
573
+ findings=issues[:MAX_FINDINGS],
574
+ omitted_findings=max(0, len(issues) - MAX_FINDINGS),
575
+ limitations=[
576
+ "Only supplied unified-diff text was reviewed, not the project.",
577
+ "Effort describes change size, not security or correctness.",
578
+ "Test path matching is heuristic; no tests were executed.",
579
+ f"Findings are capped at {MAX_FINDINGS}.",
580
+ ],
581
+ )