Files

354 lines
13 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Shared by the diff-viewer's actions (stdlib only).
Two doors to the diffs:
* the hub's ``diff.read`` bridges — ``GET <AIA_TOOLS_URL>/plugins/diff-viewer/
hub/diff/…`` (core keeps the diff engines; the caller's own conversations,
a guest restricted as the app's ``/api/*`` diff routes are);
* the ``commits`` plugin's exports ``list`` / ``diff`` (``POST
<AIA_TOOLS_URL>/plugins/commits/actions/<act>``) while it is active for the
caller (``AIA_ACTIVE_PLUGINS``, our ``optionalRequires``) — it knows the
commits a git shim reported that the transcript never showed. When it fails
the core bridge answers instead.
The review (Viewed ticks + draft comments) lives in the caller's data dir,
one file per conversation: ``$AIA_PLUGIN_DATA_DIR/reviews/<conversation>.json``
= ``{"viewed": {"<repo>|<path>": "<signature>"}, "comments": [...],
"touched": <ms>}``. A tick stores the diff's signature (counts + hunk headers,
``AiaDiff.signature``): a later change to the file changes it and the tick
drops. At most ``MAX_CONVS`` conversations are kept (least recently touched
dropped).
"""
from __future__ import annotations
import fcntl
import json
import os
import pathlib
import re
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any
sys.dont_write_bytecode = True
PLUGIN_ID = "diff-viewer"
PEER = "commits"
CID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")
SHA_RE = re.compile(r"[0-9a-fA-F]{4,64}")
REPO_RE = re.compile(r"(project|service):[A-Za-z0-9._-]{1,128}|super:_")
COMMENT_ID_RE = re.compile(r"c[a-z0-9]{4,32}")
MAX_CONVS = 60
MAX_COMMENTS = 500
MAX_VIEWED = 4000
MAX_BODY = 8000
MAX_LINE_TEXT = 2000
MAX_KEY = 1200
class Fail(Exception):
def __init__(self, message: str, status: int = 400, kind: str = "bad_request"):
super().__init__(message)
self.status, self.kind = status, kind
# ── I/O ──────────────────────────────────────────────────────────────────────
def read_payload() -> dict[str, Any]:
try:
p = json.loads(sys.stdin.read() or "{}")
except ValueError:
return {}
return p if isinstance(p, dict) else {}
def emit(obj: Any) -> None:
sys.stdout.write(json.dumps(obj, separators=(",", ":"), ensure_ascii=False))
def run(main) -> None:
"""Run an action: its answer on stdout, or ``{"_error": …}`` (the hub
turns it into that HTTP status) for what the caller asked wrong."""
try:
emit(main(read_payload()))
except Fail as e:
emit({"_error": {"status": e.status, "kind": e.kind, "message": str(e)}})
def conversation_id(p: dict) -> str:
for key in ("conversationId", "id", "sessionId"):
v = p.get(key)
if isinstance(v, str) and CID_RE.fullmatch(v):
return v
raise Fail("which conversation? (conversationId)")
def sha_of(p: dict) -> str:
v = p.get("sha")
if isinstance(v, str) and SHA_RE.fullmatch(v):
return v
raise Fail("a commit sha (4–64 hex digits) is needed")
def root_of(p: dict) -> str | None:
v = p.get("root")
if isinstance(v, str) and v and len(v) <= 1024 and "\x00" not in v:
return v
return None
# ── the hub ──────────────────────────────────────────────────────────────────
def _env() -> tuple[str, str]:
base = (os.environ.get("AIA_TOOLS_URL") or "").rstrip("/")
token = os.environ.get("AIA_TOOLS_TOKEN") or ""
if not base or not token:
raise Fail("no hub to ask (AIA_TOOLS_URL / AIA_TOOLS_TOKEN unset)", 500, "config")
return base, token
def _call(method: str, path: str, body: dict | None = None, timeout: float = 60.0) -> Any:
base, token = _env()
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json",
"X-Plugin-Call-Depth": os.environ.get("AIA_PLUGIN_CALL_DEPTH") or "0"}
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
req = urllib.request.Request(f"{base}/{path.lstrip('/')}", data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read() or b"null")
except urllib.error.HTTPError as e:
try:
err = json.loads(e.read() or b"{}")
except ValueError:
err = {}
msg = ""
if isinstance(err, dict):
d = err.get("error") if isinstance(err.get("error"), dict) else None
msg = (d or {}).get("message") or err.get("detail") or ""
if not isinstance(msg, str):
msg = json.dumps(msg)[:300]
raise Fail(msg or f"the hub answered {e.code}", e.code,
"not_found" if e.code == 404 else "hub") from None
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as e:
raise Fail(f"the hub didn't answer: {e}", 502, "hub") from None
def hub_get(path: str, **query: Any) -> Any:
q = {k: v for k, v in query.items() if v is not None}
qs = ("?" + urllib.parse.urlencode(q)) if q else ""
return _call("GET", f"plugins/{PLUGIN_ID}/hub/{path}{qs}")
def conv_path(cid: str) -> str:
return f"diff/conversations/{urllib.parse.quote(cid, safe='')}"
def peer_on() -> bool:
try:
active = json.loads(os.environ.get("AIA_ACTIVE_PLUGINS") or "[]")
except ValueError:
return False
return isinstance(active, list) and PEER in active
def peer(action: str, body: dict) -> Any:
return _call("POST", f"plugins/{PEER}/actions/{action}", body)
# ── commits ──────────────────────────────────────────────────────────────────
def _totals(commits: list[dict]) -> dict:
own = [c for c in commits if isinstance(c, dict) and not c.get("merge")]
return {"filesChanged": sum(int(c.get("files") or 0) for c in own),
"additions": sum(int(c.get("additions") or 0) for c in own),
"deletions": sum(int(c.get("deletions") or 0) for c in own)}
def conversation_commits(cid: str) -> dict:
"""The conversation's commits, **oldest first**: the commits plugin's list
when it is on (and answers), else the core's (newest first there)."""
if peer_on():
try:
got = peer("list", {"conversationId": cid})
if isinstance(got, dict) and isinstance(got.get("commits"), list) and "_error" not in got:
commits = [c for c in got["commits"] if isinstance(c, dict)]
repos = sorted({str(c.get("repo") or c.get("root") or "") for c in commits} - {""})
return {"id": cid, "commits": commits, "repos": repos,
"exact": got.get("exact", True) is not False,
"worker": got.get("worker"), "via": PEER, **_totals(commits)}
except Fail:
pass
core = hub_get(conv_path(cid) + "/commits")
if not isinstance(core, dict):
raise Fail("the hub gave no commit list", 502, "hub")
commits = [c for c in core.get("commits") or [] if isinstance(c, dict)]
commits.reverse()
out = {**core, "id": core.get("id") or cid, "commits": commits, "via": "core"}
for k, v in _totals(commits).items():
out.setdefault(k, v)
return out
def uncommitted(cid: str, stats: bool) -> dict:
return hub_get(conv_path(cid) + "/uncommitted", stats=1 if stats else 0)
def strip_hunks(d: dict) -> dict:
files = [{k: f.get(k) for k in ("path", "oldPath", "status", "additions", "deletions", "binary", "repo")}
for f in d.get("files") or [] if isinstance(f, dict)]
return {"files": files, "additions": d.get("additions") or 0, "deletions": d.get("deletions") or 0,
"worktrees": d.get("worktrees") or None, "subtitle": d.get("subtitle"), "source": d.get("source")}
def commit_diff(cid: str, sha: str, root: str | None) -> dict:
if peer_on():
try:
got = peer("diff", {"conversationId": cid, "sha": sha, **({"root": root} if root else {})})
if isinstance(got, dict) and isinstance(got.get("files"), list) and "_error" not in got:
return got
except Fail:
pass
return hub_get(conv_path(cid) + "/commit", sha=sha, root=root)
# ── the review ───────────────────────────────────────────────────────────────
def _data_dir() -> pathlib.Path:
d = os.environ.get("AIA_PLUGIN_DATA_DIR") or ""
if not d:
raise Fail("no data dir (AIA_PLUGIN_DATA_DIR unset)", 500, "config")
p = pathlib.Path(d) / "reviews"
p.mkdir(parents=True, exist_ok=True)
return p
def _review_file(cid: str) -> pathlib.Path:
safe = re.sub(r"[^A-Za-z0-9._-]", "_", cid)[:128].lstrip(".") or "_"
return _data_dir() / f"{safe}.json"
def _clean(r: Any) -> dict:
r = r if isinstance(r, dict) else {}
viewed = {k: v for k, v in (r.get("viewed") or {}).items()
if isinstance(k, str) and isinstance(v, str)} if isinstance(r.get("viewed"), dict) else {}
comments = [c for c in r.get("comments") or [] if isinstance(c, dict)]
return {"viewed": viewed, "comments": comments, "touched": int(r.get("touched") or 0)}
def load_review(cid: str) -> dict:
try:
return _clean(json.loads(_review_file(cid).read_text()))
except (OSError, ValueError):
return _clean({})
def _write(path: pathlib.Path, obj: dict) -> None:
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".tmp-", suffix=".json")
try:
with os.fdopen(fd, "w") as f:
json.dump(obj, f, separators=(",", ":"), ensure_ascii=False)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def _prune(keep: pathlib.Path) -> None:
files = [p for p in keep.parent.glob("*.json") if not p.name.startswith(".")]
if len(files) <= MAX_CONVS:
return
files.sort(key=lambda p: p.stat().st_mtime)
for p in files[: len(files) - MAX_CONVS]:
if p != keep:
try:
p.unlink()
except OSError:
pass
def _text(v: Any, cap: int, what: str) -> str:
if not isinstance(v, str):
raise Fail(f"{what} must be text")
if len(v) > cap:
raise Fail(f"{what} is over {cap} characters")
return v
def _comment(c: Any) -> dict:
if not isinstance(c, dict):
raise Fail("comment must be an object")
cid = c.get("id")
if not (isinstance(cid, str) and COMMENT_ID_RE.fullmatch(cid)):
cid = "c" + format(int(time.time() * 1000), "x") + os.urandom(3).hex()
out = {"id": cid,
"file": _text(c.get("file"), MAX_KEY, "comment.file"),
"path": _text(c.get("path"), MAX_KEY, "comment.path"),
"view": _text(c.get("view") or "all", 80, "comment.view"),
"body": _text(c.get("body"), MAX_BODY, "comment.body"),
"at": int(c.get("at") or time.time() * 1000)}
if not out["body"].strip():
raise Fail("an empty comment")
ln = c.get("line")
if isinstance(ln, dict):
side = "old" if ln.get("side") == "old" else "new"
try:
no = int(ln.get("no"))
except (TypeError, ValueError):
raise Fail("comment.line.no must be a number") from None
typ = ln.get("type") if ln.get("type") in ("add", "del", "ctx") else "ctx"
out["line"] = {"side": side, "no": no, "text": str(ln.get("text") or "")[:MAX_LINE_TEXT], "type": typ}
return out
def apply_op(r: dict, p: dict) -> dict:
op = p.get("op")
if op == "viewed":
key = _text(p.get("file"), MAX_KEY, "file")
sig = p.get("sig")
if sig is None or sig is False:
r["viewed"].pop(key, None)
else:
r["viewed"][key] = _text(sig, 120, "sig")
if len(r["viewed"]) > MAX_VIEWED:
raise Fail("too many viewed files")
elif op == "add":
c = _comment(p.get("comment"))
r["comments"] = [x for x in r["comments"] if x.get("id") != c["id"]] + [c]
if len(r["comments"]) > MAX_COMMENTS:
raise Fail(f"a review holds at most {MAX_COMMENTS} comments")
elif op == "edit":
body = _text(p.get("body"), MAX_BODY, "body")
for c in r["comments"]:
if c.get("id") == p.get("id"):
c["body"] = body
elif op == "delete":
r["comments"] = [c for c in r["comments"] if c.get("id") != p.get("id")]
elif op == "clear":
r["comments"] = []
elif op == "reset":
r["comments"], r["viewed"] = [], {}
else:
raise Fail("op must be viewed, add, edit, delete, clear or reset")
return r
def save_review(cid: str, p: dict) -> dict:
path = _review_file(cid)
lock = path.with_name(".lock")
with open(lock, "a") as lk:
fcntl.flock(lk, fcntl.LOCK_EX)
r = apply_op(load_review(cid), p)
r["touched"] = int(time.time() * 1000)
_write(path, r)
_prune(path)
return r