|
| 1 | +"""Look up GitLab CI pipeline status for a given PR, branch, or commit.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | + |
| 8 | +import httpx |
| 9 | + |
| 10 | +GITLAB_PROJECT = "couchers%2Fcouchers" |
| 11 | +GITLAB_API = f"https://gitlab.com/api/v4/projects/{GITLAB_PROJECT}" |
| 12 | + |
| 13 | + |
| 14 | +def get_pr_info(pr_number: str) -> tuple[str, str]: |
| 15 | + """Get SHA and branch name from a GitHub PR number.""" |
| 16 | + result = subprocess.run( |
| 17 | + ["gh", "pr", "view", pr_number, "--json", "headRefOid,headRefName"], |
| 18 | + capture_output=True, |
| 19 | + text=True, |
| 20 | + check=True, |
| 21 | + ) |
| 22 | + data = json.loads(result.stdout) |
| 23 | + return data["headRefOid"], data["headRefName"] |
| 24 | + |
| 25 | + |
| 26 | +def get_branch_sha(client: httpx.Client, branch: str) -> str: |
| 27 | + """Get the latest pipeline SHA for a branch from GitLab.""" |
| 28 | + resp = client.get( |
| 29 | + f"{GITLAB_API}/pipelines", |
| 30 | + params={"ref": branch, "per_page": 1, "order_by": "updated_at", "sort": "desc"}, |
| 31 | + ) |
| 32 | + resp.raise_for_status() |
| 33 | + pipelines = resp.json() |
| 34 | + if not pipelines: |
| 35 | + print(f"No pipelines found for branch: {branch}", file=sys.stderr) |
| 36 | + sys.exit(1) |
| 37 | + return pipelines[0]["sha"] |
| 38 | + |
| 39 | + |
| 40 | +def find_pipeline(client: httpx.Client, sha: str) -> dict: |
| 41 | + """Find the best pipeline for a given SHA.""" |
| 42 | + resp = client.get(f"{GITLAB_API}/pipelines", params={"sha": sha, "per_page": 5}) |
| 43 | + resp.raise_for_status() |
| 44 | + pipelines = resp.json() |
| 45 | + |
| 46 | + if not pipelines: |
| 47 | + print(f"No pipelines found for SHA: {sha}", file=sys.stderr) |
| 48 | + sys.exit(1) |
| 49 | + |
| 50 | + # Prefer external_pull_request_event source |
| 51 | + for p in pipelines: |
| 52 | + if p.get("source") == "external_pull_request_event": |
| 53 | + return p |
| 54 | + |
| 55 | + return pipelines[0] |
| 56 | + |
| 57 | + |
| 58 | +def get_jobs(client: httpx.Client, pipeline_id: int) -> list[dict]: |
| 59 | + """Fetch all jobs for a pipeline.""" |
| 60 | + resp = client.get(f"{GITLAB_API}/pipelines/{pipeline_id}/jobs", params={"per_page": 100}) |
| 61 | + resp.raise_for_status() |
| 62 | + return resp.json() |
| 63 | + |
| 64 | + |
| 65 | +def format_duration(seconds: float | None) -> str: |
| 66 | + if seconds is None: |
| 67 | + return "-" |
| 68 | + return f"{seconds:.0f}s" |
| 69 | + |
| 70 | + |
| 71 | +def main(): |
| 72 | + parser = argparse.ArgumentParser(description="Look up GitLab CI pipeline status") |
| 73 | + group = parser.add_mutually_exclusive_group(required=True) |
| 74 | + group.add_argument("--pr", help="GitHub PR number") |
| 75 | + group.add_argument("--branch", help="Git branch name") |
| 76 | + group.add_argument("--sha", help="Commit SHA") |
| 77 | + args = parser.parse_args() |
| 78 | + |
| 79 | + sha = "" |
| 80 | + branch = "" |
| 81 | + pr = "" |
| 82 | + |
| 83 | + with httpx.Client(timeout=30) as client: |
| 84 | + if args.pr: |
| 85 | + pr = args.pr |
| 86 | + sha, branch = get_pr_info(pr) |
| 87 | + elif args.branch: |
| 88 | + branch = args.branch |
| 89 | + sha = get_branch_sha(client, branch) |
| 90 | + elif args.sha: |
| 91 | + # Resolve short SHAs to full 40-char via GitLab API (works in shallow clones) |
| 92 | + if len(args.sha) < 40: |
| 93 | + resp = client.get(f"{GITLAB_API}/repository/commits/{args.sha}") |
| 94 | + resp.raise_for_status() |
| 95 | + sha = resp.json()["id"] |
| 96 | + else: |
| 97 | + sha = args.sha |
| 98 | + |
| 99 | + pipeline = find_pipeline(client, sha) |
| 100 | + pipeline_id = pipeline["id"] |
| 101 | + pipeline_status = pipeline["status"] |
| 102 | + |
| 103 | + if not branch: |
| 104 | + branch = pipeline["ref"] |
| 105 | + |
| 106 | + jobs = get_jobs(client, pipeline_id) |
| 107 | + |
| 108 | + # Print summary header |
| 109 | + print(f"Pipeline: #{pipeline_id} ({pipeline_status})") |
| 110 | + print(f"Branch: {branch}") |
| 111 | + print(f"Commit: {sha}") |
| 112 | + if pr: |
| 113 | + print(f"PR: #{pr}") |
| 114 | + print(f"URL: https://gitlab.com/couchers/couchers/-/pipelines/{pipeline_id}") |
| 115 | + print() |
| 116 | + |
| 117 | + # Sort jobs by stage then name |
| 118 | + jobs.sort(key=lambda j: (j.get("stage", ""), j.get("name", ""))) |
| 119 | + |
| 120 | + # Print jobs table |
| 121 | + print("Jobs:") |
| 122 | + print(f"{'STAGE':<16} {'JOB':<30} {'STATUS':<10} {'DURATION':<10} ID") |
| 123 | + |
| 124 | + for job in jobs: |
| 125 | + stage = job.get("stage", "") |
| 126 | + name = job.get("name", "") |
| 127 | + status = job.get("status", "") |
| 128 | + duration = format_duration(job.get("duration")) |
| 129 | + job_id = job.get("id", "") |
| 130 | + |
| 131 | + status_display = status.upper() if status == "failed" else status |
| 132 | + |
| 133 | + print(f"{stage:<16} {name:<30} {status_display:<10} {duration:<10} {job_id}") |
| 134 | + |
| 135 | + if status == "failed": |
| 136 | + reason = job.get("failure_reason", "") |
| 137 | + if reason: |
| 138 | + print(f"{'':16} ^ failure reason: {reason}") |
| 139 | + |
| 140 | + |
| 141 | +if __name__ == "__main__": |
| 142 | + main() |
0 commit comments