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/server.py ADDED
@@ -0,0 +1,750 @@
1
+ """HTTP server for the diffdesk browser app and its JSON API (version 1).
2
+
3
+ Only the Python standard library is used. The server binds 127.0.0.1 by
4
+ default, accepts only requests whose ``Host`` header names the bound address,
5
+ checks ``Origin`` and ``Sec-Fetch-Site`` on writes, and writes only to the
6
+ reviews file and the edits folder of the review root.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import gzip
12
+ import hashlib
13
+ import json
14
+ import logging
15
+ import mimetypes
16
+ import socket
17
+ import threading
18
+ from datetime import datetime
19
+ from http import HTTPStatus
20
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
21
+ from pathlib import Path, PurePosixPath
22
+ from typing import Any
23
+ from urllib.parse import parse_qs, urlsplit
24
+
25
+ from . import __version__, gitio
26
+ from .config import Config
27
+ from .gitio import GitError, InvalidInput, Numstat
28
+ from .index import (
29
+ STATUSES,
30
+ VERDICT_STATUS,
31
+ Index,
32
+ NotFound,
33
+ Snapshot,
34
+ Subject,
35
+ read_reviews,
36
+ write_atomic,
37
+ )
38
+
39
+ log = logging.getLogger(__name__)
40
+
41
+ STATIC_DIR = Path(__file__).resolve().parent / "static"
42
+ GZIP_MIN_BYTES = 1024
43
+ GZIP_LEVEL = 6
44
+ DEFAULT_LIMIT = 200
45
+ DEFAULT_CONTEXT = 3
46
+ IMMUTABLE = "max-age=31536000, immutable"
47
+ REVALIDATE = "no-cache"
48
+
49
+ CONTENT_TYPES = {
50
+ ".html": "text/html; charset=utf-8",
51
+ ".js": "text/javascript; charset=utf-8",
52
+ ".mjs": "text/javascript; charset=utf-8",
53
+ ".css": "text/css; charset=utf-8",
54
+ ".json": "application/json; charset=utf-8",
55
+ ".svg": "image/svg+xml",
56
+ ".txt": "text/plain; charset=utf-8",
57
+ ".woff2": "font/woff2",
58
+ ".woff": "font/woff",
59
+ ".ttf": "font/ttf",
60
+ ".wasm": "application/wasm",
61
+ }
62
+
63
+ LANGUAGES = {
64
+ ".py": "python",
65
+ ".pyi": "python",
66
+ ".pyx": "python",
67
+ ".js": "javascript",
68
+ ".mjs": "javascript",
69
+ ".cjs": "javascript",
70
+ ".jsx": "javascript",
71
+ ".ts": "typescript",
72
+ ".tsx": "typescript",
73
+ ".rs": "rust",
74
+ ".c": "c",
75
+ ".h": "c",
76
+ ".cc": "cpp",
77
+ ".cpp": "cpp",
78
+ ".cxx": "cpp",
79
+ ".hpp": "cpp",
80
+ ".java": "java",
81
+ ".go": "go",
82
+ ".json": "json",
83
+ ".md": "markdown",
84
+ ".markdown": "markdown",
85
+ ".rst": "restructuredtext",
86
+ ".toml": "toml",
87
+ ".yaml": "yaml",
88
+ ".yml": "yaml",
89
+ ".html": "html",
90
+ ".htm": "html",
91
+ ".xml": "xml",
92
+ ".css": "css",
93
+ ".scss": "scss",
94
+ ".sh": "shell",
95
+ ".bash": "shell",
96
+ ".zsh": "shell",
97
+ ".sql": "sql",
98
+ ".f": "fortran",
99
+ ".f90": "fortran",
100
+ ".jl": "julia",
101
+ ".r": "r",
102
+ ".tex": "latex",
103
+ ".ini": "ini",
104
+ ".cfg": "ini",
105
+ }
106
+ LANGUAGE_NAMES = {"Makefile": "makefile", "Dockerfile": "dockerfile", "CMakeLists.txt": "cmake"}
107
+
108
+
109
+ class Conflict(RuntimeError):
110
+ """The request names commits that the subject no longer points at (HTTP 409)."""
111
+
112
+
113
+ def language_of(path: str) -> str | None:
114
+ """Return the editor language name for `path`, or `None` if unknown."""
115
+ pure = PurePosixPath(path)
116
+ return LANGUAGE_NAMES.get(pure.name) or LANGUAGES.get(pure.suffix.lower())
117
+
118
+
119
+ def _int_param(query: dict[str, list[str]], name: str, default: int) -> int:
120
+ raw = query.get(name, [""])[0]
121
+ if raw == "":
122
+ return default
123
+ try:
124
+ value = int(raw)
125
+ except ValueError:
126
+ raise InvalidInput(f"'{name}' must be an integer: {raw!r}") from None
127
+ if value < 0:
128
+ raise InvalidInput(f"'{name}' must be 0 or more: {value}")
129
+ return value
130
+
131
+
132
+ def _param(query: dict[str, list[str]], name: str) -> str:
133
+ return query.get(name, [""])[0]
134
+
135
+
136
+ def _counts(subjects: list[Subject], snap: Snapshot) -> dict[str, Any]:
137
+ by_status = dict.fromkeys(STATUSES, 0)
138
+ for s in subjects:
139
+ by_status[snap.status[s.key]] += 1
140
+ return {
141
+ "total": len(subjects),
142
+ "reviewed": len(subjects) - by_status["pending"],
143
+ "by_status": by_status,
144
+ }
145
+
146
+
147
+ def _lines(subject: Subject, counts: Numstat | None) -> tuple[int | None, int | None, int | None]:
148
+ """Return ``(files_count, lines_added, lines_deleted)`` of a subject.
149
+
150
+ Only the files listed in the subject count, if it lists any. A subject
151
+ without a diff has 0 lines. Counts are `None` if git could not compute
152
+ them.
153
+ """
154
+ if not subject.has_diff:
155
+ return len(subject.files), 0, 0
156
+ if counts is None:
157
+ return (len(subject.files) or None), None, None
158
+ paths = subject.files or list(counts)
159
+ added = deleted = 0
160
+ for p in paths:
161
+ a, d = counts.get(p, (0, 0))
162
+ added += a or 0
163
+ deleted += d or 0
164
+ return len(paths), added, deleted
165
+
166
+
167
+ def _subject_paths(subject: Subject, counts: Numstat | None) -> list[str]:
168
+ if subject.files or not subject.has_diff:
169
+ return subject.files
170
+ if counts is None:
171
+ raise GitError(f"Cannot list the files of subject {subject.id}")
172
+ return sorted(counts)
173
+
174
+
175
+ class DiffdeskServer(ThreadingHTTPServer):
176
+ """Threaded HTTP server that holds the index of one review root.
177
+
178
+ Parameters
179
+ ----------
180
+ config : Config
181
+ Settings of the review root.
182
+ host : str
183
+ Address to bind.
184
+ port : int
185
+ Port to bind; 0 picks a free port.
186
+ """
187
+
188
+ daemon_threads = True
189
+
190
+ def __init__(self, config: Config, host: str, port: int) -> None:
191
+ if ":" in host:
192
+ self.address_family = socket.AF_INET6
193
+ super().__init__((host, port), Handler)
194
+ self.config = config
195
+ self.index = Index(config)
196
+ self.reviews_lock = threading.Lock()
197
+ self.edits_lock = threading.Lock()
198
+ self.gzip_cache: dict[Path, tuple[int, int, bytes]] = {}
199
+ bound = self.server_address[1]
200
+ names = {"127.0.0.1", "localhost", "[::1]"}
201
+ if host not in ("", "0.0.0.0", "::"):
202
+ names.add(f"[{host}]" if ":" in host else host)
203
+ self.allowed_hosts = {f"{name}:{bound}" for name in names}
204
+
205
+ # ---- read endpoints -------------------------------------------------
206
+
207
+ def meta(self) -> dict[str, Any]:
208
+ """Return ``GET /api/meta``."""
209
+ snap = self.index.snapshot()
210
+ names = sorted({*self.config.packages, *(s.package for s in snap.subjects)})
211
+ counts = _counts(snap.subjects, snap)
212
+ return {
213
+ "name": "diffdesk",
214
+ "version": __version__,
215
+ "title": self.config.title,
216
+ "root": str(self.config.root),
217
+ "packages": {n: {"depends_on": self.config.packages.get(n, [])} for n in names},
218
+ "ui_defaults": self.config.ui,
219
+ "counts": {"total": counts["total"], "by_status": counts["by_status"]},
220
+ }
221
+
222
+ def tree(self) -> list[dict[str, Any]]:
223
+ """Return ``GET /api/tree``: counts per package and per branch."""
224
+ snap = self.index.snapshot()
225
+ if "tree" in snap.memo:
226
+ return snap.memo["tree"]
227
+ groups: dict[str, dict[tuple[str, str | None], list[Subject]]] = {}
228
+ for s in snap.subjects:
229
+ groups.setdefault(s.package, {}).setdefault((s.branch, s.repo), []).append(s)
230
+ out = []
231
+ for package, branches in groups.items():
232
+ members = [s for group in branches.values() for s in group]
233
+ out.append(
234
+ {
235
+ "package": package,
236
+ **_counts(members, snap),
237
+ "branches": [
238
+ {"name": name, "repo": repo, **_counts(group, snap)}
239
+ for (name, repo), group in branches.items()
240
+ ],
241
+ }
242
+ )
243
+ snap.memo["tree"] = out
244
+ return out
245
+
246
+ def light(self, s: Subject, snap: Snapshot, counts: Numstat | None) -> dict[str, Any]:
247
+ """Return the light form of a subject used in lists."""
248
+ files_count, added, deleted = _lines(s, counts)
249
+ return {
250
+ "id": s.id,
251
+ "package": s.package,
252
+ "branch": s.branch,
253
+ "title": s.title,
254
+ **s.extra,
255
+ "status": snap.status[s.key],
256
+ "edited": s.key in snap.edited,
257
+ "order": s.order,
258
+ "files_count": files_count,
259
+ "lines_added": added,
260
+ "lines_deleted": deleted,
261
+ }
262
+
263
+ def subjects(self, query: dict[str, list[str]]) -> dict[str, Any]:
264
+ """Return ``GET /api/subjects``: one page of filtered light subjects."""
265
+ snap = self.index.snapshot()
266
+ offset = _int_param(query, "offset", 0)
267
+ limit = _int_param(query, "limit", DEFAULT_LIMIT)
268
+ package, branch, repo = (_param(query, k) for k in ("package", "branch", "repo"))
269
+ statuses = {v for v in _param(query, "status").split(",") if v}
270
+ unknown = statuses - set(STATUSES)
271
+ if unknown:
272
+ raise InvalidInput(f"Unknown status {sorted(unknown)}; use {list(STATUSES)}")
273
+ terms = _param(query, "q").lower().split()
274
+ items = [
275
+ s
276
+ for s in snap.subjects
277
+ if (not package or s.package == package)
278
+ and (not branch or s.branch == branch)
279
+ and (not repo or s.repo == repo)
280
+ and (not statuses or snap.status[s.key] in statuses)
281
+ and all(t in s.search for t in terms)
282
+ ]
283
+ page = items[offset : offset + limit]
284
+ counts = self.index.numstat(page)
285
+ return {
286
+ "total": len(items),
287
+ "items": [self.light(s, snap, counts.get(s.key)) for s in page],
288
+ }
289
+
290
+ def subject(self, query: dict[str, list[str]]) -> dict[str, Any]:
291
+ """Return ``GET /api/subject``: the full subject file plus review and files."""
292
+ snap = self.index.snapshot()
293
+ s = snap.find(_param(query, "id"), _param(query, "package"))
294
+ try:
295
+ data = json.loads(s.source.read_bytes())
296
+ except FileNotFoundError:
297
+ raise NotFound(f"Subject file is gone: {s.source}") from None
298
+ counts = self.index.numstat([s]).get(s.key)
299
+ paths = _subject_paths(s, counts)
300
+ stats = self.index.blob_stats(s, paths)
301
+ files = []
302
+ for path, stat in zip(paths, stats, strict=True):
303
+ added, deleted = (counts or {}).get(path, (None, None))
304
+ files.append(
305
+ {
306
+ "path": path,
307
+ "lines_added": added,
308
+ "lines_deleted": deleted,
309
+ **stat,
310
+ "edited": self.edit_target(s, path).is_file(),
311
+ }
312
+ )
313
+ rec = snap.review.get(s.key) or {}
314
+ data.update(
315
+ id=s.id,
316
+ package=s.package,
317
+ branch=s.branch,
318
+ status=snap.status[s.key],
319
+ edited=s.key in snap.edited,
320
+ review={
321
+ "verdict": rec.get("verdict"),
322
+ "comment": rec.get("comment"),
323
+ "at": rec.get("at", rec.get("time")),
324
+ "history_count": snap.history_count.get(s.key, 0),
325
+ },
326
+ files=files,
327
+ )
328
+ return data
329
+
330
+ def flow(self) -> dict[str, Any]:
331
+ """Return ``GET /api/flow``: package nodes and ``[package, dependency]`` edges."""
332
+ snap = self.index.snapshot()
333
+ if "flow" in snap.memo:
334
+ return snap.memo["flow"]
335
+ edges: set[tuple[str, str]] = set()
336
+ for pkg, deps in self.config.packages.items():
337
+ edges.update((pkg, d) for d in deps if d != pkg)
338
+ packages = {s.package for s in snap.subjects}
339
+ for s in snap.subjects:
340
+ for dep in s.depends_on:
341
+ targets = [t.package for t in snap.by_id.get(dep, [])]
342
+ if not targets and dep in packages:
343
+ targets = [dep]
344
+ edges.update((s.package, t) for t in targets if t != s.package)
345
+ names = sorted({*packages, *self.config.packages, *(n for e in edges for n in e)})
346
+ members: dict[str, list[Subject]] = {n: [] for n in names}
347
+ for s in snap.subjects:
348
+ members[s.package].append(s)
349
+ out = {
350
+ "nodes": [{"package": n, **_counts(members[n], snap)} for n in names],
351
+ "edges": [list(e) for e in sorted(edges)],
352
+ }
353
+ snap.memo["flow"] = out
354
+ return out
355
+
356
+ def treemap(self, query: dict[str, list[str]]) -> list[dict[str, Any]]:
357
+ """Return ``GET /api/treemap``: every subject (of one package) with line counts."""
358
+ snap = self.index.snapshot()
359
+ package = _param(query, "package")
360
+ items = [s for s in snap.subjects if not package or s.package == package]
361
+ counts = self.index.numstat(items)
362
+ out = []
363
+ for s in items:
364
+ _, added, deleted = _lines(s, counts.get(s.key))
365
+ out.append(
366
+ {
367
+ "id": s.id,
368
+ "package": s.package,
369
+ "branch": s.branch,
370
+ "title": s.title,
371
+ "status": snap.status[s.key],
372
+ "lines_added": added,
373
+ "lines_deleted": deleted,
374
+ }
375
+ )
376
+ return out
377
+
378
+ def diff_request(
379
+ self, query: dict[str, list[str]]
380
+ ) -> tuple[Subject, str, str, int, bool, bool, str | None]:
381
+ """Validate ``GET /api/diff`` and return what `diff` needs.
382
+
383
+ Returns
384
+ -------
385
+ tuple
386
+ ``(subject, path, mode, context, ignore_space, immutable, etag)``.
387
+ `etag` is `None` if the revisions are not full commit IDs, because
388
+ then the response can change without any input change.
389
+ """
390
+ snap = self.index.snapshot()
391
+ s = snap.find(_param(query, "id"), _param(query, "package"))
392
+ if not s.has_diff:
393
+ raise NotFound(f"Subject {s.id} has no diff")
394
+ path = gitio.check_path(_param(query, "path"))
395
+ mode = _param(query, "mode") or "full"
396
+ if mode not in ("full", "hunks"):
397
+ raise InvalidInput(f"'mode' must be 'full' or 'hunks': {mode!r}")
398
+ context = _int_param(query, "context", DEFAULT_CONTEXT)
399
+ ignore_space = _param(query, "ignore_ws") in ("1", "true")
400
+ pinned = _param(query, "base"), _param(query, "head")
401
+ if any(pinned) and pinned != (s.base, s.head):
402
+ raise Conflict(f"Subject {s.id} now points at {s.base}..{s.head}")
403
+ counts = None if s.files else self.index.numstat([s]).get(s.key)
404
+ if path not in _subject_paths(s, counts):
405
+ raise InvalidInput(f"Path {path!r} is not a file of subject {s.id}")
406
+ shas = bool(gitio.HEX_SHA.fullmatch(s.base) and gitio.HEX_SHA.fullmatch(s.head))
407
+ immutable = mode == "hunks" and shas and all(pinned)
408
+ etag = None
409
+ if shas:
410
+ parts: list[Any] = [s.repo, s.base, s.head, path, mode]
411
+ if mode == "full":
412
+ try:
413
+ st = self.edit_target(s, path).stat()
414
+ parts.append([st.st_mtime_ns, st.st_size])
415
+ except FileNotFoundError:
416
+ parts.append(None)
417
+ else:
418
+ parts += [context, ignore_space]
419
+ etag = hashlib.sha1(json.dumps(parts).encode()).hexdigest()
420
+ return s, path, mode, context, ignore_space, immutable, etag
421
+
422
+ def diff(
423
+ self, s: Subject, path: str, mode: str, context: int, ignore_space: bool
424
+ ) -> dict[str, Any]:
425
+ """Return the body of ``GET /api/diff``."""
426
+ if mode == "hunks":
427
+ hunks, binary = gitio.diff_hunks(s.repo, s.base, s.head, path, context, ignore_space)
428
+ return {"hunks": hunks, "binary": binary}
429
+ base, head = gitio.read_blobs(s.repo, [(s.base, path), (s.head, path)])
430
+ target = self.edit_target(s, path)
431
+ edit = target.read_bytes().decode("utf-8", errors="replace") if target.is_file() else None
432
+ binary = any(b is not None and b"\0" in b for b in (base, head))
433
+ return {
434
+ "base": None if binary or base is None else base.decode("utf-8", errors="replace"),
435
+ "head": None if binary or head is None else head.decode("utf-8", errors="replace"),
436
+ "edit": edit,
437
+ "language": language_of(path),
438
+ "binary": binary,
439
+ }
440
+
441
+ # ---- write endpoints ------------------------------------------------
442
+
443
+ def edit_target(self, s: Subject, path: str) -> Path:
444
+ """Return ``<edits>/<package>/<id>/<path>`` and check that it stays there.
445
+
446
+ Raises
447
+ ------
448
+ InvalidInput
449
+ If the resolved path leaves the edit folder of the subject.
450
+ """
451
+ base = (self.config.edits / s.package / s.id).resolve()
452
+ target = (base / path).resolve()
453
+ if not target.is_relative_to(base) or target == base:
454
+ raise InvalidInput(f"Path leaves the edit folder: {path!r}")
455
+ return target
456
+
457
+ def add_review(self, body: dict[str, Any]) -> dict[str, Any]:
458
+ """Validate a verdict and append it to the reviews file."""
459
+ s = self.index.snapshot().find(body.get("id"), body.get("package"))
460
+ verdict = body.get("verdict")
461
+ if verdict not in VERDICT_STATUS:
462
+ raise InvalidInput(f"'verdict' must be one of {list(VERDICT_STATUS)}: {verdict!r}")
463
+ comment = body.get("comment") or ""
464
+ if not isinstance(comment, str):
465
+ raise InvalidInput("'comment' must be a string")
466
+ record = {
467
+ "id": s.id,
468
+ "package": s.package,
469
+ "verdict": verdict,
470
+ "comment": comment,
471
+ "at": datetime.now().astimezone().isoformat(timespec="seconds"),
472
+ }
473
+ path = self.config.reviews
474
+ with self.reviews_lock:
475
+ history = read_reviews(path) if path.exists() else []
476
+ history.append(record)
477
+ write_atomic(path, (json.dumps(history, indent=2, ensure_ascii=False) + "\n").encode())
478
+ log.info("review %s/%s: %s", s.package, s.id, verdict)
479
+ return {**record, "status": VERDICT_STATUS[verdict]}
480
+
481
+ def save_edit(self, body: dict[str, Any]) -> dict[str, Any]:
482
+ """Write or remove the saved edit of one file of a subject."""
483
+ s = self.index.snapshot().find(body.get("id"), body.get("package"))
484
+ path = gitio.check_path(body.get("path"))
485
+ if "content" not in body:
486
+ raise InvalidInput("'content' is required (a string, or null to remove the edit)")
487
+ content = body["content"]
488
+ if content is not None and not isinstance(content, str):
489
+ raise InvalidInput("'content' must be a string or null")
490
+ if not s.has_diff:
491
+ raise InvalidInput(f"Subject {s.id} has no diff, so it has no files to edit")
492
+ counts = None if s.files else self.index.numstat([s]).get(s.key)
493
+ if path not in _subject_paths(s, counts):
494
+ raise InvalidInput(f"Path {path!r} is not a file of subject {s.id}")
495
+ target = self.edit_target(s, path)
496
+ root = self.config.root
497
+ with self.edits_lock:
498
+ if content is not None:
499
+ write_atomic(target, content.encode("utf-8"))
500
+ else:
501
+ target.unlink(missing_ok=True)
502
+ stop = self.config.edits.resolve()
503
+ folder = target.parent
504
+ while folder != stop and folder.is_relative_to(stop) and not any(folder.iterdir()):
505
+ folder.rmdir()
506
+ folder = folder.parent
507
+ saved = None if content is None else target.relative_to(root.resolve()).as_posix()
508
+ log.info("edit %s/%s: %s (%s)", s.package, s.id, path, saved or "removed")
509
+ return {"id": s.id, "package": s.package, "path": path, "saved": saved}
510
+
511
+
512
+ class Handler(BaseHTTPRequestHandler):
513
+ """Request handler for the static files and the JSON API."""
514
+
515
+ server: DiffdeskServer
516
+ server_version = f"diffdesk/{__version__}"
517
+ protocol_version = "HTTP/1.1"
518
+
519
+ body_pending = False
520
+
521
+ def log_message(self, format: str, *args: Any) -> None:
522
+ log.debug("%s %s", self.address_string(), format % args)
523
+
524
+ def note_body(self) -> None:
525
+ """Record whether the request declares a body that is not read yet.
526
+
527
+ Such a connection is closed after the response. Otherwise, on a kept
528
+ alive HTTP/1.1 connection, an unread body (for example of a POST that
529
+ failed the origin check) would be parsed as the next request.
530
+ """
531
+ try:
532
+ length = int(self.headers.get("Content-Length") or 0)
533
+ except ValueError:
534
+ length = -1
535
+ self.body_pending = length != 0 or "Transfer-Encoding" in self.headers
536
+
537
+ # ---- responses ------------------------------------------------------
538
+
539
+ def _accepts_gzip(self) -> bool:
540
+ for part in self.headers.get("Accept-Encoding", "").split(","):
541
+ name, *params = part.split(";")
542
+ if name.strip().lower() != "gzip":
543
+ continue
544
+ for param in params:
545
+ key, _, value = param.strip().partition("=")
546
+ if key.lower() == "q":
547
+ try:
548
+ return float(value) > 0
549
+ except ValueError:
550
+ return False
551
+ return True
552
+ return False
553
+
554
+ def _not_modified(self, etag: str) -> bool:
555
+ header = self.headers.get("If-None-Match")
556
+ if header is None:
557
+ return False
558
+ tags = {t.strip().removeprefix("W/") for t in header.split(",")}
559
+ return "*" in tags or etag.removeprefix("W/") in tags
560
+
561
+ def send_body(
562
+ self,
563
+ status: int,
564
+ data: bytes,
565
+ content_type: str,
566
+ cache: str = REVALIDATE,
567
+ etag: str | None = None,
568
+ gz: bytes | None = None,
569
+ ) -> None:
570
+ """Send `data`, gzip-compressed when the client accepts it and it is large.
571
+
572
+ A 304 response is sent instead when `etag` matches ``If-None-Match``.
573
+ """
574
+ if etag is not None and status == HTTPStatus.OK and self._not_modified(etag):
575
+ self.send_not_modified(etag, cache)
576
+ return
577
+ encoding = None
578
+ if len(data) > GZIP_MIN_BYTES and self._accepts_gzip():
579
+ data = gz if gz is not None else gzip.compress(data, compresslevel=GZIP_LEVEL)
580
+ encoding = "gzip"
581
+ self.send_response(status)
582
+ if self.body_pending:
583
+ self.send_header("Connection", "close")
584
+ self.send_header("Content-Type", content_type)
585
+ self.send_header("Content-Length", str(len(data)))
586
+ self.send_header("Cache-Control", cache)
587
+ self.send_header("Vary", "Accept-Encoding")
588
+ self.send_header("X-Content-Type-Options", "nosniff")
589
+ if encoding:
590
+ self.send_header("Content-Encoding", encoding)
591
+ if etag is not None:
592
+ self.send_header("ETag", etag)
593
+ self.end_headers()
594
+ self.wfile.write(data)
595
+
596
+ def send_not_modified(self, etag: str, cache: str) -> None:
597
+ """Send 304 Not Modified."""
598
+ self.send_response(HTTPStatus.NOT_MODIFIED)
599
+ if self.body_pending:
600
+ self.send_header("Connection", "close")
601
+ self.send_header("ETag", etag)
602
+ self.send_header("Cache-Control", cache)
603
+ self.send_header("Vary", "Accept-Encoding")
604
+ self.end_headers()
605
+
606
+ def send_json(
607
+ self, status: int, payload: Any, cache: str = REVALIDATE, etag: str | None = None
608
+ ) -> None:
609
+ """Send `payload` as JSON. GET responses get a weak ETag of the body."""
610
+ data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
611
+ if etag is None and self.command == "GET" and status == HTTPStatus.OK:
612
+ etag = f'W/"{hashlib.sha1(data).hexdigest()}"'
613
+ if status != HTTPStatus.OK:
614
+ cache = "no-store"
615
+ self.send_body(status, data, "application/json; charset=utf-8", cache, etag)
616
+
617
+ def send_error_json(self, status: int, message: str) -> None:
618
+ """Send ``{"error": message}`` with `status`."""
619
+ self.send_json(status, {"error": message})
620
+
621
+ # ---- checks ---------------------------------------------------------
622
+
623
+ def host_ok(self) -> bool:
624
+ """Reject requests whose ``Host`` header is not the bound address (DNS rebinding)."""
625
+ if self.headers.get("Host", "") in self.server.allowed_hosts:
626
+ return True
627
+ self.send_error_json(HTTPStatus.FORBIDDEN, "Host not allowed")
628
+ return False
629
+
630
+ def origin_ok(self) -> bool:
631
+ """Reject writes from other origins."""
632
+ origin = self.headers.get("Origin")
633
+ if origin is not None and urlsplit(origin).netloc not in self.server.allowed_hosts:
634
+ self.send_error_json(HTTPStatus.FORBIDDEN, "Origin not allowed")
635
+ return False
636
+ if self.headers.get("Sec-Fetch-Site", "same-origin") not in ("same-origin", "none"):
637
+ self.send_error_json(HTTPStatus.FORBIDDEN, "Cross-site request not allowed")
638
+ return False
639
+ return True
640
+
641
+ # ---- methods --------------------------------------------------------
642
+
643
+ def do_GET(self) -> None:
644
+ self.note_body()
645
+ if not self.host_ok():
646
+ return
647
+ url = urlsplit(self.path)
648
+ query = parse_qs(url.query, keep_blank_values=True)
649
+ srv = self.server
650
+ try:
651
+ if url.path == "/api/meta":
652
+ self.send_json(HTTPStatus.OK, srv.meta())
653
+ elif url.path == "/api/tree":
654
+ self.send_json(HTTPStatus.OK, srv.tree())
655
+ elif url.path == "/api/subjects":
656
+ self.send_json(HTTPStatus.OK, srv.subjects(query))
657
+ elif url.path == "/api/subject":
658
+ self.send_json(HTTPStatus.OK, srv.subject(query))
659
+ elif url.path == "/api/flow":
660
+ self.send_json(HTTPStatus.OK, srv.flow())
661
+ elif url.path == "/api/treemap":
662
+ self.send_json(HTTPStatus.OK, srv.treemap(query))
663
+ elif url.path == "/api/diff":
664
+ s, path, mode, context, ignore_space, immutable, etag = srv.diff_request(query)
665
+ cache = IMMUTABLE if immutable else REVALIDATE
666
+ tag = f'"{etag}"' if etag else None
667
+ if tag is not None and self._not_modified(tag):
668
+ self.send_not_modified(tag, cache)
669
+ return
670
+ body = srv.diff(s, path, mode, context, ignore_space)
671
+ self.send_json(HTTPStatus.OK, body, cache, tag)
672
+ elif url.path.startswith("/api/"):
673
+ raise NotFound(f"Unknown endpoint {url.path}")
674
+ else:
675
+ self.send_static(url.path)
676
+ except InvalidInput as exc:
677
+ self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
678
+ except NotFound as exc:
679
+ self.send_error_json(HTTPStatus.NOT_FOUND, str(exc))
680
+ except Conflict as exc:
681
+ self.send_error_json(HTTPStatus.CONFLICT, str(exc))
682
+ except (GitError, OSError, ValueError) as exc:
683
+ log.exception("GET %s failed", url.path)
684
+ self.send_error_json(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc))
685
+
686
+ def do_POST(self) -> None:
687
+ self.note_body()
688
+ if not self.host_ok() or not self.origin_ok():
689
+ return
690
+ if self.headers.get_content_type() != "application/json":
691
+ self.send_error_json(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "Send application/json")
692
+ return
693
+ url = urlsplit(self.path)
694
+ try:
695
+ length = int(self.headers["Content-Length"])
696
+ if length < 0:
697
+ raise ValueError(length)
698
+ except (KeyError, TypeError, ValueError):
699
+ self.send_error_json(HTTPStatus.LENGTH_REQUIRED, "Content-Length is required")
700
+ return
701
+ data = self.rfile.read(length)
702
+ self.body_pending = False
703
+ try:
704
+ body = json.loads(data.decode("utf-8"))
705
+ except (ValueError, UnicodeDecodeError) as exc:
706
+ self.send_error_json(HTTPStatus.BAD_REQUEST, f"Body is not valid JSON: {exc}")
707
+ return
708
+ try:
709
+ if not isinstance(body, dict):
710
+ raise InvalidInput("Body must be a JSON object")
711
+ if url.path == "/api/review":
712
+ self.send_json(HTTPStatus.OK, self.server.add_review(body))
713
+ elif url.path == "/api/edit":
714
+ self.send_json(HTTPStatus.OK, self.server.save_edit(body))
715
+ else:
716
+ raise NotFound(f"Unknown endpoint {url.path}")
717
+ except InvalidInput as exc:
718
+ self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
719
+ except NotFound as exc:
720
+ self.send_error_json(HTTPStatus.NOT_FOUND, str(exc))
721
+ except (GitError, OSError, ValueError) as exc:
722
+ log.exception("POST %s failed", url.path)
723
+ self.send_error_json(HTTPStatus.INTERNAL_SERVER_ERROR, str(exc))
724
+
725
+ def send_static(self, url_path: str) -> None:
726
+ """Send one file of the ``static`` folder of the package."""
727
+ rel = url_path.lstrip("/") or "index.html"
728
+ root = STATIC_DIR.resolve()
729
+ target = (root / rel).resolve()
730
+ if (
731
+ not target.is_relative_to(root)
732
+ or any(p.startswith(".") for p in target.relative_to(root).parts)
733
+ or not target.is_file()
734
+ ):
735
+ raise NotFound(f"No file {url_path}")
736
+ st = target.stat()
737
+ data = target.read_bytes()
738
+ ctype = CONTENT_TYPES.get(target.suffix.lower()) or (
739
+ mimetypes.guess_type(target.name)[0] or "application/octet-stream"
740
+ )
741
+ gz = None
742
+ if len(data) > GZIP_MIN_BYTES and self._accepts_gzip():
743
+ cached = self.server.gzip_cache.get(target)
744
+ if cached is not None and cached[:2] == (st.st_mtime_ns, st.st_size):
745
+ gz = cached[2]
746
+ else:
747
+ gz = gzip.compress(data, compresslevel=GZIP_LEVEL)
748
+ self.server.gzip_cache[target] = (st.st_mtime_ns, st.st_size, gz)
749
+ etag = f'W/"{st.st_mtime_ns:x}-{st.st_size:x}"'
750
+ self.send_body(HTTPStatus.OK, data, ctype, REVALIDATE, etag, gz)