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/cli.py ADDED
@@ -0,0 +1,329 @@
1
+ """Command line: serve, init, validate, add, reviews, guide and mcp."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import os
9
+ import sys
10
+ import webbrowser
11
+ from pathlib import Path
12
+
13
+ from . import __version__, gitio
14
+ from .agent import (
15
+ GUIDE_PATH,
16
+ collect_reviews,
17
+ create_subject,
18
+ subject_files,
19
+ validate_subjects,
20
+ )
21
+ from .config import CONFIG_NAME, ConfigError, load_config
22
+ from .gitio import GitError, InvalidInput
23
+ from .index import STATUSES
24
+ from .mcp import serve_stdio
25
+ from .server import DiffdeskServer
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ CONFIG_TEMPLATE = """\
30
+ # diffdesk review root. Every value is optional.
31
+ title = {title}
32
+
33
+ [paths]
34
+ subjects = "subjects"
35
+ reviews = "reviews.json"
36
+ edits = "edits"
37
+ cache = ".diffdesk-cache"
38
+
39
+ # [packages.mypackage]
40
+ # depends_on = ["otherpackage"]
41
+
42
+ [ui]
43
+ theme = "system"
44
+ editor = "codemirror"
45
+ """
46
+
47
+
48
+ def resolve_root(arg: str | None) -> Path:
49
+ """Return the review root of a command.
50
+
51
+ Parameters
52
+ ----------
53
+ arg : str or None
54
+ The review root given on the command line, if any.
55
+
56
+ Returns
57
+ -------
58
+ Path
59
+ `arg` if it is given, else the environment variable ``DIFFDESK_ROOT``
60
+ if it is set and not empty, else the current folder.
61
+ """
62
+ return Path(arg or os.environ.get("DIFFDESK_ROOT") or ".")
63
+
64
+
65
+ def cmd_validate(root: Path) -> int:
66
+ """Check every subject file of a review root and print the problems.
67
+
68
+ Returns
69
+ -------
70
+ int
71
+ 0 if no problem was found, else 1. Warnings do not change it.
72
+ """
73
+ result = validate_subjects(load_config(root))
74
+ problems, warnings = result["problems"], result["warnings"]
75
+ for line in problems:
76
+ print(f"problem: {line}")
77
+ for line in warnings:
78
+ print(f"warning: {line}")
79
+ print(f"{result['files']} subject files, {len(problems)} problems, {len(warnings)} warnings")
80
+ return 1 if problems else 0
81
+
82
+
83
+ def cmd_init(root: Path) -> int:
84
+ """Create the layout of a review root and, if possible, one example subject.
85
+
86
+ The example points at the first commit of the git repository that holds
87
+ `root` and is written only if that repository has a commit and the
88
+ subjects folder has no subject yet.
89
+
90
+ Returns
91
+ -------
92
+ int
93
+ Always 0.
94
+ """
95
+ root.mkdir(parents=True, exist_ok=True)
96
+ created: list[Path] = []
97
+ config_path = root / CONFIG_NAME
98
+ if not config_path.exists():
99
+ config_path.write_text(
100
+ CONFIG_TEMPLATE.format(title=json.dumps(root.resolve().name)), encoding="utf-8"
101
+ )
102
+ created.append(config_path)
103
+ config = load_config(root)
104
+ for folder in (config.subjects, config.edits):
105
+ if not folder.exists():
106
+ folder.mkdir(parents=True)
107
+ created.append(folder)
108
+ repo = gitio.toplevel(str(config.root))
109
+ head = gitio.first_commit(repo) if repo else None
110
+ if repo and head and not subject_files(config.subjects):
111
+ example = config.subjects / "example" / "EXAMPLE-1.json"
112
+ subject = {
113
+ "id": "EXAMPLE-1",
114
+ "package": "example",
115
+ "title": f"First commit of {Path(repo).name}",
116
+ "priority": "P3",
117
+ "origin": "new",
118
+ "recommended": "accept",
119
+ "summary": "Example made by `diffdesk init`. Delete it when you add real subjects.",
120
+ "why": (
121
+ "**Problem**\nNone. This subject shows the format.\n\n"
122
+ "**Fix logic**\n`base` is the empty tree, so the diff shows every file "
123
+ "of the first commit."
124
+ ),
125
+ "repo": repo,
126
+ "base": gitio.empty_tree(repo),
127
+ "head": head,
128
+ "files": [],
129
+ "tests": "not run",
130
+ }
131
+ example.parent.mkdir(parents=True, exist_ok=True)
132
+ example.write_text(json.dumps(subject, indent=2) + "\n", encoding="utf-8")
133
+ created.append(example)
134
+ for path in created:
135
+ print(f"created {path}")
136
+ if not created:
137
+ print(f"nothing to create in {config.root}")
138
+ return 0
139
+
140
+
141
+ def cmd_add(root: Path, args: argparse.Namespace) -> int:
142
+ """Write one subject file for a git commit and print where it went.
143
+
144
+ Returns
145
+ -------
146
+ int
147
+ Always 0. Errors raise.
148
+ """
149
+ why = args.why
150
+ if args.why_file == "-":
151
+ # Bytes, then UTF-8: text stdin uses the locale encoding on Windows.
152
+ why = sys.stdin.buffer.read().decode("utf-8")
153
+ elif args.why_file is not None:
154
+ why = Path(args.why_file).read_text(encoding="utf-8")
155
+ path, subject = create_subject(
156
+ load_config(root),
157
+ repo=Path(args.repo),
158
+ subject_id=args.id,
159
+ title=args.title,
160
+ commit=args.commit,
161
+ base=args.base,
162
+ head=args.head,
163
+ package=args.package,
164
+ summary=args.summary,
165
+ why=why,
166
+ priority=args.priority,
167
+ recommended=args.recommended,
168
+ tags=args.tags,
169
+ branch=args.branch,
170
+ force=args.force,
171
+ )
172
+ if args.json:
173
+ print(json.dumps(subject, indent=2))
174
+ else:
175
+ print(
176
+ f"wrote {path} (changed paths: {len(subject['files'])}, "
177
+ f"{subject['base'][:12]}..{subject['head'][:12]})"
178
+ )
179
+ return 0
180
+
181
+
182
+ def cmd_reviews(
183
+ root: Path, statuses: list[str] | None, package: str | None, subject_id: str | None, fmt: str
184
+ ) -> int:
185
+ """Print the review state of the subjects as JSON or as a short table.
186
+
187
+ Returns
188
+ -------
189
+ int
190
+ Always 0. Errors raise.
191
+ """
192
+ items = collect_reviews(
193
+ load_config(root), statuses=statuses, package=package, subject_id=subject_id
194
+ )
195
+ if fmt == "json":
196
+ print(json.dumps(items, indent=2))
197
+ return 0
198
+ rows = [("STATUS", "SUBJECT", "EDITS", "AT", "TITLE")]
199
+ rows += [
200
+ (
201
+ item["status"],
202
+ f"{item['package']}/{item['id']}",
203
+ str(len(item["edits"])),
204
+ str(item["at"] or "-"),
205
+ item["title"],
206
+ )
207
+ for item in items
208
+ ]
209
+ widths = [max(len(row[col]) for row in rows) for col in range(4)]
210
+ for row in rows:
211
+ cells = [cell.ljust(w) for cell, w in zip(row[:4], widths, strict=True)]
212
+ print(" ".join([*cells, row[4]]))
213
+ print(f"{len(items)} subjects")
214
+ return 0
215
+
216
+
217
+ def cmd_serve(root: Path, host: str, port: int, open_browser: bool) -> int:
218
+ """Run the HTTP server until interrupted."""
219
+ config = load_config(root)
220
+ try:
221
+ httpd = DiffdeskServer(config, host, port)
222
+ except OSError as exc:
223
+ print(f"diffdesk: cannot listen on {host}:{port}: {exc}", file=sys.stderr)
224
+ return 1
225
+ bound = httpd.server_address[1]
226
+ shown = "127.0.0.1" if host in ("", "0.0.0.0", "::") else host
227
+ url = f"http://{f'[{shown}]' if ':' in shown else shown}:{bound}/"
228
+ print(f"diffdesk {__version__} on {url} (root: {config.root})", flush=True)
229
+ if open_browser:
230
+ webbrowser.open(url)
231
+ try:
232
+ httpd.serve_forever()
233
+ except KeyboardInterrupt:
234
+ pass
235
+ finally:
236
+ httpd.server_close()
237
+ return 0
238
+
239
+
240
+ def main(argv: list[str] | None = None) -> int:
241
+ """Parse the command line and run one subcommand.
242
+
243
+ Returns
244
+ -------
245
+ int
246
+ Exit code.
247
+ """
248
+ parser = argparse.ArgumentParser(prog="diffdesk", description=__doc__.splitlines()[0])
249
+ parser.add_argument("--version", action="version", version=f"diffdesk {__version__}")
250
+ parser.add_argument("-v", "--verbose", action="store_true", help="log every request")
251
+ sub = parser.add_subparsers(dest="command", required=True)
252
+ root_help = "review root (default: $DIFFDESK_ROOT, else the current folder)"
253
+ root_arg = argparse.ArgumentParser(add_help=False)
254
+ root_arg.add_argument("root", nargs="?", help=root_help)
255
+ serve = sub.add_parser(
256
+ "serve", parents=[root_arg], help="serve the review desk on a local port"
257
+ )
258
+ serve.add_argument("--host", default="127.0.0.1", help="address to bind (default: 127.0.0.1)")
259
+ serve.add_argument("--port", type=int, default=8765, help="port (default: 8765; 0: any)")
260
+ serve.add_argument("--open", action="store_true", help="open the page in the browser")
261
+ sub.add_parser("init", parents=[root_arg], help="create a review root")
262
+ sub.add_parser("validate", parents=[root_arg], help="check every subject file")
263
+
264
+ add = sub.add_parser("add", parents=[root_arg], help="write a subject file for a git commit")
265
+ add.add_argument("--repo", default=".", help="folder inside the git work tree (default: .)")
266
+ add.add_argument("--commit", help="commit to review against its first parent (default: HEAD)")
267
+ add.add_argument("--base", help="old side of the diff; use with --head")
268
+ add.add_argument("--head", help="new side of the diff; use with --base")
269
+ add.add_argument("--id", required=True, help="subject ID, unique inside its package")
270
+ add.add_argument("--title", required=True, help="one-line title")
271
+ add.add_argument("--package", help="package name (default: name of the work tree folder)")
272
+ add.add_argument("--summary", help="one sentence: what is wrong and what the change does")
273
+ why = add.add_mutually_exclusive_group()
274
+ why.add_argument("--why", help="reasons for the change, in Markdown")
275
+ why.add_argument(
276
+ "--why-file", metavar="PATH", help="read the reasons from PATH ('-': standard input)"
277
+ )
278
+ add.add_argument("--priority", help="for example P1, P2 or P3")
279
+ add.add_argument("--recommended", help="suggested verdict, for example accept")
280
+ add.add_argument("--tag", action="append", dest="tags", help="free label (repeatable)")
281
+ add.add_argument("--branch", help="branch name for the tree (default: the checked-out one)")
282
+ add.add_argument("--force", action="store_true", help="replace an existing subject file")
283
+ add.add_argument("--json", action="store_true", help="print the written subject as JSON")
284
+
285
+ reviews = sub.add_parser("reviews", parents=[root_arg], help="print verdicts and edits")
286
+ reviews.add_argument(
287
+ "--status",
288
+ action="append",
289
+ dest="statuses",
290
+ choices=STATUSES,
291
+ help="keep only subjects with this status (repeatable)",
292
+ )
293
+ reviews.add_argument("--package", help="keep only subjects of this package")
294
+ reviews.add_argument("--id", help="keep only subjects with this ID")
295
+ reviews.add_argument(
296
+ "--format", choices=("json", "text"), default="json", help="output (default: json)"
297
+ )
298
+
299
+ sub.add_parser("guide", help="print the guide for coding agents")
300
+ mcp = sub.add_parser("mcp", help="run an MCP server on standard input and output")
301
+ mcp.add_argument("--root", help=root_help)
302
+ args = parser.parse_args(argv)
303
+
304
+ logging.basicConfig(
305
+ level=logging.DEBUG if args.verbose else logging.INFO,
306
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s",
307
+ )
308
+ if args.command == "guide":
309
+ sys.stdout.write(GUIDE_PATH.read_text(encoding="utf-8"))
310
+ return 0
311
+ root = resolve_root(args.root)
312
+ if args.command == "mcp":
313
+ return serve_stdio(root)
314
+ try:
315
+ if args.command == "serve":
316
+ return cmd_serve(root, args.host, args.port, args.open)
317
+ if args.command == "init":
318
+ return cmd_init(root)
319
+ if args.command == "add":
320
+ return cmd_add(root, args)
321
+ if args.command == "reviews":
322
+ return cmd_reviews(root, args.statuses, args.package, args.id, args.format)
323
+ return cmd_validate(root)
324
+ except ConfigError as exc:
325
+ print(f"diffdesk: {exc}", file=sys.stderr)
326
+ return 2
327
+ except (InvalidInput, GitError, OSError, ValueError) as exc:
328
+ print(f"diffdesk: {exc}", file=sys.stderr)
329
+ return 1
diffdesk/config.py ADDED
@@ -0,0 +1,130 @@
1
+ """Review root configuration read from ``diffdesk.toml``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass
7
+ from pathlib import Path, PurePosixPath
8
+ from typing import Any
9
+
10
+ CONFIG_NAME = "diffdesk.toml"
11
+ DEFAULT_PATHS = {
12
+ "subjects": "subjects",
13
+ "reviews": "reviews.json",
14
+ "edits": "edits",
15
+ "cache": ".diffdesk-cache",
16
+ }
17
+ DEFAULT_UI: dict[str, Any] = {"theme": "system", "editor": "codemirror"}
18
+
19
+
20
+ class ConfigError(ValueError):
21
+ """``diffdesk.toml`` holds a value that diffdesk cannot use."""
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Config:
26
+ """Settings of one review root.
27
+
28
+ Attributes
29
+ ----------
30
+ root : Path
31
+ Absolute path of the review root.
32
+ title : str
33
+ Title shown in the browser. Default: the name of the root folder.
34
+ subjects, reviews, edits, cache : Path
35
+ Absolute paths inside `root`.
36
+ packages : dict
37
+ Package name to the list of package names it depends on.
38
+ ui : dict
39
+ Default values for the settings panel of the browser.
40
+ """
41
+
42
+ root: Path
43
+ title: str
44
+ subjects: Path
45
+ reviews: Path
46
+ edits: Path
47
+ cache: Path
48
+ packages: dict[str, list[str]]
49
+ ui: dict[str, Any]
50
+
51
+
52
+ def _rel_path(key: str, value: Any) -> PurePosixPath:
53
+ if not isinstance(value, str) or not value.strip():
54
+ raise ConfigError(f"[paths] {key} must be a non-empty string: {value!r}")
55
+ pure = PurePosixPath(value)
56
+ if pure.is_absolute() or value.startswith("~") or "\\" in value or ".." in pure.parts:
57
+ raise ConfigError(f"[paths] {key} must be relative to the root, without '..': {value!r}")
58
+ return pure
59
+
60
+
61
+ def _str_list(where: str, value: Any) -> list[str]:
62
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
63
+ raise ConfigError(f"{where} must be a list of strings: {value!r}")
64
+ return list(value)
65
+
66
+
67
+ def load_config(root: Path) -> Config:
68
+ """Read ``<root>/diffdesk.toml``, or use the defaults if it is absent.
69
+
70
+ Parameters
71
+ ----------
72
+ root : Path
73
+ The review root folder.
74
+
75
+ Returns
76
+ -------
77
+ Config
78
+ The settings, with every path made absolute.
79
+
80
+ Raises
81
+ ------
82
+ ConfigError
83
+ If the file is not valid TOML, a value has the wrong type, or a path
84
+ is absolute or contains ``..``.
85
+ """
86
+ root = root.resolve()
87
+ data: dict[str, Any] = {}
88
+ path = root / CONFIG_NAME
89
+ if path.is_file():
90
+ try:
91
+ with path.open("rb") as fh:
92
+ data = tomllib.load(fh)
93
+ except tomllib.TOMLDecodeError as exc:
94
+ raise ConfigError(f"{path}: {exc}") from exc
95
+
96
+ title = data.get("title", root.name)
97
+ if not isinstance(title, str):
98
+ raise ConfigError(f"title must be a string: {title!r}")
99
+
100
+ paths_table = data.get("paths", {})
101
+ if not isinstance(paths_table, dict):
102
+ raise ConfigError("[paths] must be a table")
103
+ paths = {
104
+ key: root / _rel_path(key, paths_table.get(key, default))
105
+ for key, default in DEFAULT_PATHS.items()
106
+ }
107
+
108
+ packages_table = data.get("packages", {})
109
+ if not isinstance(packages_table, dict):
110
+ raise ConfigError("[packages] must be a table")
111
+ packages: dict[str, list[str]] = {}
112
+ for name, table in packages_table.items():
113
+ if not isinstance(table, dict):
114
+ raise ConfigError(f"[packages.{name}] must be a table")
115
+ packages[name] = _str_list(f"[packages.{name}] depends_on", table.get("depends_on", []))
116
+
117
+ ui_table = data.get("ui", {})
118
+ if not isinstance(ui_table, dict):
119
+ raise ConfigError("[ui] must be a table")
120
+
121
+ return Config(
122
+ root=root,
123
+ title=title,
124
+ subjects=paths["subjects"],
125
+ reviews=paths["reviews"],
126
+ edits=paths["edits"],
127
+ cache=paths["cache"],
128
+ packages=packages,
129
+ ui={**DEFAULT_UI, **ui_table},
130
+ )