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,503 @@
1
+ """Git boundary adapter for BlastDiff.
2
+
3
+ All subprocess calls to Git live here and translate repository state into
4
+ immutable models or plain UTF-8 strings for the pure core.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import subprocess
10
+ import tomllib
11
+ from pathlib import Path
12
+
13
+ from pydantic import BaseModel
14
+
15
+ from blastdiff.core.models import ArchRule
16
+
17
+ MAX_WORKING_FILE_BYTES = 1_048_576 # 1 MB
18
+ MAX_SOURCE_FILE_BYTES = 512_000 # 500 KB
19
+ MAX_REPO_SOURCE_FILES = 1500
20
+ MAX_COVERAGE_FILE_BYTES = 20_971_520 # 20 MB
21
+
22
+ DEFAULT_SOURCE_EXTENSIONS: tuple[str, ...] = (
23
+ ".py",
24
+ ".ts",
25
+ ".tsx",
26
+ ".js",
27
+ ".jsx",
28
+ ".mjs",
29
+ ".cjs",
30
+ ".go",
31
+ ".rs",
32
+ )
33
+
34
+ SKIP_DIR_NAMES: frozenset[str] = frozenset(
35
+ {
36
+ ".git",
37
+ ".venv",
38
+ "venv",
39
+ "node_modules",
40
+ "vendor",
41
+ "third_party",
42
+ "target",
43
+ "dist",
44
+ "build",
45
+ "__pycache__",
46
+ ".tox",
47
+ ".mypy_cache",
48
+ ".pytest_cache",
49
+ }
50
+ )
51
+
52
+ SKIP_FILE_SUFFIXES: tuple[str, ...] = (
53
+ ".min.js",
54
+ ".min.mjs",
55
+ ".min.cjs",
56
+ ".bundle.js",
57
+ )
58
+
59
+ STANDARD_COVERAGE_PATHS: tuple[str, ...] = (
60
+ "coverage.xml",
61
+ "lcov.info",
62
+ "coverage/lcov.info",
63
+ )
64
+
65
+
66
+ class GitError(RuntimeError):
67
+ """Raised when a Git command fails or a path is not a valid Git repository."""
68
+
69
+
70
+ class GitRepoInfo(BaseModel):
71
+ repo_root: str
72
+ git_dir: str
73
+ repo_name: str
74
+ branch: str
75
+ head_sha: str
76
+
77
+
78
+ def _normalize_rel_path(path_str: str) -> str:
79
+ norm = path_str.replace("\\", "/")
80
+ while norm.startswith("./"):
81
+ norm = norm[2:]
82
+ return norm.lstrip("/")
83
+
84
+
85
+ def _is_binary_bytes(raw: bytes) -> bool:
86
+ return b"\x00" in raw[:8192]
87
+
88
+
89
+ class GitAdapter:
90
+ """Thin boundary around the local Git CLI with full UTF-8 path support."""
91
+
92
+ def __init__(self, start_path: str | Path = ".") -> None:
93
+ candidate = Path(start_path).resolve()
94
+ if not candidate.exists():
95
+ raise GitError(f"Repository path does not exist: {candidate}")
96
+ search_dir = candidate.parent if candidate.is_file() else candidate
97
+
98
+ root_proc = self._run_git(
99
+ ["rev-parse", "--show-toplevel"], cwd=search_dir, check=True
100
+ )
101
+ git_dir_proc = self._run_git(
102
+ ["rev-parse", "--absolute-git-dir"], cwd=search_dir, check=True
103
+ )
104
+
105
+ self.repo_root = Path(root_proc.stdout.strip()).resolve()
106
+ self.git_dir = Path(git_dir_proc.stdout.strip()).resolve()
107
+
108
+ def _run_git(
109
+ self,
110
+ args: list[str],
111
+ cwd: Path | None = None,
112
+ check: bool = True,
113
+ ) -> subprocess.CompletedProcess[str]:
114
+ target_cwd = cwd if cwd is not None else self.repo_root
115
+ cmd = ["git", "-c", "core.quotePath=false", *args]
116
+ try:
117
+ proc = subprocess.run(
118
+ cmd,
119
+ cwd=str(target_cwd),
120
+ capture_output=True,
121
+ text=True,
122
+ encoding="utf-8",
123
+ errors="replace",
124
+ check=False,
125
+ )
126
+ except FileNotFoundError as exc:
127
+ raise GitError("Git executable was not found in PATH.") from exc
128
+ except OSError as exc:
129
+ raise GitError(f"Failed to invoke Git: {exc}") from exc
130
+
131
+ if check and proc.returncode != 0:
132
+ detail = proc.stderr.strip() or proc.stdout.strip()
133
+ raise GitError(
134
+ detail or f"Git command failed ({proc.returncode}): {' '.join(args)}"
135
+ )
136
+ return proc
137
+
138
+ def has_head(self) -> bool:
139
+ proc = self._run_git(["rev-parse", "--verify", "HEAD"], check=False)
140
+ return proc.returncode == 0
141
+
142
+ def info(self) -> GitRepoInfo:
143
+ branch_proc = self._run_git(
144
+ ["symbolic-ref", "--short", "HEAD"], check=False
145
+ )
146
+ if branch_proc.returncode == 0 and branch_proc.stdout.strip():
147
+ branch = branch_proc.stdout.strip()
148
+ else:
149
+ abbrev_proc = self._run_git(
150
+ ["rev-parse", "--abbrev-ref", "HEAD"], check=False
151
+ )
152
+ branch = (
153
+ abbrev_proc.stdout.strip()
154
+ if abbrev_proc.returncode == 0 and abbrev_proc.stdout.strip()
155
+ else "HEAD"
156
+ )
157
+
158
+ sha_proc = self._run_git(["rev-parse", "HEAD"], check=False)
159
+ head_sha = sha_proc.stdout.strip() if sha_proc.returncode == 0 else ""
160
+
161
+ return GitRepoInfo(
162
+ repo_root=str(self.repo_root),
163
+ git_dir=str(self.git_dir),
164
+ repo_name=self.repo_root.name,
165
+ branch=branch,
166
+ head_sha=head_sha,
167
+ )
168
+
169
+ def get_merge_base(self, ref_a: str, ref_b: str = "HEAD") -> str | None:
170
+ proc = self._run_git(["merge-base", ref_a, ref_b], check=False)
171
+ if proc.returncode == 0 and proc.stdout.strip():
172
+ return proc.stdout.strip()
173
+ return None
174
+
175
+ def list_recent_refs(self, limit: int = 8) -> dict[str, object]:
176
+ """List local branches and recent commits for quick base-ref switching."""
177
+ branch_proc = self._run_git(
178
+ ["for-each-ref", "--format=%(refname:short)", "refs/heads"], check=False
179
+ )
180
+ branches = [
181
+ line.strip()
182
+ for line in branch_proc.stdout.splitlines()
183
+ if line.strip()
184
+ ] if branch_proc.returncode == 0 else []
185
+
186
+ commits: list[dict[str, str]] = []
187
+ if self.has_head():
188
+ log_proc = self._run_git(
189
+ ["log", f"-n{limit}", "--format=%h\t%s"], check=False
190
+ )
191
+ if log_proc.returncode == 0:
192
+ for line in log_proc.stdout.splitlines():
193
+ if "\t" in line:
194
+ sha, subject = line.split("\t", 1)
195
+ commits.append({"sha": sha.strip(), "subject": subject.strip()[:72]})
196
+ return {"branches": branches, "recent_commits": commits}
197
+
198
+ def get_diff(
199
+ self, base_ref: str | None = None, staged: bool = False
200
+ ) -> tuple[str, str]:
201
+ """Return (raw_unified_diff, target_label)."""
202
+ if base_ref:
203
+ has_head = self.has_head()
204
+ has_working_changes = True
205
+ if has_head:
206
+ wt_proc = self._run_git(["diff", "--quiet", "HEAD"], check=False)
207
+ has_working_changes = wt_proc.returncode == 1
208
+
209
+ if has_head and not has_working_changes:
210
+ mb = self.get_merge_base(base_ref, "HEAD")
211
+ if mb is not None:
212
+ proc = self._run_git(
213
+ [
214
+ "diff",
215
+ "--unified=3",
216
+ "--no-color",
217
+ f"{base_ref}...HEAD",
218
+ ],
219
+ check=False,
220
+ )
221
+ if proc.returncode == 0:
222
+ return proc.stdout, f"{base_ref}...HEAD"
223
+
224
+ proc = self._run_git(
225
+ ["diff", "--unified=3", "--no-color", base_ref], check=True
226
+ )
227
+ return proc.stdout, f"{base_ref}..working-tree"
228
+
229
+ if staged:
230
+ proc = self._run_git(
231
+ ["diff", "--cached", "--unified=3", "--no-color"], check=True
232
+ )
233
+ return proc.stdout, "staged"
234
+
235
+ if self.has_head():
236
+ proc = self._run_git(
237
+ ["diff", "HEAD", "--unified=3", "--no-color"], check=True
238
+ )
239
+ return proc.stdout, "working-tree"
240
+
241
+ proc = self._run_git(
242
+ ["diff", "--cached", "--unified=3", "--no-color"], check=True
243
+ )
244
+ return proc.stdout, "staged"
245
+
246
+ def list_untracked_files(self) -> list[str]:
247
+ proc = self._run_git(
248
+ ["ls-files", "--others", "--exclude-standard"], check=True
249
+ )
250
+ paths = [
251
+ _normalize_rel_path(line.strip())
252
+ for line in proc.stdout.splitlines()
253
+ if line.strip()
254
+ ]
255
+ return sorted(set(paths))
256
+
257
+ def read_files_at_ref_batch(self, ref: str, rel_paths: list[str]) -> dict[str, str]:
258
+ """Read multiple files at a Git ref using a single `git cat-file --batch` process."""
259
+ if not ref or not rel_paths:
260
+ return {}
261
+ if ref == "HEAD" and not self.has_head():
262
+ return {}
263
+
264
+ unique_paths: list[str] = []
265
+ seen: set[str] = set()
266
+ for raw_path in rel_paths:
267
+ norm = _normalize_rel_path(raw_path)
268
+ if norm and norm not in seen:
269
+ seen.add(norm)
270
+ unique_paths.append(norm)
271
+
272
+ if not unique_paths:
273
+ return {}
274
+
275
+ stdin_payload = "".join(f"{ref}:{p}\n" for p in unique_paths).encode("utf-8")
276
+ try:
277
+ proc = subprocess.run(
278
+ ["git", "-c", "core.quotePath=false", "cat-file", "--batch"],
279
+ cwd=str(self.repo_root),
280
+ input=stdin_payload,
281
+ capture_output=True,
282
+ check=False,
283
+ )
284
+ except (FileNotFoundError, OSError):
285
+ return {}
286
+
287
+ if proc.returncode != 0:
288
+ return {}
289
+
290
+ out = proc.stdout
291
+ pos = 0
292
+ out_len = len(out)
293
+ results: dict[str, str] = {}
294
+
295
+ for rel_path in unique_paths:
296
+ if pos >= out_len:
297
+ break
298
+ nl = out.find(b"\n", pos)
299
+ if nl == -1:
300
+ break
301
+ header = out[pos:nl].decode("utf-8", errors="replace").strip()
302
+ pos = nl + 1
303
+
304
+ if header.endswith(" missing") or header.endswith(" ambiguous"):
305
+ continue
306
+
307
+ parts = header.rsplit(" ", 2)
308
+ if len(parts) != 3:
309
+ break
310
+ obj_type, size_str = parts[1], parts[2]
311
+ try:
312
+ size = int(size_str)
313
+ except ValueError:
314
+ break
315
+
316
+ blob = out[pos : pos + size]
317
+ pos += size
318
+ if pos < out_len and out[pos : pos + 1] == b"\n":
319
+ pos += 1
320
+
321
+ if obj_type != "blob" or size > MAX_WORKING_FILE_BYTES:
322
+ continue
323
+ if _is_binary_bytes(blob):
324
+ continue
325
+ results[rel_path] = blob.decode("utf-8", errors="replace")
326
+
327
+ return results
328
+
329
+ def read_file_at_ref(self, ref: str, rel_path: str) -> str | None:
330
+ if not ref:
331
+ return None
332
+ if ref == "HEAD" and not self.has_head():
333
+ return None
334
+ norm = _normalize_rel_path(rel_path)
335
+ proc = self._run_git(["show", f"{ref}:{norm}"], check=False)
336
+ if proc.returncode != 0:
337
+ return None
338
+ text = proc.stdout
339
+ if "\x00" in text[:8192]:
340
+ return None
341
+ if len(text.encode("utf-8", errors="ignore")) > MAX_WORKING_FILE_BYTES:
342
+ return None
343
+ return text
344
+
345
+ def read_staged_file(self, rel_path: str) -> str | None:
346
+ norm = _normalize_rel_path(rel_path)
347
+ proc = self._run_git(["show", f":{norm}"], check=False)
348
+ if proc.returncode != 0:
349
+ return None
350
+ text = proc.stdout
351
+ if "\x00" in text[:8192]:
352
+ return None
353
+ if len(text.encode("utf-8", errors="ignore")) > MAX_WORKING_FILE_BYTES:
354
+ return None
355
+ return text
356
+
357
+ def read_working_file(
358
+ self, rel_path: str, max_bytes: int = MAX_WORKING_FILE_BYTES
359
+ ) -> str | None:
360
+ norm = _normalize_rel_path(rel_path)
361
+ full_path = (self.repo_root / norm).resolve()
362
+ try:
363
+ full_path.relative_to(self.repo_root)
364
+ except ValueError:
365
+ return None
366
+
367
+ if not full_path.is_file():
368
+ return None
369
+
370
+ try:
371
+ if full_path.stat().st_size > max_bytes:
372
+ return None
373
+ raw = full_path.read_bytes()
374
+ except OSError:
375
+ return None
376
+
377
+ if _is_binary_bytes(raw):
378
+ return None
379
+ return raw.decode("utf-8", errors="replace")
380
+
381
+ def list_repo_source_files(
382
+ self,
383
+ extensions: tuple[str, ...] = DEFAULT_SOURCE_EXTENSIONS,
384
+ ) -> dict[str, str]:
385
+ tracked_proc = self._run_git(["ls-files"], check=True)
386
+ tracked = [
387
+ _normalize_rel_path(line.strip())
388
+ for line in tracked_proc.stdout.splitlines()
389
+ if line.strip()
390
+ ]
391
+ untracked = self.list_untracked_files()
392
+
393
+ lower_exts = tuple(ext.lower() for ext in extensions)
394
+ candidates = sorted(set(tracked) | set(untracked))
395
+
396
+ sources: dict[str, str] = {}
397
+ for rel_path in candidates:
398
+ if len(sources) >= MAX_REPO_SOURCE_FILES:
399
+ break
400
+ parts = Path(rel_path).parts
401
+ if any(part in SKIP_DIR_NAMES for part in parts):
402
+ continue
403
+ low_path = rel_path.lower()
404
+ if not low_path.endswith(lower_exts) or low_path.endswith(SKIP_FILE_SUFFIXES):
405
+ continue
406
+ content = self.read_working_file(
407
+ rel_path, max_bytes=MAX_SOURCE_FILE_BYTES
408
+ )
409
+ if content is None:
410
+ continue
411
+ # Skip bundled/minified JS files (very long average line length)
412
+ if low_path.endswith((".js", ".mjs", ".cjs")) and len(content) > 20_000:
413
+ line_count = content.count("\n") + 1
414
+ if (len(content) / line_count) > 400:
415
+ continue
416
+ sources[rel_path] = content
417
+ return sources
418
+
419
+ def load_arch_rules(self) -> list[ArchRule]:
420
+ config_path = self.repo_root / ".blastdiff.toml"
421
+ if not config_path.is_file():
422
+ return []
423
+ try:
424
+ raw = config_path.read_bytes()
425
+ data = tomllib.loads(raw.decode("utf-8", errors="replace"))
426
+ except (OSError, tomllib.TOMLDecodeError):
427
+ return []
428
+
429
+ arch_section = data.get("arch")
430
+ if not isinstance(arch_section, dict):
431
+ return []
432
+ raw_rules = arch_section.get("rules")
433
+ if not isinstance(raw_rules, list):
434
+ return []
435
+
436
+ rules: list[ArchRule] = []
437
+ for entry in raw_rules:
438
+ if not isinstance(entry, dict):
439
+ continue
440
+ name = entry.get("name")
441
+ source_glob = entry.get("source_glob")
442
+ forbid_import = entry.get("forbid_import")
443
+ reason = entry.get("reason", "")
444
+ if (
445
+ isinstance(name, str)
446
+ and isinstance(source_glob, str)
447
+ and isinstance(forbid_import, str)
448
+ and name
449
+ and source_glob
450
+ and forbid_import
451
+ ):
452
+ rules.append(
453
+ ArchRule(
454
+ name=name,
455
+ source_glob=source_glob,
456
+ forbid_import=forbid_import,
457
+ reason=str(reason) if reason is not None else "",
458
+ )
459
+ )
460
+ return rules
461
+
462
+ def auto_discover_coverage(
463
+ self, explicit_path: str | Path | None = None
464
+ ) -> tuple[str | None, str | None]:
465
+ """Return (source_label, content) from an explicit or standard coverage file."""
466
+ if explicit_path is not None:
467
+ raw_path = Path(explicit_path)
468
+ if raw_path.is_absolute():
469
+ target = raw_path
470
+ else:
471
+ repo_candidate = self.repo_root / raw_path
472
+ target = repo_candidate if repo_candidate.is_file() else raw_path
473
+ if not target.is_file():
474
+ return None, None
475
+ content = self._read_coverage_file(target)
476
+ if content is None:
477
+ return None, None
478
+ try:
479
+ label = _normalize_rel_path(
480
+ str(target.resolve().relative_to(self.repo_root))
481
+ )
482
+ except ValueError:
483
+ label = str(target)
484
+ return label, content
485
+
486
+ for rel in STANDARD_COVERAGE_PATHS:
487
+ candidate = self.repo_root / rel
488
+ if candidate.is_file():
489
+ content = self._read_coverage_file(candidate)
490
+ if content is not None:
491
+ return rel, content
492
+ return None, None
493
+
494
+ def _read_coverage_file(self, path: Path) -> str | None:
495
+ try:
496
+ if path.stat().st_size > MAX_COVERAGE_FILE_BYTES:
497
+ return None
498
+ raw = path.read_bytes()
499
+ except OSError:
500
+ return None
501
+ if _is_binary_bytes(raw):
502
+ return None
503
+ return raw.decode("utf-8", errors="replace")