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/gitio.py ADDED
@@ -0,0 +1,391 @@
1
+ """Git calls used by diffdesk.
2
+
3
+ Every call passes a list of arguments to ``git`` (never a shell string) and
4
+ validates revisions and paths first. Calls that handle many subjects read
5
+ their input from standard input, so the number of git processes grows with
6
+ the number of repositories, not with the number of subjects.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import subprocess
13
+ from pathlib import Path, PurePosixPath
14
+ from typing import Any
15
+
16
+ GIT_TIMEOUT_S = 60
17
+ HEX_SHA = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
18
+ _HEX_SHA_BYTES = re.compile(rb"[0-9a-f]{40}|[0-9a-f]{64}")
19
+ _REF_FORBIDDEN = re.compile(r"[\s\x00-\x1f\x7f:]")
20
+ _PATH_FORBIDDEN = re.compile(r"[\x00-\x1f\x7f\\]")
21
+ _TREE_PAIR_LINE = re.compile(rb"[0-9a-f]{40,64} [0-9a-f]{40,64}\n")
22
+ _HUNK_HEADER = re.compile(rb"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
23
+
24
+ Numstat = dict[str, list[int | None]]
25
+
26
+
27
+ class GitError(RuntimeError):
28
+ """A git command failed, timed out, or could not start."""
29
+
30
+
31
+ class InvalidInput(ValueError):
32
+ """A subject ID, package, revision or path fails validation."""
33
+
34
+
35
+ def check_ref(ref: Any) -> str:
36
+ """Return `ref` if it is safe to pass to git as one revision.
37
+
38
+ Parameters
39
+ ----------
40
+ ref : Any
41
+ Value from a subject file or a request.
42
+
43
+ Returns
44
+ -------
45
+ str
46
+ The unchanged revision.
47
+
48
+ Raises
49
+ ------
50
+ InvalidInput
51
+ If `ref` is not a non-empty string, starts with ``-``, contains
52
+ ``..``, ``:``, white space or a control character.
53
+ """
54
+ if (
55
+ not isinstance(ref, str)
56
+ or not ref
57
+ or ref.startswith("-")
58
+ or ".." in ref
59
+ or _REF_FORBIDDEN.search(ref)
60
+ ):
61
+ raise InvalidInput(f"Invalid git revision: {ref!r}")
62
+ return ref
63
+
64
+
65
+ def check_path(path: Any) -> str:
66
+ """Return `path` if it is a relative POSIX path in normal form.
67
+
68
+ Parameters
69
+ ----------
70
+ path : Any
71
+ Value from a subject file or a request.
72
+
73
+ Returns
74
+ -------
75
+ str
76
+ The unchanged path.
77
+
78
+ Raises
79
+ ------
80
+ InvalidInput
81
+ If `path` is empty, absolute, starts with ``~``, has a ``..``
82
+ component, a backslash or a control character, or is not in normal
83
+ form (for example ``a//b``, ``./a`` or ``a/``).
84
+ """
85
+ if not isinstance(path, str) or not path or _PATH_FORBIDDEN.search(path):
86
+ raise InvalidInput(f"Invalid path: {path!r}")
87
+ pure = PurePosixPath(path)
88
+ if pure.is_absolute() or path.startswith("~") or ".." in pure.parts or pure.as_posix() != path:
89
+ raise InvalidInput(f"Path must be relative, normal and without '..': {path!r}")
90
+ return path
91
+
92
+
93
+ def run_git(repo: str, args: list[str], stdin: bytes = b"") -> bytes:
94
+ """Run ``git -C <repo> <args>`` and return its standard output.
95
+
96
+ Parameters
97
+ ----------
98
+ repo : str
99
+ Repository folder.
100
+ args : list of str
101
+ Git subcommand and its arguments.
102
+ stdin : bytes, optional
103
+ Data for the standard input of git. Default: empty, so that git
104
+ never reads the standard input of diffdesk (the MCP channel of
105
+ ``diffdesk mcp``).
106
+
107
+ Returns
108
+ -------
109
+ bytes
110
+ Standard output.
111
+
112
+ Raises
113
+ ------
114
+ GitError
115
+ If `repo` is not a folder, git cannot start, git times out after
116
+ ``GIT_TIMEOUT_S`` seconds, or git exits with a nonzero code.
117
+ """
118
+ if not Path(repo).is_dir():
119
+ raise GitError(f"Repository folder not found: {repo}")
120
+ try:
121
+ res = subprocess.run(
122
+ ["git", "--literal-pathspecs", "-C", repo, *args],
123
+ input=stdin,
124
+ capture_output=True,
125
+ timeout=GIT_TIMEOUT_S,
126
+ check=False,
127
+ )
128
+ except subprocess.TimeoutExpired as exc:
129
+ raise GitError(f"git {args[0]} took more than {GIT_TIMEOUT_S} s in {repo}") from exc
130
+ except OSError as exc:
131
+ raise GitError(f"Cannot run git: {exc}") from exc
132
+ if res.returncode != 0:
133
+ msg = res.stderr.decode("utf-8", errors="replace").strip()
134
+ raise GitError(f"git {args[0]} failed in {repo}: {msg}")
135
+ return res.stdout
136
+
137
+
138
+ def resolve(repo: str, revs: list[str], kind: str) -> dict[str, str | None]:
139
+ """Map each revision to the ID of the object of type `kind` it names.
140
+
141
+ Parameters
142
+ ----------
143
+ repo : str
144
+ Repository folder.
145
+ revs : list of str
146
+ Revisions, already checked with `check_ref`.
147
+ kind : {"commit", "tree"}
148
+ Object type to peel each revision to.
149
+
150
+ Returns
151
+ -------
152
+ dict
153
+ Revision to object ID, or to `None` if git cannot find it.
154
+ """
155
+ uniq = list(dict.fromkeys(revs))
156
+ if not uniq:
157
+ return {}
158
+ data = "".join(f"{rev}^{{{kind}}}\n" for rev in uniq).encode()
159
+ lines = run_git(repo, ["cat-file", "--batch-check=%(objectname)"], data).decode().splitlines()
160
+ if len(lines) != len(uniq):
161
+ raise GitError(f"git cat-file gave {len(lines)} lines for {len(uniq)} revisions")
162
+ return {
163
+ rev: (line if HEX_SHA.fullmatch(line) else None)
164
+ for rev, line in zip(uniq, lines, strict=True)
165
+ }
166
+
167
+
168
+ def numstat_many(repo: str, pairs: list[tuple[str, str]]) -> dict[tuple[str, str], Numstat | None]:
169
+ """Return the added and deleted line counts per file for many diffs.
170
+
171
+ One ``git cat-file`` call resolves every revision to a tree, then one
172
+ ``git diff-tree --stdin`` call compares all tree pairs.
173
+
174
+ Parameters
175
+ ----------
176
+ repo : str
177
+ Repository folder.
178
+ pairs : list of (str, str)
179
+ ``(base, head)`` revisions, already checked with `check_ref`.
180
+
181
+ Returns
182
+ -------
183
+ dict
184
+ ``(base, head)`` to ``{path: [added, deleted]}``, where both counts
185
+ are `None` for a binary file. A pair maps to `None` if git cannot
186
+ find one of its revisions.
187
+ """
188
+ pairs = list(dict.fromkeys(pairs))
189
+ trees = resolve(repo, [rev for pair in pairs for rev in pair], "tree")
190
+ result: dict[tuple[str, str], Numstat | None] = dict.fromkeys(pairs)
191
+ todo = [(b, h) for b, h in pairs if trees[b] and trees[h]]
192
+ if not todo:
193
+ return result
194
+ data = "".join(f"{trees[b]} {trees[h]}\n" for b, h in todo).encode()
195
+ out = run_git(
196
+ repo,
197
+ ["diff-tree", "--stdin", "-r", "-z", "--numstat", "--no-renames", "--always"],
198
+ data,
199
+ )
200
+ # Each input line is echoed as a header that ends with a newline; each
201
+ # file line ends with NUL.
202
+ blocks: list[Numstat] = []
203
+ pos = 0
204
+ while pos < len(out):
205
+ header = _TREE_PAIR_LINE.match(out, pos)
206
+ if header:
207
+ blocks.append({})
208
+ pos = header.end()
209
+ continue
210
+ end = out.index(b"\0", pos)
211
+ added, deleted, path = out[pos:end].split(b"\t", 2)
212
+ pos = end + 1
213
+ if not blocks:
214
+ raise GitError("git diff-tree printed a file before the first tree pair")
215
+ blocks[-1][path.decode("utf-8", errors="replace")] = [
216
+ None if added == b"-" else int(added),
217
+ None if deleted == b"-" else int(deleted),
218
+ ]
219
+ if len(blocks) != len(todo):
220
+ raise GitError(f"git diff-tree gave {len(blocks)} results for {len(todo)} tree pairs")
221
+ result.update(zip(todo, blocks, strict=True))
222
+ return result
223
+
224
+
225
+ def commit_order(repo: str, heads: list[str]) -> dict[str, int]:
226
+ """Return the position of each head in topological commit order.
227
+
228
+ Parameters
229
+ ----------
230
+ repo : str
231
+ Repository folder.
232
+ heads : list of str
233
+ Revisions, already checked with `check_ref`.
234
+
235
+ Returns
236
+ -------
237
+ dict
238
+ Revision to its 0-based index in ``git rev-list --reverse
239
+ --topo-order`` of all the heads (parents before children).
240
+ Revisions that git cannot find are absent.
241
+ """
242
+ commits = resolve(repo, heads, "commit")
243
+ shas = sorted({sha for sha in commits.values() if sha})
244
+ if not shas:
245
+ return {}
246
+ out = run_git(
247
+ repo,
248
+ ["rev-list", "--reverse", "--topo-order", "--stdin"],
249
+ ("\n".join(shas) + "\n").encode(),
250
+ )
251
+ position = {sha: i for i, sha in enumerate(out.decode().split())}
252
+ return {rev: position[sha] for rev, sha in commits.items() if sha in position}
253
+
254
+
255
+ def read_blobs(repo: str, specs: list[tuple[str, str]]) -> list[bytes | None]:
256
+ """Return the content of each ``(revision, path)`` with one git call.
257
+
258
+ Parameters
259
+ ----------
260
+ repo : str
261
+ Repository folder.
262
+ specs : list of (str, str)
263
+ Revisions checked with `check_ref` and paths checked with
264
+ `check_path`.
265
+
266
+ Returns
267
+ -------
268
+ list
269
+ File content, or `None` if the path is absent at that revision or
270
+ is not a regular file.
271
+ """
272
+ if not specs:
273
+ return []
274
+ data = "".join(f"{rev}:{path}\n" for rev, path in specs).encode()
275
+ out = run_git(repo, ["cat-file", "--batch"], data)
276
+ result: list[bytes | None] = []
277
+ pos = 0
278
+ for _ in specs:
279
+ end = out.index(b"\n", pos)
280
+ parts = out[pos:end].split(b" ")
281
+ pos = end + 1
282
+ if len(parts) == 3 and _HEX_SHA_BYTES.fullmatch(parts[0]) and parts[2].isdigit():
283
+ size = int(parts[2])
284
+ body = out[pos : pos + size]
285
+ pos += size + 1
286
+ result.append(body if parts[1] == b"blob" else None)
287
+ else:
288
+ result.append(None)
289
+ return result
290
+
291
+
292
+ def diff_hunks(
293
+ repo: str, base: str, head: str, path: str, context: int, ignore_space: bool
294
+ ) -> tuple[list[dict[str, Any]], bool]:
295
+ """Return the hunks of ``git diff -U<context> base head -- path``.
296
+
297
+ Parameters
298
+ ----------
299
+ repo : str
300
+ Repository folder.
301
+ base, head : str
302
+ Revisions, already checked with `check_ref`.
303
+ path : str
304
+ File path, already checked with `check_path`.
305
+ context : int
306
+ Number of unchanged lines around each change.
307
+ ignore_space : bool
308
+ Pass ``-w`` to git.
309
+
310
+ Returns
311
+ -------
312
+ hunks : list of dict
313
+ ``{old_start, old_lines, new_start, new_lines, lines}``. Each line
314
+ starts with ``+``, ``-``, a space, or ``\\`` (git's "No newline at
315
+ end of file" note).
316
+ binary : bool
317
+ `True` if git reports the file as binary.
318
+ """
319
+ args = [
320
+ "diff",
321
+ "--no-color",
322
+ "--no-ext-diff",
323
+ "--no-textconv",
324
+ "--no-renames",
325
+ f"-U{context}",
326
+ ]
327
+ if ignore_space:
328
+ args.append("-w")
329
+ out = run_git(repo, [*args, base, head, "--", path])
330
+ hunks: list[dict[str, Any]] = []
331
+ binary = False
332
+ current: dict[str, Any] | None = None
333
+ for raw in out.split(b"\n"):
334
+ match = _HUNK_HEADER.match(raw)
335
+ if match:
336
+ old_start, old_lines, new_start, new_lines = match.groups()
337
+ current = {
338
+ "old_start": int(old_start),
339
+ "old_lines": 1 if old_lines is None else int(old_lines),
340
+ "new_start": int(new_start),
341
+ "new_lines": 1 if new_lines is None else int(new_lines),
342
+ "lines": [],
343
+ }
344
+ hunks.append(current)
345
+ elif current is None:
346
+ binary = binary or raw.startswith(b"Binary files ")
347
+ elif raw[:1] in (b"+", b"-", b" ", b"\\"):
348
+ current["lines"].append(raw.decode("utf-8", errors="replace"))
349
+ return hunks, binary
350
+
351
+
352
+ def current_branch(repo: str) -> str | None:
353
+ """Return the short name of the branch checked out in `repo`.
354
+
355
+ Returns
356
+ -------
357
+ str or None
358
+ `None` if HEAD is detached or `repo` is not a git repository.
359
+ """
360
+ try:
361
+ name = run_git(repo, ["symbolic-ref", "--quiet", "--short", "HEAD"]).decode().strip()
362
+ except GitError:
363
+ return None
364
+ return name or None
365
+
366
+
367
+ def toplevel(folder: str) -> str | None:
368
+ """Return the top folder of the work tree that contains `folder`, or `None`.
369
+
370
+ The path uses the separator of the operating system; git prints ``/``
371
+ on Windows too.
372
+ """
373
+ try:
374
+ out = run_git(folder, ["rev-parse", "--show-toplevel"]).decode().strip()
375
+ except GitError:
376
+ return None
377
+ return str(Path(out)) if out else None
378
+
379
+
380
+ def first_commit(repo: str) -> str | None:
381
+ """Return the oldest root commit reachable from HEAD, or `None` if there is no commit."""
382
+ try:
383
+ out = run_git(repo, ["rev-list", "--max-parents=0", "--reverse", "HEAD"]).decode()
384
+ except GitError:
385
+ return None
386
+ return out.split()[0] if out.split() else None
387
+
388
+
389
+ def empty_tree(repo: str) -> str:
390
+ """Return the ID of the empty tree in the object format of `repo`."""
391
+ return run_git(repo, ["hash-object", "-t", "tree", "--stdin"], b"").decode().strip()