web_git.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. """Backend git operations for the desktop coding rail + review pane.
  2. Mirrors the desktop's Electron-local git ops over the dashboard's authenticated
  3. REST surface so a *remote* gateway acts on the right filesystem. Shells out to
  4. system ``git`` (and ``gh`` for PRs). Reads degrade to ``None``/empty on a
  5. non-repo; mutations raise so the renderer can toast. ``cwd`` is already hardened.
  6. """
  7. from __future__ import annotations
  8. import itertools
  9. import json
  10. import os
  11. import re
  12. import shutil
  13. import subprocess
  14. from collections.abc import Callable
  15. from pathlib import Path
  16. from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env
  17. _GIT_TIMEOUT = 30
  18. _GH_TIMEOUT = 30
  19. # How much of a failed gh command's stderr rides into the surfaced error. A
  20. # toast can carry the informative tail; the full traceback helps nobody (#87731).
  21. _GH_ERR_TAIL_CHARS = 400
  22. _UNTRACKED_LINE_MAX_BYTES = 1024 * 1024
  23. _UNTRACKED_SCAN_CAP = 500
  24. _COMMIT_CONTEXT_DIFF_MAX_CHARS = 120_000
  25. _COMMIT_CONTEXT_UNTRACKED_MAX = 80
  26. _TRUNK_BRANCHES = ("main", "master")
  27. def _run(argv: list[str], cwd: str, timeout: int, env: dict) -> subprocess.CompletedProcess | None:
  28. """Non-interactive subprocess (stdin nulled, prompts disabled): a credential prompt from
  29. ``fetch``/``push`` could never be answered from a REST request, so fail fast and surface
  30. the real auth error in the toast. None when the process could not run at all."""
  31. try:
  32. return subprocess.run(
  33. argv, cwd=cwd, capture_output=True, text=True, encoding='utf-8',
  34. errors='replace', timeout=timeout, stdin=subprocess.DEVNULL, env=env,
  35. check=False,
  36. )
  37. except (OSError, subprocess.SubprocessError):
  38. return None
  39. def _git(cwd: str, args: list[str], *, timeout: int = _GIT_TIMEOUT) -> tuple[int, str, str]:
  40. """(returncode, stdout, stderr) of ``git`` in ``cwd``; never raises on non-zero exit."""
  41. proc = _run(["git", *harden_git_argv(args)], cwd, timeout, noninteractive_git_env())
  42. if proc is None:
  43. return 1, "", "git invocation failed"
  44. return proc.returncode, proc.stdout, proc.stderr
  45. def _git_out(cwd: str, args: list[str]) -> str:
  46. """stdout of a git command, or "" on any failure."""
  47. code, out, _ = _git(cwd, args)
  48. return out if code == 0 else ""
  49. def _git_line(cwd: str, args: list[str]) -> str:
  50. """Stripped stdout of a single-value git query ("" on failure)."""
  51. return _git_out(cwd, args).strip()
  52. def _git_ok(cwd: str, args: list[str]) -> None:
  53. """Run a git mutation, raising RuntimeError with stderr on failure."""
  54. code, _, err = _git(cwd, args)
  55. if code != 0:
  56. raise RuntimeError(err.strip() or f"git {' '.join(args)} failed")
  57. def _is_dir(cwd: str) -> bool:
  58. try:
  59. return Path(cwd).is_dir()
  60. except OSError:
  61. return False
  62. def _status_z(cwd: str, *extra: str) -> tuple[int, str]:
  63. """(returncode, raw) of ``git status --porcelain=v2 -z``."""
  64. code, raw, _ = _git(cwd, ["status", "--porcelain=v2", *extra, "-z"])
  65. return code, raw
  66. def _origin_head(cwd: str) -> str:
  67. """Short name of origin's default branch (``main``), or "" without a remote."""
  68. return _git_line(cwd, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
  69. def _origin_head_abbrev(cwd: str) -> str:
  70. return _git_line(cwd, ["rev-parse", "--abbrev-ref", "origin/HEAD"])
  71. def _ref_exists(cwd: str, ref: str) -> bool:
  72. return _git(cwd, ["rev-parse", "--verify", "--quiet", ref])[0] == 0
  73. # ── shared helpers ───────────────────────────────────────────────────────────
  74. def resolve_rename_path(raw: str) -> str:
  75. """``old => new`` (and ``dir/{old => new}/f``) → the NEW path, so a row addresses the real file."""
  76. path = str(raw or "").strip()
  77. if " => " not in path:
  78. return path
  79. head, _, tail = path.partition("{")
  80. if tail and "}" in tail:
  81. inner, _, suffix = tail.partition("}")
  82. _, _, to = inner.partition(" => ")
  83. return f"{head}{to}{suffix}".replace("//", "/")
  84. return path.split(" => ")[-1].strip()
  85. def _numstat(cwd: str, args: list[str]) -> dict[str, tuple[int, int]]:
  86. """``git diff --numstat`` → {path: (added, removed)}; binary files (``-``) → 0."""
  87. counts: dict[str, tuple[int, int]] = {}
  88. for line in _git_out(cwd, ["diff", "--numstat", *args]).splitlines():
  89. parts = line.split("\t")
  90. if len(parts) >= 3:
  91. added, removed = (0 if p == "-" else int(p or 0) for p in parts[:2])
  92. counts[resolve_rename_path(parts[2])] = (added, removed)
  93. return counts
  94. def _untracked_insertions(cwd: str, rel: str) -> int:
  95. """Line count of an untracked file (+N for new files in the review tree). Binary/oversized → 0."""
  96. try:
  97. target = Path(cwd) / rel
  98. if not os.path.isfile(target) or target.stat().st_size > _UNTRACKED_LINE_MAX_BYTES:
  99. return 0
  100. data = target.read_bytes()
  101. if b"\0" in data:
  102. return 0
  103. lines = data.count(b"\n")
  104. return lines + 1 if data and not data.endswith(b"\n") else lines
  105. except OSError:
  106. return 0
  107. def _branch_base(cwd: str) -> str | None:
  108. """Merge-base with the remote default branch for "all branch changes"."""
  109. head = _origin_head_abbrev(cwd)
  110. candidates = ([head] if head else []) + ["origin/main", "origin/master", "main", "master"]
  111. return next((b for b in (_git_line(cwd, ["merge-base", "HEAD", ref]) for ref in candidates) if b), None)
  112. def _default_branch_name(cwd: str) -> str | None:
  113. """The repo's trunk name ("main"/"master"/…), preferring origin/HEAD."""
  114. head = _origin_head_abbrev(cwd)
  115. if head and head != "origin/HEAD":
  116. return head.split("/", 1)[-1]
  117. for ref in ("refs/heads/main", "refs/heads/master",
  118. "refs/remotes/origin/main", "refs/remotes/origin/master"):
  119. if _ref_exists(cwd, ref):
  120. return ref.split("/")[-1]
  121. return None
  122. # ── porcelain v2 status parsing ──────────────────────────────────────────────
  123. def _walk_entries(raw: str):
  124. """Yield (tag, xy, path) per changed file from porcelain-v2 ``-z`` output,
  125. skipping branch headers and rename/copy origin-path records."""
  126. records = iter(raw.split("\0"))
  127. for rec in records:
  128. tag = rec[0] if rec else ""
  129. if tag == "?":
  130. yield "?", "??", rec[2:]
  131. elif tag == "u":
  132. yield "u", rec.split(" ")[1], rec.split(" ", 10)[-1]
  133. elif tag in ("1", "2"):
  134. path = rec.split(" ", 8)[-1] if tag == "1" else rec.split(" ", 9)[-1]
  135. if tag == "2":
  136. next(records, None) # rename/copy: the origin path is the next NUL record
  137. yield tag, rec.split(" ")[1], resolve_rename_path(path)
  138. def _entry_staged(tag: str, xy: str) -> bool:
  139. """A tracked entry whose index (staged) code is set."""
  140. return tag in ("1", "2") and xy[0] not in (".", "?")
  141. def _classify(tag: str, xy: str, path: str) -> dict:
  142. y = xy[1] if len(xy) > 1 else "."
  143. return {"path": path, "staged": _entry_staged(tag, xy),
  144. "unstaged": tag == "?" or (tag in ("1", "2") and y not in (".", "?")),
  145. "untracked": tag == "?", "conflicted": tag == "u"}
  146. def _status_letter(tag: str, xy: str) -> str:
  147. if tag in ("?", "u"):
  148. return tag.upper()
  149. code = xy[0] if xy[0] != "." else (xy[1] if len(xy) > 1 else ".")
  150. return (code if code != "." else "M").upper()
  151. # ── coding rail ──────────────────────────────────────────────────────────────
  152. def repo_status(cwd: str) -> dict | None:
  153. """Compact working-tree status for the coding rail. None on a non-repo."""
  154. if not _is_dir(cwd):
  155. return None
  156. code, raw = _status_z(cwd, "--branch")
  157. if code != 0:
  158. return None
  159. branch: str | None = None
  160. detached = False
  161. ahead = behind = 0
  162. for rec in raw.split("\0"):
  163. if rec.startswith("# branch.head "):
  164. head = rec[len("# branch.head ") :]
  165. detached = head == "(detached)"
  166. branch = None if detached else head
  167. elif rec.startswith("# branch.ab "):
  168. for tok in rec.split()[2:]:
  169. if tok.startswith("+"):
  170. ahead = int(tok[1:] or 0)
  171. elif tok.startswith("-"):
  172. behind = int(tok[1:] or 0)
  173. files = [_classify(tag, xy, path) for tag, xy, path in _walk_entries(raw)]
  174. # +/- vs HEAD, then fold in untracked insertions (`git diff HEAD` ignores them, so a
  175. # new-file-only turn would read +0); bounded scan.
  176. counts = _numstat(cwd, ["HEAD"]).values()
  177. added = sum(a for a, _ in counts)
  178. added += sum(_untracked_insertions(cwd, f["path"]) for f in files[:_UNTRACKED_SCAN_CAP] if f["untracked"])
  179. return {
  180. "branch": branch, "defaultBranch": _default_branch_name(cwd), "detached": detached,
  181. "ahead": ahead, "behind": behind,
  182. **{flag: sum(f[flag] for f in files) for flag in ("staged", "unstaged", "untracked", "conflicted")},
  183. "changed": len(files), "added": added, "removed": sum(r for _, r in counts), "files": files[:200],
  184. }
  185. # ── review pane ──────────────────────────────────────────────────────────────
  186. def _review_result(cwd: str, files: list[dict], base: str | None) -> dict:
  187. """Sorted rows; untracked rows with no counts get their insertion count filled in."""
  188. files.sort(key=lambda f: f["path"])
  189. for file in files:
  190. if file["status"] == "?" and file["added"] == 0 and file["removed"] == 0:
  191. file["added"] = _untracked_insertions(cwd, file["path"])
  192. return {"files": files, "base": base}
  193. def review_list(cwd: str, scope: str, base_ref: str | None) -> dict:
  194. """Changed files for a scope. Mirrors the Electron reviewList shapes."""
  195. if not _is_dir(cwd):
  196. return {"files": [], "base": None}
  197. if scope in ("branch", "lastTurn"):
  198. base = _branch_base(cwd) if scope == "branch" else base_ref
  199. if not base:
  200. return {"files": [], "base": None}
  201. rng = f"{base}...HEAD" if scope == "branch" else base
  202. files = [
  203. {"path": path, "added": a, "removed": r, "status": "M", "staged": False}
  204. for path, (a, r) in _numstat(cwd, [rng]).items()
  205. ]
  206. if scope == "lastTurn":
  207. seen = {f["path"] for f in files}
  208. files += [
  209. {"path": path, "added": 0, "removed": 0, "status": "?", "staged": False}
  210. for tag, _xy, path in _walk_entries(_status_z(cwd)[1])
  211. if tag == "?" and path not in seen
  212. ]
  213. return _review_result(cwd, files, base)
  214. code, raw = _status_z(cwd)
  215. if code != 0:
  216. return {"files": [], "base": None}
  217. staged = _numstat(cwd, ["--cached"])
  218. unstaged = _numstat(cwd, [])
  219. files = []
  220. for tag, xy, path in _walk_entries(raw):
  221. sa, sr = staged.get(path, (0, 0))
  222. ua, ur = unstaged.get(path, (0, 0))
  223. files.append({"path": path, "added": sa + ua, "removed": sr + ur,
  224. "status": _status_letter(tag, xy), "staged": _entry_staged(tag, xy)})
  225. return _review_result(cwd, files, None)
  226. def _all_add_diff(cwd: str, file_path: str) -> str:
  227. """Synthesized all-add diff for an untracked file (``--no-index`` exits non-zero by design)."""
  228. if not (Path(cwd) / file_path).is_file():
  229. return ""
  230. return _git(cwd, ["diff", "--no-index", "--", os.devnull, file_path])[1]
  231. def _single_file_diff(cwd: str, args: list[str], file_path: str) -> str:
  232. """Literal Git pathspecs still expand directories, including deleted ones."""
  233. literal = f":(literal){file_path}"
  234. names = _git_out(cwd, ["diff", *args, "--no-renames", "--name-only", "-z", "--", literal])
  235. if not names:
  236. return ""
  237. root = Path(_git_line(cwd, ["rev-parse", "--show-toplevel"]))
  238. target = (Path(cwd) / file_path).resolve()
  239. if any((root / name).resolve() != target for name in names.split("\0") if name):
  240. raise RuntimeError("Expected a single file, not a directory")
  241. return _git_out(cwd, ["diff", *args, "--no-renames", "--", literal])
  242. def review_diff(cwd: str, file_path: str, scope: str, base_ref: str | None, staged: bool) -> str:
  243. if not _is_dir(cwd):
  244. return ""
  245. if scope == "branch":
  246. base = _branch_base(cwd)
  247. return _single_file_diff(cwd, [f"{base}...HEAD"], file_path) if base else ""
  248. if scope == "lastTurn":
  249. return _single_file_diff(cwd, [base_ref], file_path) if base_ref else ""
  250. if staged:
  251. return _single_file_diff(cwd, ["--cached"], file_path)
  252. worktree = _single_file_diff(cwd, [], file_path)
  253. return worktree if worktree.strip() else _all_add_diff(cwd, file_path)
  254. def file_diff_vs_head(cwd: str, file_path: str) -> str:
  255. """Working-tree-vs-HEAD diff for one file (the preview's diff view). Unlike
  256. review_diff, never all-adds a clean tracked file; only a genuinely untracked one."""
  257. if not _is_dir(cwd):
  258. return ""
  259. literal = f":(literal){file_path}"
  260. head = _single_file_diff(cwd, ["HEAD"], file_path)
  261. if head.strip():
  262. return head
  263. status = _git_out(cwd, ["status", "--porcelain", "--", literal])
  264. return _all_add_diff(cwd, file_path) if status.strip().startswith("??") else ""
  265. def review_stage(cwd: str, file_path: str | None) -> dict:
  266. _git_ok(cwd, ["add", "--", file_path] if file_path else ["add", "-A"])
  267. return {"ok": True}
  268. def review_unstage(cwd: str, file_path: str | None) -> dict:
  269. _git_ok(cwd, ["reset", "-q", "HEAD", *(["--", file_path] if file_path else [])])
  270. return {"ok": True}
  271. def review_revert(cwd: str, file_path: str | None) -> dict:
  272. """Discard changes back to the committed state (restore tracked, remove untracked)."""
  273. target = ["--", file_path or "."]
  274. _git(cwd, ["checkout", "HEAD", *target])
  275. _git(cwd, ["clean", "-fd", *target])
  276. return {"ok": True}
  277. def review_rev_parse(cwd: str, ref: str | None) -> str | None:
  278. return _git_line(cwd, ["rev-parse", ref or "HEAD"]) or None
  279. def _has_staged(raw: str) -> bool:
  280. return any(_entry_staged(tag, xy) for tag, xy, _ in _walk_entries(raw))
  281. def _review_commit_env(cwd: str) -> dict[str, str]:
  282. """Carry Git's effective identity into an otherwise isolated commit.
  283. Only read-only ``git var`` queries see the original config files. Git resolves
  284. local/conditional config and author/committer environment precedence in *cwd*;
  285. status, staging and the commit itself retain all noninteractive isolation.
  286. """
  287. base = dict(os.environ)
  288. env = noninteractive_git_env(base)
  289. probe_env = dict(env)
  290. for key in ("GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM"):
  291. if key in base:
  292. probe_env[key] = base[key]
  293. else:
  294. probe_env.pop(key, None)
  295. for role in ("AUTHOR", "COMMITTER"):
  296. proc = _run(["git", "var", f"GIT_{role}_IDENT"], cwd, 5, probe_env)
  297. if proc is None:
  298. raise RuntimeError("git identity lookup failed")
  299. if proc.returncode != 0:
  300. raise RuntimeError(proc.stderr.strip() or "git identity lookup failed")
  301. ident = re.fullmatch(r"(.*) <([^<>]*)> -?\d+ [+-]\d{4}", proc.stdout.strip())
  302. if ident is None:
  303. raise RuntimeError("git returned an invalid commit identity")
  304. env[f"GIT_{role}_NAME"], env[f"GIT_{role}_EMAIL"] = ident.groups()
  305. return env
  306. def review_commit(cwd: str, message: str, push: bool) -> dict:
  307. """Commit the working tree; stage everything first when nothing is staged."""
  308. env = _review_commit_env(cwd)
  309. if not _has_staged(_status_z(cwd)[1]):
  310. _git_ok(cwd, ["add", "-A"])
  311. proc = _run(
  312. ["git", *harden_git_argv(["commit", "-m", message])], cwd, _GIT_TIMEOUT, env
  313. )
  314. if proc is None or proc.returncode != 0:
  315. raise RuntimeError(
  316. (proc.stderr.strip() if proc is not None else "") or "git commit failed"
  317. )
  318. if push:
  319. _review_push(cwd)
  320. return {"ok": True}
  321. def _review_push(cwd: str) -> None:
  322. if _git_line(cwd, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]):
  323. _git_ok(cwd, ["push"])
  324. return
  325. branch = _git_line(cwd, ["rev-parse", "--abbrev-ref", "HEAD"])
  326. if branch and branch != "HEAD":
  327. _git_ok(cwd, ["push", "-u", "origin", branch])
  328. def review_push(cwd: str) -> dict:
  329. _review_push(cwd)
  330. return {"ok": True}
  331. def review_commit_context(cwd: str, path_allowed: Callable[[Path], bool] | None = None) -> dict:
  332. """Diff of what WILL commit + recent subjects, for drafting a commit message."""
  333. code, raw = _status_z(cwd) if _is_dir(cwd) else (1, "")
  334. if code != 0:
  335. return {"diff": "", "recent": ""}
  336. entries = list(_walk_entries(raw))
  337. args = ["diff", "--cached"] if _has_staged(raw) else ["diff", "HEAD"]
  338. if path_allowed is None:
  339. diff = _git_out(cwd, args)
  340. else:
  341. # Disable rename pairing so an allowed destination cannot include the
  342. # old contents of a credential path excluded from the diff.
  343. repo = _git_line(cwd, ["rev-parse", "--show-toplevel"])
  344. if not repo:
  345. return {"diff": "", "recent": ""}
  346. names = _git_out(repo, [*args, "--no-renames", "--name-only", "-z"]).split("\0")
  347. allowed = [f":(literal){name}" for name in names if name and path_allowed(Path(repo) / name)]
  348. diff = _git_out(repo, [*args, "--no-renames", "--", *allowed]) if allowed else ""
  349. entries = [entry for entry in entries if path_allowed(Path(repo) / entry[2])]
  350. if len(diff) > _COMMIT_CONTEXT_DIFF_MAX_CHARS:
  351. omitted = len(diff) - _COMMIT_CONTEXT_DIFF_MAX_CHARS
  352. diff = f"{diff[:_COMMIT_CONTEXT_DIFF_MAX_CHARS]}\n# diff truncated: {omitted} chars omitted\n"
  353. untracked = [path for tag, _xy, path in entries if tag == "?"]
  354. if untracked:
  355. visible = untracked[:_COMMIT_CONTEXT_UNTRACKED_MAX]
  356. diff += "\n# New (untracked) files:\n" + "".join(f"# {p}\n" for p in visible)
  357. if len(untracked) > len(visible):
  358. diff += f"# ... {len(untracked) - len(visible)} more omitted\n"
  359. return {"diff": diff or "", "recent": _git_line(cwd, ["log", "-n", "10", "--pretty=format:%s"])}
  360. # ── ship flow (gh) ───────────────────────────────────────────────────────────
  361. def _gh(cwd: str, args: list[str]) -> tuple[bool, str, str]:
  362. """``(ok, stdout, stderr)`` of ``gh`` in ``cwd``. Never raises on non-zero exit —
  363. the caller decides what a failure means, and the real reason rides in stderr."""
  364. if not shutil.which("gh"):
  365. return False, "", ""
  366. # GH_PROMPT_DISABLED: gh's documented kill-switch for interactive prompts.
  367. env = noninteractive_git_env()
  368. env["GH_PROMPT_DISABLED"] = "1"
  369. proc = _run(["gh", *args], cwd, _GH_TIMEOUT, env)
  370. if proc is None:
  371. return False, "", ""
  372. return proc.returncode == 0, proc.stdout or "", proc.stderr or ""
  373. def _gh_json(cwd: str, args: list[str]):
  374. """Parsed JSON stdout of a successful gh call, else None."""
  375. ok, out, _stderr = _gh(cwd, args)
  376. if not ok:
  377. return None
  378. try:
  379. return json.loads(out)
  380. except json.JSONDecodeError:
  381. return None
  382. def review_ship_info(cwd: str) -> dict:
  383. """gh availability/auth + this branch's PR. ghReady false when gh missing/unauthed."""
  384. if not _is_dir(cwd) or not _gh(cwd, ["auth", "status"])[0]:
  385. return {"ghReady": False, "pr": None}
  386. pr = _gh_json(cwd, ["pr", "view", "--json", "url,state,number"])
  387. if pr and pr.get("url"):
  388. return {"ghReady": True, "pr": {"url": pr["url"], "state": pr.get("state"), "number": pr.get("number")}}
  389. return {"ghReady": True, "pr": None}
  390. # GraphQL asks per branch so the answer can't be crowded out like a `gh pr list`
  391. # page. Aliases carry many branches per request; 50 stays inside GitHub's node budget.
  392. _PR_QUERY_BRANCH_CHUNK = 50
  393. _PR_QUERY_BRANCH_CAP = 300
  394. _PR_NODE_FIELDS = "number state isDraft isCrossRepository title url headRefName"
  395. def _pr_query(owner: str, name: str, branches: list[str], numbers: list[int]) -> str:
  396. fields = [
  397. f"b{i}: pullRequests(headRefName: {json.dumps(branch)}, first: 5, "
  398. f"orderBy: {{field: CREATED_AT, direction: DESC}}) "
  399. f"{{ nodes {{ {_PR_NODE_FIELDS} }} }}"
  400. for i, branch in enumerate(branches)
  401. ]
  402. # A PR recovered from a transcript is known by number; asking directly also
  403. # yields its branch, so it lands in the same by-branch map.
  404. fields += [f"n{i}: pullRequest(number: {n}) {{ {_PR_NODE_FIELDS} }}" for i, n in enumerate(numbers)]
  405. return (f"query {{ repository(owner: {json.dumps(owner)}, name: {json.dumps(name)}) {{\n"
  406. + "\n".join(fields) + "\n} }")
  407. def _pr_payload(pr: dict) -> dict:
  408. return {"branch": str(pr.get("headRefName")), "draft": bool(pr.get("isDraft")),
  409. "number": int(pr.get("number") or 0), "state": str(pr.get("state") or "").lower(),
  410. "title": str(pr.get("title") or ""), "url": str(pr.get("url") or "")}
  411. def _own_pr(key: str, field: dict) -> dict | None:
  412. """The PR a GraphQL alias resolved to. Asked-by-number (``n<i>``) → ours by construction (a
  413. fork PR can't come from our own transcript). Fork PRs share our branch namespace (a
  414. contributor's `main` would badge a trunk session with a stranger's PR), so by-branch
  415. lookups only count own-repo nodes."""
  416. if key.startswith("n"):
  417. return field
  418. return next((n for n in (field.get("nodes") or []) if n and not n.get("isCrossRepository")), None)
  419. def review_pr_list(cwd: str, branches: list[str], numbers: list[int] | None = None) -> dict:
  420. """PRs on the given branches (plus any asked for by number) — queried per branch
  421. rather than paging the repo's newest PRs and hoping ours are in the page."""
  422. not_ready = {"ghReady": False, "prs": []}
  423. if not _is_dir(cwd):
  424. return not_ready
  425. wanted = list(dict.fromkeys(str(b) for b in (branches or []) if b))[:_PR_QUERY_BRANCH_CAP]
  426. by_number = list(dict.fromkeys(int(n) for n in (numbers or []) if n))[:_PR_QUERY_BRANCH_CAP]
  427. if not wanted and not by_number:
  428. return not_ready
  429. repo_ok, repo_out, _repo_err = _gh(cwd, ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"])
  430. owner, _, name = repo_out.strip().partition("/")
  431. if not repo_ok or not owner or not name:
  432. # gh missing, unauthenticated, or no GitHub remote — all "nothing to badge".
  433. return not_ready
  434. prs: list[dict] = []
  435. step = _PR_QUERY_BRANCH_CHUNK
  436. chunks = ([(wanted[i:i + step], []) for i in range(0, len(wanted), step)]
  437. + [([], by_number[i:i + step]) for i in range(0, len(by_number), step)])
  438. for branch_chunk, number_chunk in chunks:
  439. # A failed/malformed chunk drops its branches; the rest still resolve.
  440. data = _gh_json(cwd, ["api", "graphql", "-f", f"query={_pr_query(owner, name, branch_chunk, number_chunk)}"])
  441. repository = ((data or {}).get("data") or {}).get("repository") or {}
  442. for key, field in repository.items():
  443. pr = _own_pr(key, field) if field else None
  444. if pr and pr.get("headRefName"):
  445. prs.append(_pr_payload(pr))
  446. return {"ghReady": True, "prs": prs}
  447. def review_create_pr(cwd: str) -> dict:
  448. """Create a PR for the current branch (push first), letting gh fill title/body."""
  449. try:
  450. _review_push(cwd)
  451. except RuntimeError:
  452. pass
  453. created, out, err = _gh(cwd, ["pr", "create", "--fill"])
  454. if not created:
  455. # gh's own stderr says why the create failed ("no commits between main
  456. # and feature", a missing upstream, a publish-email refusal). The generic
  457. # fallback lied whenever gh itself was fine — keep it only for the case
  458. # gh reported nothing (#87731). Bounded: a toast carries the tail, not
  459. # the whole traceback.
  460. detail = err.strip()[-_GH_ERR_TAIL_CHARS:] or "is gh installed and authenticated?"
  461. raise RuntimeError(f"gh pr create failed: {detail}")
  462. url = next((line for line in reversed(out.strip().splitlines()) if line.strip()), "")
  463. return {"url": url}
  464. # ── worktrees & branches ─────────────────────────────────────────────────────
  465. def worktree_list(cwd: str) -> list[dict]:
  466. """``git worktree list --porcelain`` -> one dict per tree (main tree first)."""
  467. trees: list[dict] = []
  468. for line in _git_out(cwd, ["worktree", "list", "--porcelain"]).split("\n"):
  469. if line.startswith("worktree "):
  470. trees.append({"path": line[9:].strip(), "branch": None, "isMain": not trees,
  471. "detached": False, "locked": False})
  472. elif not trees:
  473. continue
  474. elif line.startswith("branch "):
  475. trees[-1]["branch"] = line[7:].strip().replace("refs/heads/", "", 1)
  476. elif line == "detached":
  477. trees[-1]["detached"] = True
  478. elif line.startswith("locked"):
  479. trees[-1]["locked"] = True
  480. return trees
  481. def _main_root(cwd: str) -> str:
  482. trees = worktree_list(cwd)
  483. return trees[0]["path"] if trees else cwd
  484. _BRANCH_SANITIZERS = (
  485. (r"\s+", "-"), (r"[^\w./-]", ""), (r"-{2,}", "-"), (r"/{2,}", "/"), (r"\.{2,}", "."), (r"^[-./]+|[-./]+$", ""),
  486. )
  487. def _sanitize_branch(name: str) -> str:
  488. value = str(name or "")
  489. for pattern, repl in _BRANCH_SANITIZERS:
  490. value = re.sub(pattern, repl, value)
  491. return value
  492. def _fetch_tracking_ref(root: str, remote: str, branch: str) -> bool:
  493. """Fetch ``<remote>/<branch>`` by explicit refspec; True when the remote has the branch.
  494. A tag-pinned narrow clone maps only the tag in ``remote.<remote>.fetch``, so a by-name
  495. fetch writes FETCH_HEAD without creating the tracking ref (#125686).
  496. """
  497. from hermes_cli.update_cmd_check import tracking_refspec
  498. return _git(root, ["fetch", remote, tracking_refspec(remote, branch)])[0] == 0
  499. def _slugify(name: str) -> str:
  500. slug = re.sub(r"[^a-z0-9]+", "-", str(name or "").strip().lower())
  501. slug = re.sub(r"^-+|-+$", "", slug)[:40].rstrip("-")
  502. return slug or "work"
  503. def _default_branch(cwd: str) -> str:
  504. return (
  505. _origin_head(cwd).replace("origin/", "", 1)
  506. or _git_line(cwd, ["config", "--get", "init.defaultBranch"])
  507. or next((b for b in _TRUNK_BRANCHES if _git_line(cwd, ["show-ref", "--verify", f"refs/heads/{b}"])), "")
  508. )
  509. def _ensure_repo(cwd: str) -> None:
  510. """A new project folder may not be a repo (or has no commit to branch from);
  511. init it with a root commit so worktrees just work. No-op for a committed repo."""
  512. if _git_line(cwd, ["rev-parse", "--is-inside-work-tree"]) != "true":
  513. _git_ok(cwd, ["init"])
  514. needs_root = True
  515. else:
  516. needs_root = not _ref_exists(cwd, "HEAD")
  517. if needs_root:
  518. _git_ok(cwd, ["-c", "user.email=hermes@localhost", "-c", "user.name=Hermes",
  519. "commit", "--allow-empty", "-m", "Initial commit"])
  520. def _unique_dir(base: str) -> str:
  521. candidates = itertools.chain([base], (f"{base}-{n}" for n in itertools.count(2)))
  522. return next(c for c in candidates if not os.path.exists(c))
  523. def _remote_of_ref(cwd: str, name: str) -> str:
  524. """The remote a ref belongs to ("origin" for "origin/main"), or "" when ``name`` is not a
  525. remote-tracking ref here. Asks git rather than assuming "origin" (mirrors the Electron op)."""
  526. if "/" not in name or _git(cwd, ["show-ref", "--verify", "--quiet", f"refs/remotes/{name}"])[0] != 0:
  527. return ""
  528. return name.split("/", 1)[0]
  529. def _worktree_for_existing(root: str, raw_name: str) -> dict:
  530. """Check out an existing local or remote-tracking branch into a worktree (or switch the
  531. main tree when it IS the trunk).
  532. "origin/feature" is a remote-tracking ref — `git worktree add <dir> origin/feature` detaches
  533. HEAD. Create a local branch of the same short name tracking it, like `git switch feature`
  534. does (Electron-op parity).
  535. """
  536. requested = _sanitize_branch(raw_name)
  537. if not requested:
  538. raise RuntimeError("Branch name is required.")
  539. # "origin/feature" is a remote-tracking ref, not a branch git can check out — `git worktree add <dir>
  540. # origin/feature` detaches HEAD. Create a local branch of the same short name that tracks the remote
  541. # ref, like `git switch feature` does for a branch on exactly one remote. (Parity with the Electron op;
  542. # a remote gateway serves this mirror, so the desktop's convert-a-branch flow must behave identically.
  543. # #81724)
  544. remote = _remote_of_ref(root, requested)
  545. fetched = False
  546. if not remote and "/" in requested and not _ref_exists(root, f"refs/heads/{requested}"):
  547. # A tag-pinned narrow clone has no tracking ref for any branch, so the ref-based reading
  548. # above misreads "origin/feature" as a local branch. When no such local branch exists
  549. # and the remote carries the branch, fetching it creates the ref; otherwise keep the
  550. # local-branch reading and its error.
  551. maybe_remote, maybe_branch = requested.split("/", 1)
  552. if _git_line(root, ["remote", "get-url", maybe_remote]) and _fetch_tracking_ref(
  553. root, maybe_remote, maybe_branch
  554. ):
  555. remote, fetched = maybe_remote, True
  556. existing = requested.split("/", 1)[1] if remote else requested
  557. if not remote and existing == _default_branch(root):
  558. _git_ok(root, ["switch", existing])
  559. return {"path": root, "branch": existing, "repoRoot": root}
  560. target = _unique_dir(os.path.join(root, ".worktrees", _slugify(existing)))
  561. if remote:
  562. # Best-effort freshness: on failure (offline, branch gone) the last known ref is still
  563. # there to branch from.
  564. fetched = fetched or _fetch_tracking_ref(root, remote, existing)
  565. if _git(root, ["worktree", "add", "--track", "-b", existing, target, requested])[0] != 0:
  566. # `--track` needs remote.<remote>.fetch to map the ref back to a remote branch; a
  567. # narrow clone maps only its tag. Branch untracked, then register the branch and
  568. # wire upstream, but only for a branch the fetch just proved exists: a configured
  569. # refspec whose source is gone makes every later plain `git fetch` fail.
  570. _git_ok(root, ["worktree", "add", "-b", existing, target, requested])
  571. if fetched:
  572. _git(root, ["remote", "set-branches", "--add", remote, existing])
  573. _git(root, ["branch", f"--set-upstream-to={requested}", existing])
  574. else:
  575. _git_ok(root, ["worktree", "add", target, existing])
  576. return {"path": target, "branch": existing, "repoRoot": root}
  577. def worktree_add(cwd: str, options: dict) -> dict:
  578. _ensure_repo(cwd)
  579. root = _main_root(cwd)
  580. options = options or {}
  581. if options.get("existingBranch"):
  582. result = _worktree_for_existing(root, options["existingBranch"])
  583. if result.get("path") != root: # a new checkout, not a switch of the main tree
  584. from hermes_cli.worktree_registry import record_worktree_repo
  585. record_worktree_repo(root)
  586. return result
  587. slug = _slugify(options.get("name") or f"work-{os.urandom(4).hex()}")
  588. branch = _sanitize_branch(options.get("branch") or "") or f"hermes/{slug}"
  589. target = _unique_dir(os.path.join(root, ".worktrees", slug))
  590. args = ["worktree", "add", "-b", branch, target]
  591. if options.get("base"):
  592. base = str(options["base"])
  593. # Fetch just that branch so a stale remote-tracking ref is fresh; fetch failures
  594. # (offline / no remote) are ignored — git uses the local ref or raises a clear error
  595. # below if it is entirely missing.
  596. if base.startswith("origin/"):
  597. remote_branch = base[len("origin/"):]
  598. # `base` comes straight from the API, and inside a refspec a glob such as
  599. # "origin/*" would fetch every branch: only fetch valid branch names.
  600. if _git(root, ["check-ref-format", "--branch", remote_branch])[0] == 0:
  601. _fetch_tracking_ref(root, "origin", remote_branch)
  602. # Branching off a remote-tracking ref auto-wires upstream tracking; the user wants
  603. # a standalone local branch (Electron-op parity).
  604. args.append("--no-track")
  605. args.append(base)
  606. code, _, err = _git(root, args)
  607. if code != 0:
  608. if "already exists" not in (err or "").lower():
  609. raise RuntimeError(err.strip() or "git worktree add failed")
  610. _git_ok(root, ["worktree", "add", target, branch])
  611. from hermes_cli.worktree_registry import record_worktree_repo
  612. record_worktree_repo(root)
  613. return {"path": target, "branch": branch, "repoRoot": root}
  614. def worktree_remove(cwd: str, worktree_path: str, force: bool) -> dict:
  615. _git_ok(_main_root(cwd), ["worktree", "remove", *(["--force"] if force else []), worktree_path])
  616. return {"removed": worktree_path}
  617. def _ref_names(cwd: str, *patterns: str, fmt: str = "%(refname:short)") -> list[str]:
  618. """Non-empty ``for-each-ref`` lines, newest commit first."""
  619. out = _git_out(cwd, ["for-each-ref", f"--format={fmt}", "--sort=-committerdate", *patterns])
  620. return [line.strip() for line in out.split("\n") if line.strip()]
  621. def branch_list(cwd: str) -> list[dict]:
  622. """Branches for the convert-a-branch picker: local heads first, then remote-tracking
  623. refs with no local head yet (a teammate's branch without a manual checkout).
  624. Parity with the Electron op — a remote gateway serves this mirror for the same desktop UI (#81724).
  625. """
  626. locals_ = _ref_names(cwd, "refs/heads")
  627. if not locals_:
  628. return []
  629. path_by_branch = {t["branch"]: t["path"] for t in worktree_list(cwd) if t["branch"]}
  630. trunk = _default_branch(cwd)
  631. local_set = set(locals_)
  632. # "origin/HEAD" is a symbolic alias, not a branch; a remote branch tracked locally is
  633. # reachable via its head (checking out the remote ref detaches).
  634. remotes = [name for name in _ref_names(cwd, "refs/remotes")
  635. if not name.endswith("/HEAD") and name.split("/", 1)[-1] not in local_set]
  636. return [
  637. *({"name": name, "checkedOut": name in path_by_branch, "isDefault": bool(trunk and name == trunk),
  638. "isRemote": False, "worktreePath": path_by_branch.get(name)} for name in locals_),
  639. # Remote rows: no local checkout, and never the local trunk.
  640. *({"name": name, "checkedOut": False, "isDefault": False, "isRemote": True,
  641. "worktreePath": None} for name in remotes),
  642. ]
  643. def branch_switch(cwd: str, branch: str) -> dict:
  644. target = _sanitize_branch(branch)
  645. if not target:
  646. raise RuntimeError("Branch name is required.")
  647. _git_ok(cwd, ["switch", target])
  648. return {"branch": target}
  649. def base_branch_list(cwd: str) -> list[dict]:
  650. """Local heads + remote-tracking refs for the base-branch picker; the remote default
  651. (origin/HEAD) is flagged so the UI can preselect it."""
  652. lines = _ref_names(cwd, "refs/heads", "refs/remotes", fmt="%(refname:short)\t%(committerdate:iso)")
  653. if not lines:
  654. return []
  655. # origin/HEAD when a remote exists; else the local default so a no-remote repo still flags its trunk.
  656. default = _origin_head(cwd) or _default_branch(cwd)
  657. return [
  658. {"name": name, "isRemote": name.startswith("origin/"), "isDefault": bool(default and name == default)}
  659. for name in (line.split("\t")[0] for line in lines)
  660. ]