mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-30 14:56:11 +00:00
The retrigger guard aborted with 'its job log records no inputs' while _gh(check=False) dropped gh's stderr, so a transient log read failure and a moved Inputs block looked the same. _gh now takes an errors list instead of check: given, a failure appends gh's last stderr line with URL query strings cut (job logs redirect to signed blob URLs) and yields an empty string; absent, it aborts as before. inputs_from_jobs passes such a list through, and dispatched_priority appends how many log reads failed and the last error, or that none failed. MEDUSA findings accepted as false positives (unchanged lines, no SQL or untrusted argv; independent skeptic review): MEDUSA-FTSCAN-231 runs.py:80 and runs.py:318, B603 gh.py:27 and gh.py:79, B105 runs.py:36. 🎯 Fix: 95 % 💥 Break: 2 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 93 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
129 lines
4.2 KiB
Python
129 lines
4.2 KiB
Python
"""Git and ``gh`` plumbing for the CI deploy-run status/trigger commands."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
def run_id_from_url(url: str) -> str:
|
|
match = re.search(r"/runs/(\d+)", url)
|
|
if not match:
|
|
raise ValueError(f"no run id found in URL: {url}")
|
|
return match.group(1)
|
|
|
|
|
|
def slug_from_url(url: str) -> str:
|
|
"""Extract the ``owner/repo`` slug from a github.com URL (https or ssh)."""
|
|
match = re.search(r"github\.com[/:]([^/]+)/([^/]+?)(?:\.git)?(?:/|$)", url)
|
|
if not match:
|
|
raise ValueError(f"no owner/repo found in URL: {url}")
|
|
return f"{match.group(1)}/{match.group(2)}"
|
|
|
|
|
|
def _run(args: list[str]) -> str:
|
|
return subprocess.run(
|
|
args, check=True, capture_output=True, text=True
|
|
).stdout.strip()
|
|
|
|
|
|
def _branch_remote() -> str:
|
|
"""The remote the current branch tracks (e.g. a fork), falling back to
|
|
``remote.pushDefault``, then 'origin' or the only configured remote."""
|
|
try:
|
|
upstream = _run(
|
|
["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]
|
|
)
|
|
if "/" in upstream:
|
|
return upstream.split("/", 1)[0]
|
|
except subprocess.CalledProcessError:
|
|
pass
|
|
remotes = _run(["git", "remote"]).split()
|
|
try:
|
|
push_default = _run(["git", "config", "--get", "remote.pushDefault"])
|
|
if push_default in remotes:
|
|
return push_default
|
|
except subprocess.CalledProcessError:
|
|
pass
|
|
if "origin" in remotes:
|
|
return "origin"
|
|
if not remotes:
|
|
raise RuntimeError("no git remote configured")
|
|
return remotes[0]
|
|
|
|
|
|
def resolve_repo() -> str:
|
|
"""The ``owner/repo`` the current branch lives on, derived from its
|
|
tracking remote (not gh's default repo, which may be the upstream)."""
|
|
return slug_from_url(_run(["git", "remote", "get-url", _branch_remote()]))
|
|
|
|
|
|
def _gh(
|
|
args: list[str], repo: str | None = None, errors: list[str] | None = None
|
|
) -> str:
|
|
"""Run ``gh`` and return its stdout.
|
|
|
|
Args:
|
|
args: the ``gh`` arguments, without the ``gh`` itself.
|
|
repo: appended as ``--repo`` when given.
|
|
errors: when given, a non-zero exit appends gh's last stderr line to it
|
|
and yields ``""`` instead of aborting the command. URL query strings
|
|
are cut from that line: job logs redirect to signed blob URLs whose
|
|
query string is the signature.
|
|
"""
|
|
cmd = ["gh", *args]
|
|
if repo:
|
|
cmd += ["--repo", repo]
|
|
proc = subprocess.run(cmd, check=False, capture_output=True, text=True)
|
|
if proc.returncode != 0:
|
|
if errors is not None:
|
|
lines = proc.stderr.strip().splitlines()
|
|
errors.append(
|
|
re.sub(r"\?\S*", "", lines[-1])
|
|
if lines
|
|
else f"gh exited {proc.returncode}"
|
|
)
|
|
return ""
|
|
sys.stderr.write(
|
|
proc.stderr or f"gh exited {proc.returncode}: {' '.join(cmd)}\n"
|
|
)
|
|
raise SystemExit(proc.returncode)
|
|
return proc.stdout
|
|
|
|
|
|
def current_branch() -> str:
|
|
return _run(["git", "rev-parse", "--abbrev-ref", "HEAD"])
|
|
|
|
|
|
def fetch_jobs(run_id: str, repo: str | None = None) -> list[dict]:
|
|
return json.loads(_gh(["run", "view", run_id, "--json", "jobs"], repo=repo)).get(
|
|
"jobs", []
|
|
)
|
|
|
|
|
|
def fetch_run(run_id: str, repo: str | None = None) -> dict:
|
|
"""Jobs plus the run title, in one ``gh`` call.
|
|
|
|
The REST API answers ``inputs: null`` for a finished workflow_dispatch, so
|
|
the inputs are recovered from the run itself: short ones from the title
|
|
(``config_from_title``), the long ones from a called job's log
|
|
(``inputs_from_jobs``), which the title truncates.
|
|
"""
|
|
return json.loads(
|
|
_gh(["run", "view", run_id, "--json", "jobs,displayTitle"], repo=repo)
|
|
)
|
|
|
|
|
|
def fetch_run_ref(run: str, repo: str) -> dict:
|
|
"""Jobs plus the run title of a run given as a URL or a bare id.
|
|
|
|
Args:
|
|
run: a run URL, or a bare run id that resolves against ``repo``.
|
|
repo: ``owner/repo`` a bare id belongs to.
|
|
"""
|
|
if run.isdigit():
|
|
return fetch_run(run, repo=repo)
|
|
return fetch_run(run_id_from_url(run), repo=slug_from_url(run))
|