blastdiff 0.1.0__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.
@@ -0,0 +1,368 @@
1
+ """Unified Git diff parser and fingerprint helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+
9
+ from blastdiff.core.languages.base import detect_language
10
+ from blastdiff.core.models import DiffLine, FileReview, Hunk
11
+
12
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$")
13
+
14
+ _C_ESCAPES: dict[str, int] = {
15
+ "a": 0x07,
16
+ "b": 0x08,
17
+ "f": 0x0C,
18
+ "n": 0x0A,
19
+ "r": 0x0D,
20
+ "t": 0x09,
21
+ "v": 0x0B,
22
+ "\\": ord("\\"),
23
+ '"': ord('"'),
24
+ }
25
+
26
+
27
+ def _unquote_git_path(raw: str) -> str:
28
+ """Decode Git C-quoted UTF-8 paths (including octal escapes) to normalized POSIX paths."""
29
+ text = raw.strip()
30
+ if len(text) >= 2 and text[0] == '"' and text[-1] == '"':
31
+ inner = text[1:-1]
32
+ buf = bytearray()
33
+ i = 0
34
+ n = len(inner)
35
+ while i < n:
36
+ ch = inner[i]
37
+ if ch == "\\" and i + 1 < n:
38
+ nxt = inner[i + 1]
39
+ if "0" <= nxt <= "7":
40
+ oct_digits = inner[i + 1 : i + 4]
41
+ valid_oct = ""
42
+ for d in oct_digits:
43
+ if "0" <= d <= "7":
44
+ valid_oct += d
45
+ else:
46
+ break
47
+ buf.append(int(valid_oct, 8) & 0xFF)
48
+ i += 1 + len(valid_oct)
49
+ continue
50
+ if nxt in _C_ESCAPES:
51
+ buf.append(_C_ESCAPES[nxt])
52
+ i += 2
53
+ continue
54
+ buf.extend(nxt.encode("utf-8", errors="replace"))
55
+ i += 2
56
+ continue
57
+ buf.extend(ch.encode("utf-8", errors="replace"))
58
+ i += 1
59
+ text = buf.decode("utf-8", errors="replace")
60
+ return text.replace("\\", "/")
61
+
62
+
63
+ def _strip_diff_prefix(path: str, prefix: str) -> str:
64
+ if path.startswith(prefix):
65
+ return path[len(prefix) :]
66
+ return path
67
+
68
+
69
+ def _parse_diff_git_header(line: str) -> tuple[str, str]:
70
+ """Extract (old_path, new_path) from a `diff --git ...` header line."""
71
+ rest = line[len("diff --git ") :].strip()
72
+ if not rest:
73
+ return "", ""
74
+
75
+ # Parse quoted tokens if present
76
+ if rest.startswith('"'):
77
+ i = 1
78
+ n = len(rest)
79
+ while i < n:
80
+ if rest[i] == "\\" and i + 1 < n:
81
+ i += 2
82
+ continue
83
+ if rest[i] == '"':
84
+ i += 1
85
+ break
86
+ i += 1
87
+ left = _unquote_git_path(rest[:i])
88
+ right = _unquote_git_path(rest[i:].strip())
89
+ return _strip_diff_prefix(left, "a/"), _strip_diff_prefix(right, "b/")
90
+
91
+ # Check if right side is quoted: `a/foo "b/bar"`
92
+ quoted_b = rest.find(' "b/')
93
+ if quoted_b != -1:
94
+ left = _unquote_git_path(rest[:quoted_b])
95
+ right = _unquote_git_path(rest[quoted_b + 1 :])
96
+ return _strip_diff_prefix(left, "a/"), _strip_diff_prefix(right, "b/")
97
+
98
+ # Unquoted `a/... b/...`
99
+ marker = " b/"
100
+ idx = rest.find(marker)
101
+ if idx != -1:
102
+ # Prefer a split where old_path == new_path when paths contain spaces
103
+ start = 0
104
+ best_idx = idx
105
+ while True:
106
+ pos = rest.find(marker, start)
107
+ if pos == -1:
108
+ break
109
+ cand_a = _strip_diff_prefix(rest[:pos], "a/")
110
+ cand_b = _strip_diff_prefix(rest[pos + 1 :], "b/")
111
+ if cand_a == cand_b:
112
+ best_idx = pos
113
+ break
114
+ start = pos + 1
115
+ left = _unquote_git_path(rest[:best_idx])
116
+ right = _unquote_git_path(rest[best_idx + 1 :])
117
+ return _strip_diff_prefix(left, "a/"), _strip_diff_prefix(right, "b/")
118
+
119
+ parts = rest.split(" ", 1)
120
+ if len(parts) == 2:
121
+ return (
122
+ _strip_diff_prefix(_unquote_git_path(parts[0]), "a/"),
123
+ _strip_diff_prefix(_unquote_git_path(parts[1]), "b/"),
124
+ )
125
+ p = _strip_diff_prefix(_unquote_git_path(rest), "a/")
126
+ return p, p
127
+
128
+
129
+ def _compute_hunk_fingerprint(lines: list[DiffLine]) -> str:
130
+ """Compute stable 12-char SHA-256 fingerprint over normalized +/- lines."""
131
+ normalized: list[str] = []
132
+ for dl in lines:
133
+ if dl.kind == "add":
134
+ normalized.append("+" + " ".join(dl.content.split()))
135
+ elif dl.kind == "del":
136
+ normalized.append("-" + " ".join(dl.content.split()))
137
+ payload = "\n".join(normalized).encode("utf-8", errors="replace")
138
+ return hashlib.sha256(payload).hexdigest()[:12]
139
+
140
+
141
+ def parse_unified_diff(raw_diff: str) -> list[FileReview]:
142
+ """Parse `git diff --unified=3 --no-color` output into FileReview models."""
143
+ if not raw_diff or not raw_diff.strip():
144
+ return []
145
+
146
+ text = raw_diff.replace("\r\n", "\n").replace("\r", "\n")
147
+ raw_lines = text.split("\n")
148
+
149
+ reviews: list[FileReview] = []
150
+ i = 0
151
+ total_lines = len(raw_lines)
152
+
153
+ while i < total_lines:
154
+ line = raw_lines[i]
155
+ if not line.startswith("diff --git "):
156
+ i += 1
157
+ continue
158
+
159
+ header_old, header_new = _parse_diff_git_header(line)
160
+ old_path: str | None = header_old or None
161
+ new_path: str = header_new or header_old
162
+ status: str = "modified"
163
+ is_binary = False
164
+ hunks: list[Hunk] = []
165
+ additions = 0
166
+ deletions = 0
167
+
168
+ i += 1
169
+ # Parse extended file headers before first hunk or next diff
170
+ while i < total_lines and not raw_lines[i].startswith("diff --git "):
171
+ cur = raw_lines[i]
172
+ if cur.startswith("@@ "):
173
+ break
174
+ if cur.startswith("new file mode "):
175
+ status = "added"
176
+ elif cur.startswith("deleted file mode "):
177
+ status = "deleted"
178
+ elif cur.startswith("rename from "):
179
+ status = "renamed"
180
+ old_path = _unquote_git_path(cur[len("rename from ") :])
181
+ elif cur.startswith("rename to "):
182
+ status = "renamed"
183
+ new_path = _unquote_git_path(cur[len("rename to ") :])
184
+ elif cur.startswith("--- "):
185
+ raw_old = cur[4:].split("\t", 1)[0].strip()
186
+ if raw_old == "/dev/null":
187
+ status = "added"
188
+ old_path = None
189
+ else:
190
+ old_path = _strip_diff_prefix(_unquote_git_path(raw_old), "a/")
191
+ elif cur.startswith("+++ "):
192
+ raw_new = cur[4:].split("\t", 1)[0].strip()
193
+ if raw_new == "/dev/null":
194
+ status = "deleted"
195
+ else:
196
+ new_path = _strip_diff_prefix(_unquote_git_path(raw_new), "b/")
197
+ elif cur.startswith("Binary files ") or cur.startswith("GIT binary patch"):
198
+ is_binary = True
199
+ i += 1
200
+
201
+ if status == "deleted" and old_path:
202
+ file_path = old_path
203
+ else:
204
+ file_path = new_path or old_path or ""
205
+
206
+ # Parse hunks for non-binary files
207
+ if not is_binary:
208
+ while i < total_lines and not raw_lines[i].startswith("diff --git "):
209
+ cur = raw_lines[i]
210
+ match = _HUNK_HEADER_RE.match(cur)
211
+ if not match:
212
+ i += 1
213
+ continue
214
+
215
+ old_start = int(match.group(1))
216
+ old_count = int(match.group(2)) if match.group(2) is not None else 1
217
+ new_start = int(match.group(3))
218
+ new_count = int(match.group(4)) if match.group(4) is not None else 1
219
+ header_ctx = match.group(5).strip()
220
+
221
+ old_cur = old_start
222
+ new_cur = new_start
223
+ diff_lines: list[DiffLine] = []
224
+ i += 1
225
+
226
+ while i < total_lines:
227
+ hline = raw_lines[i]
228
+ if hline.startswith("diff --git ") or _HUNK_HEADER_RE.match(hline):
229
+ break
230
+ if hline.startswith("\"):
231
+ i += 1
232
+ continue
233
+ if hline.startswith("+"):
234
+ diff_lines.append(
235
+ DiffLine(
236
+ kind="add",
237
+ old_lineno=None,
238
+ new_lineno=new_cur,
239
+ content=hline[1:],
240
+ )
241
+ )
242
+ new_cur += 1
243
+ additions += 1
244
+ elif hline.startswith("-"):
245
+ diff_lines.append(
246
+ DiffLine(
247
+ kind="del",
248
+ old_lineno=old_cur,
249
+ new_lineno=None,
250
+ content=hline[1:],
251
+ )
252
+ )
253
+ old_cur += 1
254
+ deletions += 1
255
+ elif hline.startswith(" "):
256
+ diff_lines.append(
257
+ DiffLine(
258
+ kind="ctx",
259
+ old_lineno=old_cur,
260
+ new_lineno=new_cur,
261
+ content=hline[1:],
262
+ )
263
+ )
264
+ old_cur += 1
265
+ new_cur += 1
266
+ elif hline == "":
267
+ # Trailing empty line at EOF of raw_diff should not become a fake context line
268
+ if i == total_lines - 1:
269
+ i += 1
270
+ break
271
+ if old_cur < old_start + old_count and new_cur < new_start + new_count:
272
+ diff_lines.append(
273
+ DiffLine(
274
+ kind="ctx",
275
+ old_lineno=old_cur,
276
+ new_lineno=new_cur,
277
+ content="",
278
+ )
279
+ )
280
+ old_cur += 1
281
+ new_cur += 1
282
+ i += 1
283
+
284
+ hunk_idx = len(hunks)
285
+ hunks.append(
286
+ Hunk(
287
+ id=f"{file_path}:{hunk_idx}",
288
+ file_path=file_path,
289
+ old_start=old_start,
290
+ old_count=old_count,
291
+ new_start=new_start,
292
+ new_count=new_count,
293
+ header=header_ctx,
294
+ fingerprint=_compute_hunk_fingerprint(diff_lines),
295
+ lines=diff_lines,
296
+ )
297
+ )
298
+ else:
299
+ # Skip remaining lines of binary section
300
+ while i < total_lines and not raw_lines[i].startswith("diff --git "):
301
+ i += 1
302
+
303
+ if status != "renamed" and old_path == file_path:
304
+ recorded_old = None
305
+ else:
306
+ recorded_old = old_path if status == "renamed" else None
307
+
308
+ reviews.append(
309
+ FileReview(
310
+ path=file_path,
311
+ old_path=recorded_old,
312
+ status=status, # type: ignore[arg-type]
313
+ language=detect_language(file_path),
314
+ additions=additions,
315
+ deletions=deletions,
316
+ hunks=hunks,
317
+ )
318
+ )
319
+
320
+ return reviews
321
+
322
+
323
+ def build_untracked_file_review(rel_path: str, content: str) -> FileReview:
324
+ """Convert a newly created untracked text file into a single-hunk FileReview."""
325
+ norm_path = rel_path.replace("\\", "/").lstrip("./")
326
+ normalized_content = content.replace("\r\n", "\n").replace("\r", "\n")
327
+ raw_lines = normalized_content.splitlines()
328
+
329
+ diff_lines = [
330
+ DiffLine(kind="add", old_lineno=None, new_lineno=idx, content=line)
331
+ for idx, line in enumerate(raw_lines, start=1)
332
+ ]
333
+
334
+ hunks: list[Hunk] = []
335
+ if diff_lines:
336
+ hunks.append(
337
+ Hunk(
338
+ id=f"{norm_path}:0",
339
+ file_path=norm_path,
340
+ old_start=0,
341
+ old_count=0,
342
+ new_start=1,
343
+ new_count=len(diff_lines),
344
+ header="",
345
+ fingerprint=_compute_hunk_fingerprint(diff_lines),
346
+ lines=diff_lines,
347
+ )
348
+ )
349
+
350
+ return FileReview(
351
+ path=norm_path,
352
+ old_path=None,
353
+ status="added",
354
+ language=detect_language(norm_path),
355
+ additions=len(diff_lines),
356
+ deletions=0,
357
+ hunks=hunks,
358
+ )
359
+
360
+
361
+ def compute_diff_fingerprint(files: list[FileReview]) -> str:
362
+ """Compute stable 16-char SHA-256 fingerprint across all files and hunks."""
363
+ canonical = sorted(
364
+ (f.path, f.status, [h.fingerprint for h in f.hunks])
365
+ for f in files
366
+ )
367
+ payload = json.dumps(canonical, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
368
+ return hashlib.sha256(payload).hexdigest()[:16]
@@ -0,0 +1,17 @@
1
+ """Language analyzer exports for BlastDiff core."""
2
+
3
+ from blastdiff.core.languages.base import (
4
+ LanguageAnalyzer,
5
+ detect_language,
6
+ get_analyzer_for_path,
7
+ )
8
+ from blastdiff.core.languages.python_lang import PythonAnalyzer
9
+ from blastdiff.core.languages.ts_lang import TypeScriptAnalyzer
10
+
11
+ __all__ = [
12
+ "LanguageAnalyzer",
13
+ "PythonAnalyzer",
14
+ "TypeScriptAnalyzer",
15
+ "detect_language",
16
+ "get_analyzer_for_path",
17
+ ]
@@ -0,0 +1,111 @@
1
+ """Language detection and analyzer protocol for BlastDiff core."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import OrderedDict
6
+ import hashlib
7
+ from pathlib import PurePosixPath
8
+ from typing import Protocol
9
+
10
+ from blastdiff.core.models import FileSymbols
11
+
12
+ _EXT_TO_LANGUAGE: dict[str, str] = {
13
+ ".py": "python",
14
+ ".pyi": "python",
15
+ ".ts": "typescript",
16
+ ".tsx": "typescript",
17
+ ".mts": "typescript",
18
+ ".cts": "typescript",
19
+ ".js": "javascript",
20
+ ".jsx": "javascript",
21
+ ".mjs": "javascript",
22
+ ".cjs": "javascript",
23
+ ".json": "json",
24
+ ".jsonc": "json",
25
+ ".yaml": "yaml",
26
+ ".yml": "yaml",
27
+ ".toml": "toml",
28
+ ".md": "markdown",
29
+ ".markdown": "markdown",
30
+ ".mdx": "markdown",
31
+ ".html": "html",
32
+ ".htm": "html",
33
+ ".css": "css",
34
+ ".scss": "css",
35
+ ".less": "css",
36
+ ".go": "go",
37
+ ".rs": "rust",
38
+ }
39
+
40
+
41
+ class LanguageAnalyzer(Protocol):
42
+ """Protocol implemented by deterministic AST language analyzers."""
43
+
44
+ language: str
45
+ extensions: tuple[str, ...]
46
+
47
+ def analyze_file(self, file_path: str, source: str) -> FileSymbols:
48
+ """Extract symbols, imports, and call sites from source text."""
49
+ ...
50
+
51
+
52
+ def detect_language(file_path: str) -> str:
53
+ """Detect normalized language identifier from a repository-relative path."""
54
+ norm = file_path.replace("\\", "/")
55
+ suffix = PurePosixPath(norm).suffix.lower()
56
+ return _EXT_TO_LANGUAGE.get(suffix, "text")
57
+
58
+
59
+ _ANALYZERS_CACHE: tuple[LanguageAnalyzer, ...] | None = None
60
+
61
+
62
+ def _get_registered_analyzers() -> tuple[LanguageAnalyzer, ...]:
63
+ global _ANALYZERS_CACHE
64
+ if _ANALYZERS_CACHE is None:
65
+ from blastdiff.core.languages.go_lang import GoAnalyzer
66
+ from blastdiff.core.languages.python_lang import PythonAnalyzer
67
+ from blastdiff.core.languages.rust_lang import RustAnalyzer
68
+ from blastdiff.core.languages.ts_lang import TypeScriptAnalyzer
69
+
70
+ _ANALYZERS_CACHE = (
71
+ PythonAnalyzer(),
72
+ TypeScriptAnalyzer(),
73
+ GoAnalyzer(),
74
+ RustAnalyzer(),
75
+ )
76
+ return _ANALYZERS_CACHE
77
+
78
+
79
+ def get_analyzer_for_path(file_path: str) -> LanguageAnalyzer | None:
80
+ """Return a matching LanguageAnalyzer for the file extension, or None."""
81
+ norm = file_path.replace("\\", "/")
82
+ suffix = PurePosixPath(norm).suffix.lower()
83
+ if not suffix:
84
+ return None
85
+ for analyzer in _get_registered_analyzers():
86
+ if suffix in analyzer.extensions:
87
+ return analyzer
88
+ return None
89
+
90
+
91
+ _MAX_SYMBOL_CACHE_ENTRIES = 4096
92
+ _FILE_SYMBOLS_CACHE: OrderedDict[tuple[str, str], FileSymbols] = OrderedDict()
93
+
94
+
95
+ def analyze_file_cached(file_path: str, source: str) -> FileSymbols | None:
96
+ """Parse a file with its LanguageAnalyzer using an LRU content-hash cache."""
97
+ analyzer = get_analyzer_for_path(file_path)
98
+ if analyzer is None:
99
+ return None
100
+ norm = file_path.replace("\\", "/")
101
+ content_hash = hashlib.sha256(source.encode("utf-8", errors="replace")).hexdigest()
102
+ key = (norm, content_hash)
103
+ cached = _FILE_SYMBOLS_CACHE.get(key)
104
+ if cached is not None:
105
+ _FILE_SYMBOLS_CACHE.move_to_end(key)
106
+ return cached
107
+ parsed = analyzer.analyze_file(norm, source)
108
+ _FILE_SYMBOLS_CACHE[key] = parsed
109
+ if len(_FILE_SYMBOLS_CACHE) > _MAX_SYMBOL_CACHE_ENTRIES:
110
+ _FILE_SYMBOLS_CACHE.popitem(last=False)
111
+ return parsed