diffdesk 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.
Files changed (59) hide show
  1. diffdesk/__init__.py +3 -0
  2. diffdesk/agent.py +414 -0
  3. diffdesk/agent_guide.md +112 -0
  4. diffdesk/cli.py +329 -0
  5. diffdesk/config.py +130 -0
  6. diffdesk/gitio.py +391 -0
  7. diffdesk/index.py +635 -0
  8. diffdesk/mcp.py +472 -0
  9. diffdesk/server.py +750 -0
  10. diffdesk/static/app.js +402 -0
  11. diffdesk/static/index.html +129 -0
  12. diffdesk/static/js/api.js +58 -0
  13. diffdesk/static/js/boot.js +12 -0
  14. diffdesk/static/js/diffview.js +359 -0
  15. diffdesk/static/js/dom.js +82 -0
  16. diffdesk/static/js/editor-cm.js +225 -0
  17. diffdesk/static/js/editor-monaco.js +116 -0
  18. diffdesk/static/js/flow.js +227 -0
  19. diffdesk/static/js/hunks.js +40 -0
  20. diffdesk/static/js/markdown.js +102 -0
  21. diffdesk/static/js/settings.js +228 -0
  22. diffdesk/static/js/subject.js +127 -0
  23. diffdesk/static/js/tree.js +492 -0
  24. diffdesk/static/js/treemap.js +217 -0
  25. diffdesk/static/style.css +508 -0
  26. diffdesk/static/vendor/LICENSES.txt +603 -0
  27. diffdesk/static/vendor/codemirror.js +24 -0
  28. diffdesk/static/vendor/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  29. diffdesk/static/vendor/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  30. diffdesk/static/vendor/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  31. diffdesk/static/vendor/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  32. diffdesk/static/vendor/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  33. diffdesk/static/vendor/fonts/KaTeX_Main-Bold.woff2 +0 -0
  34. diffdesk/static/vendor/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  35. diffdesk/static/vendor/fonts/KaTeX_Main-Italic.woff2 +0 -0
  36. diffdesk/static/vendor/fonts/KaTeX_Main-Regular.woff2 +0 -0
  37. diffdesk/static/vendor/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  38. diffdesk/static/vendor/fonts/KaTeX_Math-Italic.woff2 +0 -0
  39. diffdesk/static/vendor/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  40. diffdesk/static/vendor/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  41. diffdesk/static/vendor/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  42. diffdesk/static/vendor/fonts/KaTeX_Script-Regular.woff2 +0 -0
  43. diffdesk/static/vendor/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  44. diffdesk/static/vendor/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  45. diffdesk/static/vendor/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  46. diffdesk/static/vendor/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  47. diffdesk/static/vendor/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  48. diffdesk/static/vendor/fonts/OFL.txt +102 -0
  49. diffdesk/static/vendor/katex.css +2 -0
  50. diffdesk/static/vendor/katex.js +258 -0
  51. diffdesk/static/vendor/marked.js +72 -0
  52. diffdesk/subject.schema.json +59 -0
  53. diffdesk-0.1.0.dist-info/METADATA +520 -0
  54. diffdesk-0.1.0.dist-info/RECORD +59 -0
  55. diffdesk-0.1.0.dist-info/WHEEL +4 -0
  56. diffdesk-0.1.0.dist-info/entry_points.txt +2 -0
  57. diffdesk-0.1.0.dist-info/licenses/LICENSE +21 -0
  58. diffdesk-0.1.0.dist-info/licenses/src/diffdesk/static/vendor/LICENSES.txt +603 -0
  59. diffdesk-0.1.0.dist-info/licenses/src/diffdesk/static/vendor/fonts/OFL.txt +102 -0
