-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpatch_processor.py
347 lines (285 loc) · 10.8 KB
/
patch_processor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
from dataclasses import dataclass
from pathlib import Path
import re
from typing import Optional, Tuple, List
from config import Config
import logging
@dataclass
class FileChange:
file_path: str
changes: str
language: str
@dataclass
class PatchInfo:
repo_owner: str
repo_name: str
commit_id: str
file_changes: List[FileChange]
class PatchProcessor:
def __init__(self, config: Config):
self.config = config
def get_language_from_file(self, file_path: str) -> Optional[str]:
"""Determine programming language from file extension."""
ext_map = {
# Python
".py": "python",
".pyi": "python",
".pyx": "python",
".pyw": "python",
# JavaScript/TypeScript
".js": "javascript",
".jsx": "javascript",
".ts": "typescript",
".tsx": "typescript",
".mjs": "javascript",
".cjs": "javascript",
# Java
".java": "java",
".jav": "java",
# C/C++
".cpp": "cpp",
".hpp": "cpp",
".cc": "cpp",
".cxx": "cpp",
".c++": "cpp",
".h": "cpp",
".hh": "cpp",
".hxx": "cpp",
".h++": "cpp",
".c": "c",
# C#
".cs": "csharp",
# Ruby
".rb": "ruby",
".rbw": "ruby",
".rake": "ruby",
".gemspec": "ruby",
# PHP
".php": "php",
".phtml": "php",
".php3": "php",
".php4": "php",
".php5": "php",
# Go
".go": "go",
# Rust
".rs": "rust",
# Swift
".swift": "swift",
# Kotlin
".kt": "kotlin",
".kts": "kotlin",
# Scala
".scala": "scala",
".sc": "scala",
# HTML/CSS
".html": "html",
".htm": "html",
".xhtml": "html",
".css": "css",
".scss": "scss",
".sass": "sass",
".less": "less",
# Shell scripting
".sh": "shell",
".bash": "shell",
".zsh": "shell",
".fish": "shell",
# PowerShell
".ps1": "powershell",
".psm1": "powershell",
".psd1": "powershell",
# Perl
".pl": "perl",
".pm": "perl",
".t": "perl",
# R
".r": "r",
".R": "r",
".rmd": "r",
# Lua
".lua": "lua",
# Haskell
".hs": "haskell",
".lhs": "haskell",
# Julia
".jl": "julia",
# Dart
".dart": "dart",
# Visual Basic
".vb": "vb",
".bas": "vb",
".vbs": "vb",
# MATLAB
".m": "matlab",
".mat": "matlab",
# Assembly
".asm": "assembly",
".s": "assembly",
# SQL
".sql": "sql",
# Markdown
".md": "markdown",
".markdown": "markdown",
# XML
".xml": "xml",
".xsl": "xml",
".xsd": "xml",
# JSON
".json": "json",
# YAML
".yml": "yaml",
".yaml": "yaml",
# Protocol Buffers
".proto": "protobuf",
# Groovy
".groovy": "groovy",
".gvy": "groovy",
# Objective-C
".m": "objectivec",
".mm": "objectivec",
# F#
".fs": "fsharp",
".fsi": "fsharp",
".fsx": "fsharp",
# Clojure
".clj": "clojure",
".cljs": "clojure",
".cljc": "clojure",
# Elixir
".ex": "elixir",
".exs": "elixir",
# Erlang
".erl": "erlang",
".hrl": "erlang",
}
ext = Path(file_path).suffix.lower()
return ext_map.get(ext)
def process_patch(self, patch_file: Path) -> Optional[PatchInfo]:
"""Process a patch file and return relevant information if valid."""
try:
owner, name, commit = self.parse_patch_filename(patch_file.name)
with open(patch_file) as f:
content = f.read()
if not content.strip():
return None
# Parse the diff to get modified files
file_changes = []
current_file = None
changes = []
for line in content.split('\n'):
if line.startswith('diff --git'):
if current_file:
language = self.get_language_from_file(current_file)
if language: # Only add if we recognize the language
file_changes.append(FileChange(
file_path=current_file,
changes='\n'.join(changes),
language=language
))
current_file = line.split()[-1][2:] # Remove a/ prefix
changes = []
elif current_file and line.startswith(('+', '-')):
changes.append(line)
# Add the last file
if current_file:
language = self.get_language_from_file(current_file)
if language:
file_changes.append(FileChange(
file_path=current_file,
changes='\n'.join(changes),
language=language
))
# Skip if no valid programming files were found
if not file_changes:
return None
# Group files by language
language_groups = {}
for fc in file_changes:
if fc.language not in language_groups:
language_groups[fc.language] = []
language_groups[fc.language].append(fc)
# Create patch info objects for each language group
patch_infos = []
for language, files in language_groups.items():
patch_infos.append(PatchInfo(
repo_owner=owner,
repo_name=name,
commit_id=commit,
file_changes=files
))
# Return the first patch info - we'll process one language at a time
return patch_infos[0] if patch_infos else None
except Exception as e:
logging.error(f"Error processing patch {patch_file}: {e}")
return None
def parse_patch_filename(self, filename: str) -> Tuple[str, str, str]:
"""Extract repository and commit information from patch filename."""
pattern = r"github\.com_(.+?)_(.+?)_([a-f0-9]+)\.patch"
match = re.match(pattern, filename)
if not match:
raise ValueError(f"Invalid patch filename format: {filename}")
owner, name, commit = match.groups()
owner = owner.replace("_", "/")
return (owner, name, commit)
def inspect_patch_content(self, patch_file: Path) -> Optional[dict]:
"""Inspect patch content and return detailed information about the changes."""
try:
with open(patch_file) as f:
content = f.read()
if not content.strip():
logging.warning(f"Empty patch file: {patch_file}")
return None
patch_info = {
'files': [],
'stats': {
'total_lines': len(content.splitlines()),
'additions': 0,
'deletions': 0
}
}
current_file = None
current_changes = []
header_lines = []
for line in content.split('\n'):
if line.startswith('diff --git'):
if current_file:
patch_info['files'].append({
'file': current_file,
'changes': '\n'.join(current_changes),
'header': '\n'.join(header_lines)
})
current_file = line.split()[-1][2:] # Remove a/ prefix
current_changes = []
header_lines = [line]
elif line.startswith('+++') or line.startswith('---') or line.startswith('@@'):
if current_file:
header_lines.append(line)
elif current_file:
if line.startswith('+'):
patch_info['stats']['additions'] += 1
current_changes.append(line)
elif line.startswith('-'):
patch_info['stats']['deletions'] += 1
current_changes.append(line)
else:
current_changes.append(line)
if current_file:
patch_info['files'].append({
'file': current_file,
'changes': '\n'.join(current_changes),
'header': '\n'.join(header_lines)
})
logging.info(f"Patch analysis for {patch_file}:")
logging.info(f" Total files modified: {len(patch_info['files'])}")
logging.info(f" Total lines: {patch_info['stats']['total_lines']}")
logging.info(f" Additions: {patch_info['stats']['additions']}")
logging.info(f" Deletions: {patch_info['stats']['deletions']}")
for file_info in patch_info['files']:
logging.info(f" File: {file_info['file']}")
logging.info(f" Header:\n{file_info['header']}")
logging.info(f" Changes:\n{file_info['changes']}")
return patch_info
except Exception as e:
logging.error(f"Error inspecting patch {patch_file}: {e}", exc_info=True)
return None