patchproof-core 0.3.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.
- patchproof/__init__.py +44 -0
- patchproof/__main__.py +8 -0
- patchproof/benchmarks/__init__.py +17 -0
- patchproof/benchmarks/swe_bench.py +159 -0
- patchproof/cli.py +1254 -0
- patchproof/core/__init__.py +33 -0
- patchproof/core/agent_init.py +103 -0
- patchproof/core/anti_cheat.py +396 -0
- patchproof/core/applier.py +159 -0
- patchproof/core/ast_analyzer.py +254 -0
- patchproof/core/detector.py +78 -0
- patchproof/core/git_provider.py +298 -0
- patchproof/core/healer.py +104 -0
- patchproof/core/mutator.py +223 -0
- patchproof/core/normalizer.py +338 -0
- patchproof/core/polyglot_guard.py +167 -0
- patchproof/core/runtime_guard.py +188 -0
- patchproof/core/search_replace.py +222 -0
- patchproof/core/slicer.py +172 -0
- patchproof/core/sparse_tree.py +95 -0
- patchproof/docker/runner.Dockerfile +42 -0
- patchproof/exceptions.py +37 -0
- patchproof/factory/__init__.py +22 -0
- patchproof/factory/blast_radius.py +120 -0
- patchproof/factory/engine.py +134 -0
- patchproof/factory/models.py +75 -0
- patchproof/mcp.py +532 -0
- patchproof/models/__init__.py +57 -0
- patchproof/models/ast.py +78 -0
- patchproof/models/patch.py +106 -0
- patchproof/models/sandbox.py +417 -0
- patchproof/reporting/__init__.py +19 -0
- patchproof/reporting/asymmetric.py +88 -0
- patchproof/reporting/badge.py +86 -0
- patchproof/reporting/certificate.py +230 -0
- patchproof/reporting/diagnostic.py +330 -0
- patchproof/reporting/html_report.py +367 -0
- patchproof/reporting/in_toto.py +188 -0
- patchproof/reporting/markdown.py +179 -0
- patchproof/reporting/sbom.py +152 -0
- patchproof/sandbox/__init__.py +37 -0
- patchproof/sandbox/classifier.py +289 -0
- patchproof/sandbox/comparative.py +478 -0
- patchproof/sandbox/docker_cli.py +384 -0
- patchproof/sandbox/doctor.py +605 -0
- patchproof/sandbox/flakiness.py +87 -0
- patchproof/sandbox/network_bridge.py +145 -0
- patchproof/sandbox/parser.py +172 -0
- patchproof/sandbox/runner.py +424 -0
- patchproof/sandbox/setup_runner.py +261 -0
- patchproof_core-0.3.1.dist-info/METADATA +212 -0
- patchproof_core-0.3.1.dist-info/RECORD +56 -0
- patchproof_core-0.3.1.dist-info/WHEEL +5 -0
- patchproof_core-0.3.1.dist-info/entry_points.txt +2 -0
- patchproof_core-0.3.1.dist-info/licenses/LICENSE +13 -0
- patchproof_core-0.3.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Autonomous Patch Self-Healing Engine.
|
|
2
|
+
|
|
3
|
+
Orchestrates multi-turn convergence loops using Fault Localization diagnostics
|
|
4
|
+
to automatically repair regressions and produce verified green patches.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
from patchproof.core.normalizer import parse_patch
|
|
14
|
+
from patchproof.models.patch import CanonicalPatch
|
|
15
|
+
from patchproof.models.sandbox import (
|
|
16
|
+
ComparativeExecutionResult,
|
|
17
|
+
ContainerConfig,
|
|
18
|
+
PatchVerdict,
|
|
19
|
+
)
|
|
20
|
+
from patchproof.reporting.diagnostic import AISelfHealingReport, generate_ai_feedback
|
|
21
|
+
from patchproof.sandbox.comparative import ComparativeRunner
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class HealResult:
|
|
28
|
+
"""Consolidated outcome of an autonomous self-healing session."""
|
|
29
|
+
|
|
30
|
+
success: bool
|
|
31
|
+
iterations: int
|
|
32
|
+
final_patch: str
|
|
33
|
+
last_result: ComparativeExecutionResult
|
|
34
|
+
summary: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class AutonomousHealer:
|
|
38
|
+
"""Orchestrates an automated repair-and-verify convergence loop."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, runner: ComparativeRunner | None = None) -> None:
|
|
41
|
+
self.runner = runner or ComparativeRunner()
|
|
42
|
+
|
|
43
|
+
def heal(
|
|
44
|
+
self,
|
|
45
|
+
config: ContainerConfig,
|
|
46
|
+
initial_patch: str,
|
|
47
|
+
repair_agent_fn: Callable[[AISelfHealingReport], str | None],
|
|
48
|
+
max_iterations: int = 3,
|
|
49
|
+
disambiguate_flakes: bool = False,
|
|
50
|
+
) -> HealResult:
|
|
51
|
+
"""Iteratively verify and repair a patch until regression-free or bounded limit."""
|
|
52
|
+
current_patch = initial_patch
|
|
53
|
+
last_result: ComparativeExecutionResult | None = None
|
|
54
|
+
|
|
55
|
+
for iteration in range(1, max_iterations + 1):
|
|
56
|
+
logger.info("Starting healing iteration %d/%d", iteration, max_iterations)
|
|
57
|
+
last_result = self.runner.run(
|
|
58
|
+
config,
|
|
59
|
+
current_patch,
|
|
60
|
+
disambiguate_flakes=disambiguate_flakes,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
if last_result.verdict == PatchVerdict.ACCEPTED:
|
|
64
|
+
return HealResult(
|
|
65
|
+
success=True,
|
|
66
|
+
iterations=iteration,
|
|
67
|
+
final_patch=current_patch,
|
|
68
|
+
last_result=last_result,
|
|
69
|
+
summary=f"Patch successfully healed in {iteration} iteration(s)",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# Generate fault localization diagnostics
|
|
73
|
+
can_p: CanonicalPatch | None = None
|
|
74
|
+
try:
|
|
75
|
+
can_p = parse_patch(current_patch)
|
|
76
|
+
except Exception:
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
diagnostic_report = generate_ai_feedback(last_result, patch=can_p)
|
|
80
|
+
|
|
81
|
+
# Call agent/repair function
|
|
82
|
+
proposed_patch = repair_agent_fn(diagnostic_report)
|
|
83
|
+
if not proposed_patch:
|
|
84
|
+
return HealResult(
|
|
85
|
+
success=False,
|
|
86
|
+
iterations=iteration,
|
|
87
|
+
final_patch=current_patch,
|
|
88
|
+
last_result=last_result,
|
|
89
|
+
summary=(
|
|
90
|
+
f"Healing aborted at iteration {iteration}: "
|
|
91
|
+
"repair agent returned no replacement patch"
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
current_patch = proposed_patch
|
|
96
|
+
|
|
97
|
+
assert last_result is not None
|
|
98
|
+
return HealResult(
|
|
99
|
+
success=False,
|
|
100
|
+
iterations=max_iterations,
|
|
101
|
+
final_patch=current_patch,
|
|
102
|
+
last_result=last_result,
|
|
103
|
+
summary=f"Exhausted maximum {max_iterations} iterations without convergence",
|
|
104
|
+
)
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""AST Differential Mutation Testing Subsystem.
|
|
2
|
+
|
|
3
|
+
Synthesizes targeted code mutations on touched source lines to evaluate
|
|
4
|
+
whether candidate test suites actually exercise and verify logic rather than
|
|
5
|
+
asserting tautologies or using empty mocks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import ast
|
|
11
|
+
import copy
|
|
12
|
+
from dataclasses import asdict, dataclass
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Mutant:
|
|
18
|
+
"""Represents a single-site intentional synthetic code mutation."""
|
|
19
|
+
|
|
20
|
+
id: str
|
|
21
|
+
file_path: str
|
|
22
|
+
line_number: int
|
|
23
|
+
description: str
|
|
24
|
+
mutated_source: str
|
|
25
|
+
killed: bool | None = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class DifferentialMutationReport:
|
|
30
|
+
"""Summary of differential mutation evaluation."""
|
|
31
|
+
|
|
32
|
+
total_mutants: int
|
|
33
|
+
killed_mutants: int
|
|
34
|
+
survived_mutants: int
|
|
35
|
+
mutation_score: float
|
|
36
|
+
mutants: tuple[Mutant, ...] = ()
|
|
37
|
+
|
|
38
|
+
def is_sufficiently_killed(self, threshold_pct: float = 70.0) -> bool:
|
|
39
|
+
"""True if the proportion of killed mutants meets or exceeds threshold."""
|
|
40
|
+
return self.mutation_score >= threshold_pct
|
|
41
|
+
|
|
42
|
+
def to_dict(self) -> dict[str, Any]:
|
|
43
|
+
"""Convert report to serializable dictionary."""
|
|
44
|
+
return {
|
|
45
|
+
"total_mutants": self.total_mutants,
|
|
46
|
+
"killed_mutants": self.killed_mutants,
|
|
47
|
+
"survived_mutants": self.survived_mutants,
|
|
48
|
+
"mutation_score": self.mutation_score,
|
|
49
|
+
"mutants": [asdict(m) for m in self.mutants],
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class _SingleSiteMutator(ast.NodeTransformer):
|
|
54
|
+
"""Applies a mutation to a single designated node index."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, target_index: int) -> None:
|
|
57
|
+
super().__init__()
|
|
58
|
+
self.target_index = target_index
|
|
59
|
+
self.current_index = 0
|
|
60
|
+
self.description: str | None = None
|
|
61
|
+
self.line_number: int = 1
|
|
62
|
+
|
|
63
|
+
def visit_Compare(self, node: ast.Compare) -> ast.AST:
|
|
64
|
+
new_ops: list[ast.cmpop] = []
|
|
65
|
+
modified = False
|
|
66
|
+
for op in node.ops:
|
|
67
|
+
if self.current_index == self.target_index:
|
|
68
|
+
self.line_number = getattr(node, "lineno", 1)
|
|
69
|
+
if isinstance(op, ast.Gt):
|
|
70
|
+
new_ops.append(ast.LtE())
|
|
71
|
+
self.description = f"Line {self.line_number}: Replaced > with <="
|
|
72
|
+
modified = True
|
|
73
|
+
elif isinstance(op, ast.Lt):
|
|
74
|
+
new_ops.append(ast.GtE())
|
|
75
|
+
self.description = f"Line {self.line_number}: Replaced < with >="
|
|
76
|
+
modified = True
|
|
77
|
+
elif isinstance(op, ast.Eq):
|
|
78
|
+
new_ops.append(ast.NotEq())
|
|
79
|
+
self.description = f"Line {self.line_number}: Replaced == with !="
|
|
80
|
+
modified = True
|
|
81
|
+
elif isinstance(op, ast.NotEq):
|
|
82
|
+
new_ops.append(ast.Eq())
|
|
83
|
+
self.description = f"Line {self.line_number}: Replaced != with =="
|
|
84
|
+
modified = True
|
|
85
|
+
else:
|
|
86
|
+
new_ops.append(op)
|
|
87
|
+
else:
|
|
88
|
+
new_ops.append(op)
|
|
89
|
+
self.current_index += 1
|
|
90
|
+
|
|
91
|
+
if modified:
|
|
92
|
+
return ast.Compare(
|
|
93
|
+
left=self.visit(node.left),
|
|
94
|
+
ops=new_ops,
|
|
95
|
+
comparators=[self.visit(c) for c in node.comparators],
|
|
96
|
+
)
|
|
97
|
+
return self.generic_visit(node)
|
|
98
|
+
|
|
99
|
+
def visit_BoolOp(self, node: ast.BoolOp) -> ast.AST:
|
|
100
|
+
if self.current_index == self.target_index:
|
|
101
|
+
self.line_number = getattr(node, "lineno", 1)
|
|
102
|
+
if isinstance(node.op, ast.And):
|
|
103
|
+
self.current_index += 1
|
|
104
|
+
self.description = f"Line {self.line_number}: Replaced 'and' with 'or'"
|
|
105
|
+
return ast.BoolOp(
|
|
106
|
+
op=ast.Or(),
|
|
107
|
+
values=[self.visit(v) for v in node.values],
|
|
108
|
+
)
|
|
109
|
+
elif isinstance(node.op, ast.Or):
|
|
110
|
+
self.current_index += 1
|
|
111
|
+
self.description = f"Line {self.line_number}: Replaced 'or' with 'and'"
|
|
112
|
+
return ast.BoolOp(
|
|
113
|
+
op=ast.And(),
|
|
114
|
+
values=[self.visit(v) for v in node.values],
|
|
115
|
+
)
|
|
116
|
+
self.current_index += 1
|
|
117
|
+
return self.generic_visit(node)
|
|
118
|
+
|
|
119
|
+
def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
|
|
120
|
+
if self.current_index == self.target_index:
|
|
121
|
+
self.line_number = getattr(node, "lineno", 1)
|
|
122
|
+
if isinstance(node.op, ast.Add):
|
|
123
|
+
self.current_index += 1
|
|
124
|
+
self.description = f"Line {self.line_number}: Replaced + with -"
|
|
125
|
+
return ast.BinOp(
|
|
126
|
+
left=self.visit(node.left), op=ast.Sub(), right=self.visit(node.right)
|
|
127
|
+
)
|
|
128
|
+
elif isinstance(node.op, ast.Sub):
|
|
129
|
+
self.current_index += 1
|
|
130
|
+
self.description = f"Line {self.line_number}: Replaced - with +"
|
|
131
|
+
return ast.BinOp(
|
|
132
|
+
left=self.visit(node.left), op=ast.Add(), right=self.visit(node.right)
|
|
133
|
+
)
|
|
134
|
+
elif isinstance(node.op, ast.Mult):
|
|
135
|
+
self.current_index += 1
|
|
136
|
+
self.description = f"Line {self.line_number}: Replaced * with /"
|
|
137
|
+
return ast.BinOp(
|
|
138
|
+
left=self.visit(node.left), op=ast.Div(), right=self.visit(node.right)
|
|
139
|
+
)
|
|
140
|
+
self.current_index += 1
|
|
141
|
+
return self.generic_visit(node)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _count_mutation_sites(tree: ast.AST) -> int:
|
|
145
|
+
"""Count total potential mutation targets in AST."""
|
|
146
|
+
count = 0
|
|
147
|
+
for node in ast.walk(tree):
|
|
148
|
+
if isinstance(node, ast.Compare):
|
|
149
|
+
count += len(node.ops)
|
|
150
|
+
elif isinstance(node, ast.BoolOp):
|
|
151
|
+
count += 1
|
|
152
|
+
elif isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult)):
|
|
153
|
+
count += 1
|
|
154
|
+
return count
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def generate_mutants_for_source(
|
|
158
|
+
source_code: str,
|
|
159
|
+
file_path: str = "module.py",
|
|
160
|
+
max_mutants: int = 15,
|
|
161
|
+
) -> list[Mutant]:
|
|
162
|
+
"""Generate isolated AST mutants from Python source code.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
source_code: Source code string to mutate.
|
|
166
|
+
file_path: Path of the source file.
|
|
167
|
+
max_mutants: Maximum number of mutants to generate.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
list[Mutant]: Generated mutants.
|
|
171
|
+
"""
|
|
172
|
+
try:
|
|
173
|
+
base_tree = ast.parse(source_code, filename=file_path)
|
|
174
|
+
except SyntaxError:
|
|
175
|
+
return []
|
|
176
|
+
|
|
177
|
+
total_sites = _count_mutation_sites(base_tree)
|
|
178
|
+
mutants: list[Mutant] = []
|
|
179
|
+
|
|
180
|
+
for site_idx in range(min(total_sites, max_mutants)):
|
|
181
|
+
mutated_tree = copy.deepcopy(base_tree)
|
|
182
|
+
mutator = _SingleSiteMutator(target_index=site_idx)
|
|
183
|
+
transformed = mutator.visit(mutated_tree)
|
|
184
|
+
ast.fix_missing_locations(transformed)
|
|
185
|
+
|
|
186
|
+
if mutator.description:
|
|
187
|
+
mutated_src = ast.unparse(transformed)
|
|
188
|
+
mutants.append(
|
|
189
|
+
Mutant(
|
|
190
|
+
id=f"mutant_{site_idx + 1}",
|
|
191
|
+
file_path=file_path,
|
|
192
|
+
line_number=mutator.line_number,
|
|
193
|
+
description=mutator.description,
|
|
194
|
+
mutated_source=mutated_src,
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
return mutants
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def score_mutation_results(mutants: list[Mutant]) -> DifferentialMutationReport:
|
|
202
|
+
"""Calculate aggregate mutation survival metrics from evaluated mutants."""
|
|
203
|
+
total = len(mutants)
|
|
204
|
+
if total == 0:
|
|
205
|
+
return DifferentialMutationReport(
|
|
206
|
+
total_mutants=0,
|
|
207
|
+
killed_mutants=0,
|
|
208
|
+
survived_mutants=0,
|
|
209
|
+
mutation_score=100.0,
|
|
210
|
+
mutants=(),
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
killed = sum(1 for m in mutants if m.killed is True)
|
|
214
|
+
survived = total - killed
|
|
215
|
+
score = (killed / total) * 100.0
|
|
216
|
+
|
|
217
|
+
return DifferentialMutationReport(
|
|
218
|
+
total_mutants=total,
|
|
219
|
+
killed_mutants=killed,
|
|
220
|
+
survived_mutants=survived,
|
|
221
|
+
mutation_score=score,
|
|
222
|
+
mutants=tuple(mutants),
|
|
223
|
+
)
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Unified diff parsing and normalization into canonical patch representations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from patchproof.exceptions import InvalidPatchFormatError
|
|
8
|
+
from patchproof.models.patch import (
|
|
9
|
+
CanonicalPatch,
|
|
10
|
+
ChangeType,
|
|
11
|
+
FileDelta,
|
|
12
|
+
PatchHunk,
|
|
13
|
+
PatchType,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
HUNK_HEADER_RE = re.compile(
|
|
17
|
+
r"^@@ -(?P<old_start>\d+)(?:,(?P<old_lines>\d+))? "
|
|
18
|
+
r"\+(?P<new_start>\d+)(?:,(?P<new_lines>\d+))? @@(?P<header_rest>.*)$"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
GIT_DIFF_RE = re.compile(
|
|
22
|
+
r'^diff --git (?:"(?P<old_quoted>[^"]+)"|(?P<old_unquoted>\S+)) '
|
|
23
|
+
r'(?:"(?P<new_quoted>[^"]+)"|(?P<new_unquoted>\S+))$'
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
BINARY_DIFF_RE = re.compile(
|
|
27
|
+
r'^Binary files (?:"(?P<old_quoted>[^"]+)"|(?P<old_unquoted>\S+)) '
|
|
28
|
+
r'and (?:"(?P<new_quoted>[^"]+)"|(?P<new_unquoted>\S+)) differ$'
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _clean_path(path: str) -> str:
|
|
33
|
+
"""Normalize file path by stripping leading a/ or b/ prefixes, quotes, and timestamps."""
|
|
34
|
+
clean = path.split("\t")[0].strip()
|
|
35
|
+
clean = clean.strip("\"'")
|
|
36
|
+
if clean == "/dev/null":
|
|
37
|
+
return "/dev/null"
|
|
38
|
+
if clean.startswith("a/") or clean.startswith("b/"):
|
|
39
|
+
return clean[2:]
|
|
40
|
+
return clean
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _UnifiedDiffParser:
|
|
44
|
+
"""Internal state-machine parser for unified diff format."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, raw_diff: str) -> None:
|
|
47
|
+
self.raw_diff = raw_diff.replace("\r\n", "\n").replace("\r", "\n")
|
|
48
|
+
self.lines: list[str] = self.raw_diff.split("\n")
|
|
49
|
+
if self.lines and self.lines[-1] == "":
|
|
50
|
+
self.lines.pop()
|
|
51
|
+
|
|
52
|
+
self.idx = 0
|
|
53
|
+
self.total = len(self.lines)
|
|
54
|
+
|
|
55
|
+
def parse(self) -> CanonicalPatch:
|
|
56
|
+
if not self.raw_diff.strip():
|
|
57
|
+
raise InvalidPatchFormatError("Patch content is empty or contains only whitespace")
|
|
58
|
+
|
|
59
|
+
file_deltas: list[FileDelta] = []
|
|
60
|
+
|
|
61
|
+
while self.idx < self.total:
|
|
62
|
+
line = self.lines[self.idx]
|
|
63
|
+
|
|
64
|
+
if not (
|
|
65
|
+
line.startswith("diff --git")
|
|
66
|
+
or line.startswith("--- ")
|
|
67
|
+
or line.startswith("Index: ")
|
|
68
|
+
or line.startswith("Binary files ")
|
|
69
|
+
):
|
|
70
|
+
self.idx += 1
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
start_idx = self.idx
|
|
74
|
+
delta = self._parse_file_entry()
|
|
75
|
+
if delta is not None:
|
|
76
|
+
file_deltas.append(delta)
|
|
77
|
+
elif self.idx == start_idx:
|
|
78
|
+
# Guaranteed forward progress to prevent infinite loops
|
|
79
|
+
self.idx += 1
|
|
80
|
+
|
|
81
|
+
if not file_deltas:
|
|
82
|
+
raise InvalidPatchFormatError(
|
|
83
|
+
"No valid unified diff file headers found (expected '---'/'+++' or 'diff --git')"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
return CanonicalPatch(
|
|
87
|
+
patch_type=PatchType.UNIFIED_DIFF,
|
|
88
|
+
file_deltas=tuple(file_deltas),
|
|
89
|
+
raw_diff=self.raw_diff,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def _parse_file_entry(self) -> FileDelta | None:
|
|
93
|
+
old_path: str | None = None
|
|
94
|
+
new_path: str | None = None
|
|
95
|
+
is_new_mode = False
|
|
96
|
+
is_deleted_mode = False
|
|
97
|
+
is_mode_change = False
|
|
98
|
+
is_binary = False
|
|
99
|
+
|
|
100
|
+
while self.idx < self.total:
|
|
101
|
+
line = self.lines[self.idx]
|
|
102
|
+
|
|
103
|
+
if line.startswith("diff --git"):
|
|
104
|
+
match = GIT_DIFF_RE.match(line)
|
|
105
|
+
if match:
|
|
106
|
+
old_path = match.group("old_quoted") or match.group("old_unquoted")
|
|
107
|
+
new_path = match.group("new_quoted") or match.group("new_unquoted")
|
|
108
|
+
self.idx += 1
|
|
109
|
+
continue
|
|
110
|
+
|
|
111
|
+
if line.startswith("Index: "):
|
|
112
|
+
idx_path = line[7:].strip().strip("\"'")
|
|
113
|
+
if not old_path:
|
|
114
|
+
old_path = idx_path
|
|
115
|
+
if not new_path:
|
|
116
|
+
new_path = idx_path
|
|
117
|
+
self.idx += 1
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
if line.startswith("===") or line.startswith("RCS file:"):
|
|
121
|
+
# Subversion / CVS header dividers
|
|
122
|
+
self.idx += 1
|
|
123
|
+
continue
|
|
124
|
+
|
|
125
|
+
if line.startswith("new file mode"):
|
|
126
|
+
is_new_mode = True
|
|
127
|
+
self.idx += 1
|
|
128
|
+
continue
|
|
129
|
+
|
|
130
|
+
if line.startswith("deleted file mode"):
|
|
131
|
+
is_deleted_mode = True
|
|
132
|
+
self.idx += 1
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
if line.startswith("old mode ") or line.startswith("new mode "):
|
|
136
|
+
is_mode_change = True
|
|
137
|
+
self.idx += 1
|
|
138
|
+
continue
|
|
139
|
+
|
|
140
|
+
if line.startswith("rename from "):
|
|
141
|
+
old_path = line[12:].strip().strip("\"'")
|
|
142
|
+
self.idx += 1
|
|
143
|
+
continue
|
|
144
|
+
|
|
145
|
+
if line.startswith("rename to "):
|
|
146
|
+
new_path = line[10:].strip().strip("\"'")
|
|
147
|
+
self.idx += 1
|
|
148
|
+
continue
|
|
149
|
+
|
|
150
|
+
if line.startswith("Binary files "):
|
|
151
|
+
is_binary = True
|
|
152
|
+
bin_match = BINARY_DIFF_RE.match(line)
|
|
153
|
+
if bin_match:
|
|
154
|
+
bin_old = bin_match.group("old_quoted") or bin_match.group("old_unquoted")
|
|
155
|
+
bin_new = bin_match.group("new_quoted") or bin_match.group("new_unquoted")
|
|
156
|
+
if not old_path:
|
|
157
|
+
old_path = bin_old
|
|
158
|
+
if not new_path:
|
|
159
|
+
new_path = bin_new
|
|
160
|
+
self.idx += 1
|
|
161
|
+
break
|
|
162
|
+
|
|
163
|
+
if line.startswith("--- "):
|
|
164
|
+
old_path = line[4:].strip().strip("\"'")
|
|
165
|
+
self.idx += 1
|
|
166
|
+
continue
|
|
167
|
+
|
|
168
|
+
if line.startswith("+++ "):
|
|
169
|
+
new_path = line[4:].strip().strip("\"'")
|
|
170
|
+
self.idx += 1
|
|
171
|
+
break
|
|
172
|
+
|
|
173
|
+
if line.startswith("@@ "):
|
|
174
|
+
break
|
|
175
|
+
|
|
176
|
+
if line.startswith("index ") or line.startswith("similarity index "):
|
|
177
|
+
self.idx += 1
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
break
|
|
181
|
+
|
|
182
|
+
if not old_path and not new_path:
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
norm_old = _clean_path(old_path) if old_path else None
|
|
186
|
+
norm_new = _clean_path(new_path) if new_path else None
|
|
187
|
+
|
|
188
|
+
if norm_old == "/dev/null" or is_new_mode:
|
|
189
|
+
change_type = ChangeType.ADD
|
|
190
|
+
canonical_path = norm_new or norm_old or ""
|
|
191
|
+
elif norm_new == "/dev/null" or is_deleted_mode:
|
|
192
|
+
change_type = ChangeType.DELETE
|
|
193
|
+
canonical_path = norm_old or norm_new or ""
|
|
194
|
+
else:
|
|
195
|
+
change_type = ChangeType.MODIFY
|
|
196
|
+
canonical_path = norm_new or norm_old or ""
|
|
197
|
+
|
|
198
|
+
if not canonical_path or canonical_path == "/dev/null":
|
|
199
|
+
msg = f"Could not determine valid target file path: {old_path} -> {new_path}"
|
|
200
|
+
raise InvalidPatchFormatError(msg)
|
|
201
|
+
|
|
202
|
+
hunks: list[PatchHunk] = []
|
|
203
|
+
if not is_binary:
|
|
204
|
+
while self.idx < self.total:
|
|
205
|
+
line = self.lines[self.idx]
|
|
206
|
+
if (
|
|
207
|
+
line.startswith("diff --git")
|
|
208
|
+
or line.startswith("--- ")
|
|
209
|
+
or line.startswith("Index: ")
|
|
210
|
+
or line.startswith("Binary files ")
|
|
211
|
+
):
|
|
212
|
+
break
|
|
213
|
+
|
|
214
|
+
if line.startswith("@@ "):
|
|
215
|
+
hunk = self._parse_hunk()
|
|
216
|
+
hunks.append(hunk)
|
|
217
|
+
else:
|
|
218
|
+
if not line.strip():
|
|
219
|
+
self.idx += 1
|
|
220
|
+
continue
|
|
221
|
+
if is_mode_change or (old_path and new_path and old_path != new_path):
|
|
222
|
+
break
|
|
223
|
+
msg = (
|
|
224
|
+
f"Unexpected content before next hunk/file at line {self.idx + 1}: {line!r}"
|
|
225
|
+
)
|
|
226
|
+
raise InvalidPatchFormatError(msg)
|
|
227
|
+
|
|
228
|
+
return FileDelta(
|
|
229
|
+
path=canonical_path,
|
|
230
|
+
change_type=change_type,
|
|
231
|
+
old_path=old_path,
|
|
232
|
+
new_path=new_path,
|
|
233
|
+
hunks=tuple(hunks),
|
|
234
|
+
is_binary=is_binary,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
def _parse_hunk(self) -> PatchHunk:
|
|
238
|
+
header_line = self.lines[self.idx]
|
|
239
|
+
match = HUNK_HEADER_RE.match(header_line)
|
|
240
|
+
if not match:
|
|
241
|
+
msg = f"Malformed hunk header at line {self.idx + 1}: {header_line!r}"
|
|
242
|
+
raise InvalidPatchFormatError(msg)
|
|
243
|
+
|
|
244
|
+
old_start = int(match.group("old_start"))
|
|
245
|
+
old_lines_raw = match.group("old_lines")
|
|
246
|
+
old_lines = (
|
|
247
|
+
int(old_lines_raw) if old_lines_raw is not None else (0 if old_start == 0 else 1)
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
new_start = int(match.group("new_start"))
|
|
251
|
+
new_lines_raw = match.group("new_lines")
|
|
252
|
+
new_lines = (
|
|
253
|
+
int(new_lines_raw) if new_lines_raw is not None else (0 if new_start == 0 else 1)
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
self.idx += 1
|
|
257
|
+
|
|
258
|
+
hunk_lines: list[str] = []
|
|
259
|
+
actual_old_count = 0
|
|
260
|
+
actual_new_count = 0
|
|
261
|
+
|
|
262
|
+
while self.idx < self.total:
|
|
263
|
+
line = self.lines[self.idx]
|
|
264
|
+
|
|
265
|
+
if (
|
|
266
|
+
line.startswith("@@ ")
|
|
267
|
+
or line.startswith("diff --git")
|
|
268
|
+
or line.startswith("--- ")
|
|
269
|
+
or line.startswith("Index: ")
|
|
270
|
+
or line.startswith("Binary files ")
|
|
271
|
+
):
|
|
272
|
+
break
|
|
273
|
+
|
|
274
|
+
if line.startswith(" "):
|
|
275
|
+
hunk_lines.append(line)
|
|
276
|
+
actual_old_count += 1
|
|
277
|
+
actual_new_count += 1
|
|
278
|
+
self.idx += 1
|
|
279
|
+
elif line.startswith("-"):
|
|
280
|
+
hunk_lines.append(line)
|
|
281
|
+
actual_old_count += 1
|
|
282
|
+
self.idx += 1
|
|
283
|
+
elif line.startswith("+"):
|
|
284
|
+
hunk_lines.append(line)
|
|
285
|
+
actual_new_count += 1
|
|
286
|
+
self.idx += 1
|
|
287
|
+
elif line.startswith("\\"):
|
|
288
|
+
hunk_lines.append(line)
|
|
289
|
+
self.idx += 1
|
|
290
|
+
elif line == "":
|
|
291
|
+
if actual_old_count < old_lines or actual_new_count < new_lines:
|
|
292
|
+
hunk_lines.append(" ")
|
|
293
|
+
actual_old_count += 1
|
|
294
|
+
actual_new_count += 1
|
|
295
|
+
self.idx += 1
|
|
296
|
+
else:
|
|
297
|
+
break
|
|
298
|
+
else:
|
|
299
|
+
msg = f"Invalid line marker in hunk body at line {self.idx + 1}: {line!r}"
|
|
300
|
+
raise InvalidPatchFormatError(msg)
|
|
301
|
+
|
|
302
|
+
if actual_old_count == old_lines and actual_new_count == new_lines:
|
|
303
|
+
if self.idx < self.total and self.lines[self.idx].startswith("\\"):
|
|
304
|
+
hunk_lines.append(self.lines[self.idx])
|
|
305
|
+
self.idx += 1
|
|
306
|
+
break
|
|
307
|
+
|
|
308
|
+
if actual_old_count != old_lines or actual_new_count != new_lines:
|
|
309
|
+
counts = (
|
|
310
|
+
f"expected -{old_lines}/+{new_lines}, found -{actual_old_count}/+{actual_new_count}"
|
|
311
|
+
)
|
|
312
|
+
msg = f"Hunk line count mismatch for header '{header_line}': {counts}"
|
|
313
|
+
raise InvalidPatchFormatError(msg)
|
|
314
|
+
|
|
315
|
+
return PatchHunk(
|
|
316
|
+
old_start=old_start,
|
|
317
|
+
old_lines=old_lines,
|
|
318
|
+
new_start=new_start,
|
|
319
|
+
new_lines=new_lines,
|
|
320
|
+
header=header_line,
|
|
321
|
+
lines=tuple(hunk_lines),
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def parse_patch(raw_diff: str) -> CanonicalPatch:
|
|
326
|
+
"""Parse a unified diff string into an immutable CanonicalPatch model.
|
|
327
|
+
|
|
328
|
+
Args:
|
|
329
|
+
raw_diff: Raw unified diff string (supports CRLF and LF line endings).
|
|
330
|
+
|
|
331
|
+
Returns:
|
|
332
|
+
CanonicalPatch: Immutable representation containing parsed file deltas and hunks.
|
|
333
|
+
|
|
334
|
+
Raises:
|
|
335
|
+
InvalidPatchFormatError: If raw_diff is empty, corrupted, or violates diff syntax.
|
|
336
|
+
"""
|
|
337
|
+
parser = _UnifiedDiffParser(raw_diff)
|
|
338
|
+
return parser.parse()
|