diffdesk/index.py ADDED
@@ -0,0 +1,635 @@
1
+ """Subject index of one review root.
2
+
3
+ The index keeps every parsed subject file keyed by its ``mtime_ns`` and
4
+ size, and parses a file again only when one of them changes. Review status
5
+ comes from ``reviews.json``, the edit flag from the ``edits`` folder, and
6
+ line counts from ``git diff-tree --numstat``, cached on disk in
7
+ ``<cache>/numstat.json`` for diffs between two full commit IDs.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ import re
16
+ import stat
17
+ import tempfile
18
+ import threading
19
+ from collections.abc import Iterable
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from . import gitio
25
+ from .config import Config
26
+ from .gitio import GitError, InvalidInput, Numstat
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+ ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
31
+ STATUSES = ("pending", "accepted", "rejected", "change")
32
+ VERDICT_STATUS = {"accept": "accepted", "reject": "rejected", "change": "change"}
33
+ DEFAULT_PACKAGE = "default"
34
+ NO_REPO_BRANCH = "(no repo)"
35
+ DETACHED_BRANCH = "HEAD"
36
+ NUMSTAT_FORMAT = 1
37
+
38
+ Key = tuple[str, str]
39
+
40
+ # Read once at import, while only one thread runs: os.umask can only be read
41
+ # by setting it.
42
+ _UMASK = os.umask(0)
43
+ os.umask(_UMASK)
44
+
45
+
46
+ class NotFound(LookupError):
47
+ """No subject, file or endpoint matches the request."""
48
+
49
+
50
+ def check_name(value: Any, what: str) -> str:
51
+ """Return `value` if it is a safe subject ID or package name.
52
+
53
+ Parameters
54
+ ----------
55
+ value : Any
56
+ Value from a subject file or a request.
57
+ what : str
58
+ Name of the value for the error message.
59
+
60
+ Returns
61
+ -------
62
+ str
63
+ The unchanged value.
64
+
65
+ Raises
66
+ ------
67
+ InvalidInput
68
+ If `value` is not letters, digits, ``.``, ``_`` and ``-`` that start
69
+ with a letter or digit, or if it contains ``..``.
70
+ """
71
+ if not isinstance(value, str) or not ID_PATTERN.fullmatch(value) or ".." in value:
72
+ raise InvalidInput(f"Invalid {what}: {value!r}")
73
+ return value
74
+
75
+
76
+ def write_atomic(path: Path, data: bytes) -> None:
77
+ """Write `data` to `path` through a temporary file and ``os.replace``.
78
+
79
+ The file keeps its permission bits if it exists. A new file gets
80
+ ``0o666`` minus the umask, like a file made with ``open()``.
81
+ """
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
84
+ try:
85
+ with os.fdopen(fd, "wb") as fh:
86
+ fh.write(data)
87
+ try:
88
+ mode = stat.S_IMODE(path.stat().st_mode)
89
+ except FileNotFoundError:
90
+ mode = 0o666 & ~_UMASK
91
+ os.chmod(tmp, mode)
92
+ os.replace(tmp, path)
93
+ except BaseException:
94
+ Path(tmp).unlink(missing_ok=True)
95
+ raise
96
+
97
+
98
+ def natural_key(text: str) -> tuple[tuple[int, int, str], ...]:
99
+ """Sort key that compares runs of digits as numbers (``SB-2`` before ``SB-12``)."""
100
+ return tuple(
101
+ (0, int(part), "") if part.isdigit() else (1, 0, part)
102
+ for part in re.split(r"(\d+)", text)
103
+ if part
104
+ )
105
+
106
+
107
+ @dataclass
108
+ class Subject:
109
+ """The fields of one subject file that the index needs.
110
+
111
+ `branch` is the `branch` field of the file, or the branch resolved by
112
+ the index (see `Index`).
113
+ """
114
+
115
+ source: Path
116
+ package: str
117
+ id: str
118
+ title: str
119
+ branch_field: str | None
120
+ repo: str | None
121
+ base: str | None
122
+ head: str | None
123
+ files: list[str]
124
+ order: float | None
125
+ depends_on: list[str]
126
+ extra: dict[str, Any]
127
+ search: str
128
+ branch: str = ""
129
+
130
+ @property
131
+ def key(self) -> Key:
132
+ """``(package, id)``, unique in one review root."""
133
+ return (self.package, self.id)
134
+
135
+ @property
136
+ def has_diff(self) -> bool:
137
+ """`True` if the subject has a repository, a base and a head."""
138
+ return self.repo is not None and self.base is not None and self.head is not None
139
+
140
+
141
+ def parse_subject(path: Path, default_package: str) -> Subject:
142
+ """Read one subject file.
143
+
144
+ Parameters
145
+ ----------
146
+ path : Path
147
+ The JSON file.
148
+ default_package : str
149
+ Package if the file has no ``package`` field: the first folder below
150
+ the subjects folder, or ``DEFAULT_PACKAGE`` for a file directly in it.
151
+
152
+ Returns
153
+ -------
154
+ Subject
155
+ The parsed subject.
156
+
157
+ Raises
158
+ ------
159
+ OSError
160
+ If the file cannot be read.
161
+ ValueError
162
+ If the file is not a JSON object, or a field has a value that the
163
+ index cannot use (`InvalidInput` is a subclass).
164
+ """
165
+ data = json.loads(path.read_bytes())
166
+ if not isinstance(data, dict):
167
+ raise ValueError("top-level value is not an object")
168
+ sid = check_name(data.get("id", path.stem), "subject ID")
169
+ package = check_name(data.get("package") or default_package, "package")
170
+ title = data.get("title")
171
+ branch = data.get("branch")
172
+ repo = data.get("repo")
173
+ if repo is not None and not isinstance(repo, str):
174
+ raise ValueError(f"'repo' is not a string: {repo!r}")
175
+ base, head = data.get("base"), data.get("head")
176
+ if (base is None) != (head is None):
177
+ raise ValueError("'base' and 'head' must both be set or both be null")
178
+ if base is not None:
179
+ base, head = gitio.check_ref(base), gitio.check_ref(head)
180
+ files = data.get("files") or []
181
+ if not isinstance(files, list):
182
+ raise ValueError("'files' is not a list")
183
+ files = [gitio.check_path(p) for p in files]
184
+ order = data.get("order")
185
+ if isinstance(order, bool) or not isinstance(order, int | float):
186
+ order = None
187
+ depends_on = data.get("depends_on") or []
188
+ if not isinstance(depends_on, list):
189
+ depends_on = []
190
+ tags = data.get("tags") or []
191
+ words = [sid, title, data.get("summary"), *(tags if isinstance(tags, list) else [])]
192
+ return Subject(
193
+ source=path,
194
+ package=package,
195
+ id=sid,
196
+ title=title if isinstance(title, str) else sid,
197
+ branch_field=branch if isinstance(branch, str) and branch else None,
198
+ repo=repo,
199
+ base=base,
200
+ head=head,
201
+ files=files,
202
+ order=order,
203
+ depends_on=[d for d in depends_on if isinstance(d, str)],
204
+ extra={k: data.get(k) for k in ("priority", "origin", "recommended", "senior_verdict")},
205
+ search=" ".join(w for w in words if isinstance(w, str)).lower(),
206
+ )
207
+
208
+
209
+ @dataclass
210
+ class Snapshot:
211
+ """A consistent view of the subjects, their status and edit flags.
212
+
213
+ Attributes
214
+ ----------
215
+ subjects : list of Subject
216
+ Sorted by package, branch, repository, then the order inside the
217
+ branch (commit order, then `order`, then natural ID order).
218
+ by_key : dict
219
+ ``(package, id)`` to subject.
220
+ by_id : dict
221
+ ID to every subject with this ID (more than one if two packages use
222
+ the same ID).
223
+ status : dict
224
+ ``(package, id)`` to one of `STATUSES`.
225
+ review : dict
226
+ ``(package, id)`` to the last review record, if any.
227
+ history_count : dict
228
+ ``(package, id)`` to the number of review records.
229
+ edited : frozenset
230
+ Keys of the subjects that have at least one saved edit.
231
+ memo : dict
232
+ Responses computed from this snapshot, reused until it changes.
233
+ """
234
+
235
+ subjects: list[Subject]
236
+ by_key: dict[Key, Subject]
237
+ by_id: dict[str, list[Subject]]
238
+ status: dict[Key, str]
239
+ review: dict[Key, dict[str, Any]]
240
+ history_count: dict[Key, int]
241
+ edited: frozenset[Key]
242
+ memo: dict[str, Any] = field(default_factory=dict)
243
+
244
+ def find(self, subject_id: Any, package: Any = None) -> Subject:
245
+ """Return the subject with ID `subject_id` (and `package`, if given).
246
+
247
+ Raises
248
+ ------
249
+ InvalidInput
250
+ If the ID or package is not valid, or the ID is used in more than
251
+ one package and `package` is not given.
252
+ NotFound
253
+ If no subject matches.
254
+ """
255
+ sid = check_name(subject_id, "subject ID")
256
+ if package not in (None, ""):
257
+ subject = self.by_key.get((check_name(package, "package"), sid))
258
+ if subject is None:
259
+ raise NotFound(f"No subject {sid!r} in package {package!r}")
260
+ return subject
261
+ matches = self.by_id.get(sid, [])
262
+ if not matches:
263
+ raise NotFound(f"No subject with ID {sid!r}")
264
+ if len(matches) > 1:
265
+ names = ", ".join(s.package for s in matches)
266
+ raise InvalidInput(f"Subject ID {sid!r} is used in packages {names}; add 'package'")
267
+ return matches[0]
268
+
269
+
270
+ class Index:
271
+ """Cached subject index of one review root.
272
+
273
+ A subject without a `branch` field belongs to the branch checked out in
274
+ its repository (``DETACHED_BRANCH`` if HEAD is detached), or to
275
+ ``NO_REPO_BRANCH`` if it has no repository. Checked-out branches are read
276
+ again only when a subject file changes.
277
+
278
+ Parameters
279
+ ----------
280
+ config : Config
281
+ Settings of the review root.
282
+ """
283
+
284
+ def __init__(self, config: Config) -> None:
285
+ self.config = config
286
+ self._lock = threading.Lock()
287
+ self._numstat_lock = threading.Lock()
288
+ self._files: dict[str, tuple[int, int, Subject | None]] = {}
289
+ self._subjects: list[Subject] = []
290
+ self._subjects_changed = True
291
+ self._reviews_stat: tuple[int, int] | None = None
292
+ self._reviews: list[Any] = []
293
+ self._edited: frozenset[Key] = frozenset()
294
+ self._order_cache: dict[tuple[str, tuple[str, ...]], dict[str, int]] = {}
295
+ self._numstat_disk: dict[str, Numstat] | None = None
296
+ self._numstat_memory: dict[str, Numstat | None] = {}
297
+ self._blob_cache: dict[tuple[str, ...], list[dict[str, int | None]]] = {}
298
+ self._snapshot: Snapshot | None = None
299
+
300
+ def snapshot(self) -> Snapshot:
301
+ """Bring the index up to date with the files and return a snapshot.
302
+
303
+ Raises
304
+ ------
305
+ ValueError
306
+ If ``reviews.json`` exists but is not a JSON list.
307
+ """
308
+ with self._lock:
309
+ subjects_changed = self._scan_subjects()
310
+ reviews_changed = self._load_reviews()
311
+ edited = self._scan_edits()
312
+ edits_changed = edited != self._edited
313
+ self._edited = edited
314
+ if self._snapshot is None or subjects_changed or reviews_changed or edits_changed:
315
+ self._snapshot = self._build_snapshot()
316
+ return self._snapshot
317
+
318
+ def _scan_subjects(self) -> bool:
319
+ # Plain strings, not Path objects: hashing 10,000 Paths per request
320
+ # costs more than the stat calls.
321
+ root = self.config.subjects
322
+ seen: dict[str, tuple[int, int, str]] = {}
323
+ stack = [(str(root), DEFAULT_PACKAGE)] if root.is_dir() else []
324
+ while stack:
325
+ folder, package = stack.pop()
326
+ try:
327
+ entries = list(os.scandir(folder))
328
+ except OSError as exc:
329
+ log.warning("Cannot list %s: %s", folder, exc)
330
+ continue
331
+ for entry in entries:
332
+ if entry.name.startswith("."):
333
+ continue
334
+ if entry.is_dir():
335
+ top = folder == str(root)
336
+ stack.append((entry.path, entry.name if top else package))
337
+ elif entry.name.endswith(".json") and entry.is_file():
338
+ try:
339
+ st = entry.stat()
340
+ except OSError:
341
+ continue
342
+ seen[entry.path] = (st.st_mtime_ns, st.st_size, package)
343
+ changed = seen.keys() != self._files.keys()
344
+ for path, (mtime_ns, size, package) in seen.items():
345
+ cached = self._files.get(path)
346
+ if cached is not None and cached[:2] == (mtime_ns, size):
347
+ continue
348
+ changed = True
349
+ subject: Subject | None
350
+ try:
351
+ subject = parse_subject(Path(path), package)
352
+ except (OSError, ValueError) as exc:
353
+ log.warning("Skipping %s: %s", path, exc)
354
+ subject = None
355
+ self._files[path] = (mtime_ns, size, subject)
356
+ for path in self._files.keys() - seen.keys():
357
+ del self._files[path]
358
+ if changed:
359
+ self._subjects_changed = True
360
+ return changed
361
+
362
+ def _load_reviews(self) -> bool:
363
+ path = self.config.reviews
364
+ try:
365
+ st = path.stat()
366
+ except FileNotFoundError:
367
+ changed = self._reviews_stat is not None
368
+ self._reviews_stat, self._reviews = None, []
369
+ return changed
370
+ stamp = (st.st_mtime_ns, st.st_size)
371
+ if stamp == self._reviews_stat:
372
+ return False
373
+ self._reviews = read_reviews(path)
374
+ self._reviews_stat = stamp
375
+ return True
376
+
377
+ def _scan_edits(self) -> frozenset[Key]:
378
+ found: set[Key] = set()
379
+ root = self.config.edits
380
+ if not root.is_dir():
381
+ return frozenset()
382
+ for pkg in os.scandir(root):
383
+ if pkg.name.startswith(".") or not pkg.is_dir():
384
+ continue
385
+ for sub in os.scandir(pkg.path):
386
+ if sub.name.startswith(".") or not sub.is_dir():
387
+ continue
388
+ if _has_file(Path(sub.path)):
389
+ found.add((pkg.name, sub.name))
390
+ return frozenset(found)
391
+
392
+ def _build_snapshot(self) -> Snapshot:
393
+ if self._subjects_changed:
394
+ self._subjects = self._order_subjects()
395
+ self._subjects_changed = False
396
+ self._numstat_memory.clear()
397
+ subjects = self._subjects
398
+ by_key = {s.key: s for s in subjects}
399
+ by_id: dict[str, list[Subject]] = {}
400
+ for s in subjects:
401
+ by_id.setdefault(s.id, []).append(s)
402
+
403
+ last: dict[Key, dict[str, Any]] = {}
404
+ count: dict[Key, int] = {}
405
+ for rec in self._reviews:
406
+ if not isinstance(rec, dict):
407
+ continue
408
+ sid, pkg = rec.get("id"), rec.get("package")
409
+ if isinstance(pkg, str):
410
+ keys = [(pkg, sid)] if (pkg, sid) in by_key else []
411
+ else:
412
+ keys = [s.key for s in by_id.get(sid, [])] if isinstance(sid, str) else []
413
+ for key in keys:
414
+ last[key] = rec
415
+ count[key] = count.get(key, 0) + 1
416
+ status = {
417
+ s.key: VERDICT_STATUS.get(last[s.key].get("verdict"), "pending")
418
+ if s.key in last
419
+ else "pending"
420
+ for s in subjects
421
+ }
422
+ return Snapshot(
423
+ subjects=subjects,
424
+ by_key=by_key,
425
+ by_id=by_id,
426
+ status=status,
427
+ review=last,
428
+ history_count=count,
429
+ edited=self._edited,
430
+ )
431
+
432
+ def _order_subjects(self) -> list[Subject]:
433
+ unique: dict[Key, Subject] = {}
434
+ for path in sorted(self._files):
435
+ subject = self._files[path][2]
436
+ if subject is None:
437
+ continue
438
+ if subject.key in unique:
439
+ log.warning(
440
+ "Skipping %s: same package and ID as %s", path, unique[subject.key].source
441
+ )
442
+ continue
443
+ unique[subject.key] = subject
444
+ subjects = list(unique.values())
445
+
446
+ branches: dict[str, str | None] = {}
447
+ heads: dict[str, set[str]] = {}
448
+ for s in subjects:
449
+ if s.branch_field is None and s.repo is not None and s.repo not in branches:
450
+ branches[s.repo] = gitio.current_branch(s.repo)
451
+ if s.has_diff:
452
+ heads.setdefault(s.repo, set()).add(s.head)
453
+ for s in subjects:
454
+ if s.branch_field is not None:
455
+ s.branch = s.branch_field
456
+ elif s.repo is None:
457
+ s.branch = NO_REPO_BRANCH
458
+ else:
459
+ s.branch = branches[s.repo] or DETACHED_BRANCH
460
+
461
+ positions: dict[str, dict[str, int]] = {}
462
+ for repo, repo_heads in heads.items():
463
+ cache_key = (repo, tuple(sorted(repo_heads)))
464
+ if cache_key not in self._order_cache:
465
+ try:
466
+ self._order_cache[cache_key] = gitio.commit_order(repo, sorted(repo_heads))
467
+ except GitError as exc:
468
+ log.warning("No commit order for %s: %s", repo, exc)
469
+ self._order_cache[cache_key] = {}
470
+ positions[repo] = self._order_cache[cache_key]
471
+ live = {(repo, tuple(sorted(h))) for repo, h in heads.items()}
472
+ for stale in self._order_cache.keys() - live:
473
+ del self._order_cache[stale]
474
+
475
+ def sort_key(s: Subject) -> tuple[Any, ...]:
476
+ pos = positions.get(s.repo or "", {}).get(s.head or "") if s.has_diff else None
477
+ return (
478
+ s.package,
479
+ s.branch,
480
+ s.repo or "",
481
+ pos is None,
482
+ pos or 0,
483
+ s.order is None,
484
+ s.order or 0,
485
+ natural_key(s.id),
486
+ )
487
+
488
+ return sorted(subjects, key=sort_key)
489
+
490
+ def _load_numstat_disk(self) -> dict[str, Numstat]:
491
+ if self._numstat_disk is None:
492
+ path = self.config.cache / "numstat.json"
493
+ self._numstat_disk = {}
494
+ try:
495
+ data = json.loads(path.read_bytes())
496
+ if data.get("format") == NUMSTAT_FORMAT and isinstance(data.get("entries"), dict):
497
+ self._numstat_disk = data["entries"]
498
+ except FileNotFoundError:
499
+ pass
500
+ except (OSError, ValueError, AttributeError) as exc:
501
+ log.warning("Ignoring %s: %s", path, exc)
502
+ return self._numstat_disk
503
+
504
+ def numstat(self, subjects: Iterable[Subject]) -> dict[Key, Numstat | None]:
505
+ """Return ``{path: [added, deleted]}`` for each subject with a diff.
506
+
507
+ Diffs not in the cache are computed with one ``git diff-tree`` call
508
+ per repository. Diffs between two full commit IDs are stored in
509
+ ``<cache>/numstat.json``. Others are kept in memory until a subject
510
+ file changes.
511
+
512
+ Returns
513
+ -------
514
+ dict
515
+ ``(package, id)`` to the counts, or to `None` if git cannot
516
+ compute them. Subjects without a diff are absent.
517
+ """
518
+ wanted = [s for s in subjects if s.has_diff]
519
+ with self._numstat_lock:
520
+ disk = self._load_numstat_disk()
521
+ memory = self._numstat_memory
522
+ missing: dict[str, list[tuple[str, str]]] = {}
523
+ for s in wanted:
524
+ key = _numstat_key(s)
525
+ if key not in disk and key not in memory:
526
+ missing.setdefault(s.repo, []).append((s.base, s.head))
527
+ dirty = False
528
+ for repo, pairs in missing.items():
529
+ try:
530
+ found = gitio.numstat_many(repo, pairs)
531
+ except GitError as exc:
532
+ log.warning("No line counts for %s: %s", repo, exc)
533
+ found = dict.fromkeys(pairs)
534
+ for (base, head), counts in found.items():
535
+ key = f"{repo}\n{base}\n{head}"
536
+ if (
537
+ counts is not None
538
+ and gitio.HEX_SHA.fullmatch(base)
539
+ and (gitio.HEX_SHA.fullmatch(head))
540
+ ):
541
+ disk[key] = counts
542
+ dirty = True
543
+ else:
544
+ memory[key] = counts
545
+ if dirty:
546
+ self._save_numstat(disk)
547
+ return {
548
+ s.key: disk[k] if k in disk else memory.get(k)
549
+ for s in wanted
550
+ for k in [_numstat_key(s)]
551
+ }
552
+
553
+ def _save_numstat(self, disk: dict[str, Numstat]) -> None:
554
+ path = self.config.cache / "numstat.json"
555
+ payload = {"format": NUMSTAT_FORMAT, "entries": disk}
556
+ try:
557
+ write_atomic(path, json.dumps(payload, separators=(",", ":")).encode())
558
+ except OSError as exc:
559
+ log.warning("Cannot write %s: %s", path, exc)
560
+
561
+ def blob_stats(self, subject: Subject, paths: list[str]) -> list[dict[str, int | None]]:
562
+ """Return the size in bytes and the line count of each path at base and head.
563
+
564
+ Results for two full commit IDs are cached in memory.
565
+
566
+ Returns
567
+ -------
568
+ list of dict
569
+ ``{size_base, size_head, lines_base, lines_head}`` per path, each
570
+ `None` where the file is absent.
571
+
572
+ Raises
573
+ ------
574
+ GitError
575
+ If git fails.
576
+ """
577
+ if not subject.has_diff or not paths:
578
+ return [dict.fromkeys(_BLOB_FIELDS) for _ in paths]
579
+ key = (subject.repo, subject.base, subject.head, *paths)
580
+ cached = self._blob_cache.get(key)
581
+ if cached is None:
582
+ specs = [(rev, p) for p in paths for rev in (subject.base, subject.head)]
583
+ blobs = gitio.read_blobs(subject.repo, specs)
584
+ cached = [
585
+ {
586
+ "size_base": _size(base),
587
+ "size_head": _size(head),
588
+ "lines_base": count_lines(base),
589
+ "lines_head": count_lines(head),
590
+ }
591
+ for base, head in zip(blobs[0::2], blobs[1::2], strict=True)
592
+ ]
593
+ if gitio.HEX_SHA.fullmatch(subject.base) and gitio.HEX_SHA.fullmatch(subject.head):
594
+ self._blob_cache[key] = cached
595
+ return cached
596
+
597
+
598
+ _BLOB_FIELDS = ("size_base", "size_head", "lines_base", "lines_head")
599
+
600
+
601
+ def _size(blob: bytes | None) -> int | None:
602
+ return None if blob is None else len(blob)
603
+
604
+
605
+ def count_lines(blob: bytes | None) -> int | None:
606
+ """Return the number of lines in `blob` (a last line without a newline counts)."""
607
+ if blob is None:
608
+ return None
609
+ return blob.count(b"\n") + (1 if blob and not blob.endswith(b"\n") else 0)
610
+
611
+
612
+ def _numstat_key(subject: Subject) -> str:
613
+ return f"{subject.repo}\n{subject.base}\n{subject.head}"
614
+
615
+
616
+ def _has_file(folder: Path) -> bool:
617
+ # Skip only the temporary files of `write_atomic`: an edit may be a dotfile.
618
+ for _dirpath, _dirnames, filenames in os.walk(folder):
619
+ if any(not (f.startswith(".") and f.endswith(".tmp")) for f in filenames):
620
+ return True
621
+ return False
622
+
623
+
624
+ def read_reviews(path: Path) -> list[Any]:
625
+ """Return the review records in ``reviews.json`` (a JSON list).
626
+
627
+ Raises
628
+ ------
629
+ ValueError
630
+ If the file is not valid JSON or does not hold a list.
631
+ """
632
+ data = json.loads(path.read_bytes())
633
+ if not isinstance(data, list):
634
+ raise ValueError(f"{path} does not hold a JSON list")
635
+ return data