|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +import urllib.request |
| 8 | + |
| 9 | + |
| 10 | +def get_pr_checks(pr_number): |
| 11 | + try: |
| 12 | + # Check if gh is installed |
| 13 | + subprocess.run( |
| 14 | + ["gh", "--version"], |
| 15 | + check=True, |
| 16 | + stdout=subprocess.DEVNULL, |
| 17 | + stderr=subprocess.DEVNULL, |
| 18 | + ) |
| 19 | + except FileNotFoundError: |
| 20 | + print( |
| 21 | + "Error: 'gh' (GitHub CLI) is not installed or not in PATH.", file=sys.stderr |
| 22 | + ) |
| 23 | + sys.exit(1) |
| 24 | + except subprocess.CalledProcessError: |
| 25 | + print("Error: 'gh' command failed. Is it installed?", file=sys.stderr) |
| 26 | + sys.exit(1) |
| 27 | + |
| 28 | + cmd = ["gh", "pr", "checks", str(pr_number), "--json", "bucket,name,link,state"] |
| 29 | + try: |
| 30 | + result = subprocess.run(cmd, capture_output=True, text=True, check=True) |
| 31 | + return json.loads(result.stdout) |
| 32 | + except subprocess.CalledProcessError as e: |
| 33 | + print(f"Error fetching PR checks: {e.stderr}", file=sys.stderr) |
| 34 | + sys.exit(1) |
| 35 | + |
| 36 | + |
| 37 | +def get_buildkite_build_url(checks): |
| 38 | + for check in checks: |
| 39 | + # Looking for Buildkite check. The name usually contains "buildkite" |
| 40 | + if "buildkite" in check.get("name", "").lower(): |
| 41 | + return check.get("link") |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +def fetch_buildkite_data(build_url): |
| 46 | + # Convert https://buildkite.com/org/pipeline/builds/number |
| 47 | + # to https://buildkite.com/org/pipeline/builds/number.json |
| 48 | + if not build_url.endswith(".json"): |
| 49 | + json_url = build_url + ".json" |
| 50 | + else: |
| 51 | + json_url = build_url |
| 52 | + |
| 53 | + try: |
| 54 | + with urllib.request.urlopen(json_url) as response: |
| 55 | + if response.status != 200: |
| 56 | + print( |
| 57 | + f"Error fetching data from {json_url}: Status {response.status}", |
| 58 | + file=sys.stderr, |
| 59 | + ) |
| 60 | + return None |
| 61 | + return json.loads(response.read().decode()) |
| 62 | + except Exception as e: |
| 63 | + print(f"Error fetching data from {json_url}: {e}", file=sys.stderr) |
| 64 | + return None |
| 65 | + |
| 66 | + |
| 67 | +def download_log(job_url, output_path): |
| 68 | + # Construct raw log URL: job_url + "/raw" (Buildkite convention) |
| 69 | + # job_url e.g. https://buildkite.com/org/pipeline/builds/14394#job-id |
| 70 | + # Wait, the job['path'] gives /org/pipeline/builds/14394#job-id |
| 71 | + # We want /org/pipeline/builds/14394/jobs/job-id/raw? No |
| 72 | + # The clean URL for a job is https://buildkite.com/org/pipeline/builds/14394/jobs/job-id |
| 73 | + # And raw log is https://buildkite.com/org/pipeline/builds/14394/jobs/job-id/raw |
| 74 | + |
| 75 | + # We have full_url e.g. https://buildkite.com/bazel/rules-python-python/builds/14394#019c5cf9-e3cf-468f-a7b1-8f9f5ad4b08c |
| 76 | + # We need to transform it. |
| 77 | + |
| 78 | + if "#" in job_url: |
| 79 | + base, job_id = job_url.split("#") |
| 80 | + # Ensure base doesn't end with / |
| 81 | + if base.endswith("/"): |
| 82 | + base = base[:-1] |
| 83 | + |
| 84 | + # Build raw URL |
| 85 | + raw_url = f"{base}/jobs/{job_id}/raw" |
| 86 | + else: |
| 87 | + print(f"Could not parse job URL for download: {job_url}", file=sys.stderr) |
| 88 | + return False |
| 89 | + |
| 90 | + try: |
| 91 | + with urllib.request.urlopen(raw_url) as response: |
| 92 | + if response.status != 200: |
| 93 | + print( |
| 94 | + f"Error downloading log from {raw_url}: Status {response.status}", |
| 95 | + file=sys.stderr, |
| 96 | + ) |
| 97 | + return False |
| 98 | + with open(output_path, "wb") as f: |
| 99 | + f.write(response.read()) |
| 100 | + return True |
| 101 | + except Exception as e: |
| 102 | + print(f"Error downloading log from {raw_url}: {e}", file=sys.stderr) |
| 103 | + return False |
| 104 | + |
| 105 | + |
| 106 | +def main(): |
| 107 | + parser = argparse.ArgumentParser(description="Get Buildkite CI results for a PR.") |
| 108 | + parser.add_argument("pr_number", help="The PR number.") |
| 109 | + parser.add_argument( |
| 110 | + "--jobs", |
| 111 | + action="append", |
| 112 | + help="Filter by job name (regex match). Can be specified multiple times.", |
| 113 | + ) |
| 114 | + parser.add_argument( |
| 115 | + "--download", |
| 116 | + action="store_true", |
| 117 | + help="If exactly one job is matched, download its log to a local file.", |
| 118 | + ) |
| 119 | + |
| 120 | + args = parser.parse_args() |
| 121 | + |
| 122 | + print(f"Fetching checks for PR #{args.pr_number}...", file=sys.stderr) |
| 123 | + checks = get_pr_checks(args.pr_number) |
| 124 | + |
| 125 | + build_url = get_buildkite_build_url(checks) |
| 126 | + if not build_url: |
| 127 | + print("No Buildkite check found for this PR.", file=sys.stderr) |
| 128 | + sys.exit(1) |
| 129 | + |
| 130 | + print(f"Found Buildkite URL: {build_url}", file=sys.stderr) |
| 131 | + |
| 132 | + data = fetch_buildkite_data(build_url) |
| 133 | + if not data: |
| 134 | + sys.exit(1) |
| 135 | + |
| 136 | + print(f"Build State: {data.get('state')}") |
| 137 | + print("-" * 40) |
| 138 | + |
| 139 | + jobs = data.get("jobs", []) |
| 140 | + |
| 141 | + filtered_jobs = [] |
| 142 | + if args.jobs: |
| 143 | + for job in jobs: |
| 144 | + job_name = job.get("name") |
| 145 | + if not job_name: |
| 146 | + continue |
| 147 | + for pattern in args.jobs: |
| 148 | + if re.search(pattern, job_name, re.IGNORECASE): |
| 149 | + filtered_jobs.append(job) |
| 150 | + break |
| 151 | + else: |
| 152 | + filtered_jobs = jobs |
| 153 | + |
| 154 | + for job in filtered_jobs: |
| 155 | + name = job.get("name", "Unknown") |
| 156 | + state = job.get("state", "Unknown") |
| 157 | + path = job.get("path") |
| 158 | + full_url = f"https://buildkite.com{path}" if path else "N/A" |
| 159 | + |
| 160 | + passed = job.get("passed", False) |
| 161 | + outcome = job.get("outcome") |
| 162 | + |
| 163 | + if passed: |
| 164 | + result_str = "PASSED" |
| 165 | + elif outcome: |
| 166 | + result_str = outcome.upper() |
| 167 | + else: |
| 168 | + result_str = state.upper() |
| 169 | + |
| 170 | + print(f"Job: {name}") |
| 171 | + print(f" Result: {result_str}") |
| 172 | + print(f" URL: {full_url}") |
| 173 | + print("") |
| 174 | + |
| 175 | + if args.download: |
| 176 | + if len(filtered_jobs) == 1: |
| 177 | + job = filtered_jobs[0] |
| 178 | + name = job.get("name", "unknown_job") |
| 179 | + # Sanitize name for filename |
| 180 | + safe_name = re.sub(r"[^a-zA-Z0-9_\-]", "_", name) |
| 181 | + output_path = f"{safe_name}.log" |
| 182 | + |
| 183 | + path = job.get("path") |
| 184 | + if path: |
| 185 | + full_url = f"https://buildkite.com{path}" |
| 186 | + print(f"Downloading log for '{name}'...", file=sys.stderr) |
| 187 | + if download_log(full_url, output_path): |
| 188 | + print(f"Downloaded log to: {output_path}") |
| 189 | + else: |
| 190 | + print("Failed to download log.", file=sys.stderr) |
| 191 | + else: |
| 192 | + print("Job has no URL path, cannot download.", file=sys.stderr) |
| 193 | + elif len(filtered_jobs) == 0: |
| 194 | + print("No jobs matched to download.", file=sys.stderr) |
| 195 | + else: |
| 196 | + print( |
| 197 | + f"Matched {len(filtered_jobs)} jobs. Please filter to exactly one job to download.", |
| 198 | + file=sys.stderr, |
| 199 | + ) |
| 200 | + |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + main() |
0 commit comments