mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-29 22:37:29 +00:00
Work-in-progress commit on the collective code-scanning sidetree, so main can be merged in; the single quality-high gate runs on the integration branch before the pull request. Fixes the CodeQL notes py/import-and-import-from, py/unused-import, py/unused-global-variable, py/empty-except, py/mixed-tuple-returns and py/unused-local-variable across 194 files, and adds one lint per rule under tests/lint/repository/python/ so none of them can come back: test_import_and_import_from, test_unused_imports_hidden_from_ruff, test_unused_global_variables, test_empty_except, test_mixed_tuple_returns, test_unused_local_variables, plus test_modules_import. Accepted security finding: MEDUSA-MP-SCAN-2056 (low) on utils/i18n/client.py:21, an import line matched by a keyword heuristic; operator-confirmed false positive. 🎯 Fix: 85 % 💥 Break: 8 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 78 🚦 Gate: ⛔ fix 85 % < 90, break 8 % > 5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
126 lines
4.2 KiB
Python
126 lines
4.2 KiB
Python
"""Git and ``gh`` plumbing for the CI deploy-run status/trigger commands."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
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."""
|
|
with contextlib.suppress(subprocess.CalledProcessError):
|
|
upstream = _run(
|
|
["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]
|
|
)
|
|
if "/" in upstream:
|
|
return upstream.split("/", 1)[0]
|
|
remotes = _run(["git", "remote"]).split()
|
|
with contextlib.suppress(subprocess.CalledProcessError):
|
|
push_default = _run(["git", "config", "--get", "remote.pushDefault"])
|
|
if push_default in remotes:
|
|
return push_default
|
|
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))
|