|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import json |
| 3 | +import os |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +from dataclasses import dataclass |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +import yaml |
| 11 | + |
| 12 | +FIELD_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(frozen=True) |
| 16 | +class CheckResult: |
| 17 | + name: str |
| 18 | + status: str |
| 19 | + message: str |
| 20 | + |
| 21 | + |
| 22 | +def parse_json_list(value): |
| 23 | + try: |
| 24 | + items = json.loads(value) |
| 25 | + except json.JSONDecodeError as error: |
| 26 | + raise ValueError("skip must be a JSON array of strings") from error |
| 27 | + |
| 28 | + if not isinstance(items, list) or not all(isinstance(item, str) and item for item in items): |
| 29 | + raise ValueError("skip must be a JSON array of strings") |
| 30 | + |
| 31 | + return set(items) |
| 32 | + |
| 33 | + |
| 34 | +def load_config(config_path): |
| 35 | + try: |
| 36 | + with open(config_path) as file: |
| 37 | + config = yaml.safe_load(file) |
| 38 | + except yaml.YAMLError as error: |
| 39 | + raise ValueError("github repo config must be valid YAML") from error |
| 40 | + |
| 41 | + if not isinstance(config, dict): |
| 42 | + raise ValueError("github repo config must be a mapping") |
| 43 | + |
| 44 | + checks = config.get("checks") |
| 45 | + if not isinstance(checks, dict) or not checks: |
| 46 | + raise ValueError("github repo config must contain a non-empty checks mapping") |
| 47 | + for field in checks: |
| 48 | + if not isinstance(field, str) or not FIELD_PATTERN.fullmatch(field): |
| 49 | + raise ValueError("github repo check names must be GraphQL field names") |
| 50 | + |
| 51 | + return checks |
| 52 | + |
| 53 | + |
| 54 | +def github_request(args): |
| 55 | + result = subprocess.run(["gh", *args], capture_output=True, text=True) |
| 56 | + if result.returncode: |
| 57 | + message = result.stderr.strip() or result.stdout.strip() or "unknown error" |
| 58 | + raise RuntimeError(message) |
| 59 | + |
| 60 | + try: |
| 61 | + return json.loads(result.stdout) |
| 62 | + except json.JSONDecodeError as error: |
| 63 | + raise RuntimeError("GitHub API returned invalid JSON") from error |
| 64 | + |
| 65 | + |
| 66 | +def repository_name(repository): |
| 67 | + parts = repository.split("/") |
| 68 | + if len(parts) != 2 or not all(parts): |
| 69 | + raise ValueError("repository must use owner/name format") |
| 70 | + return parts |
| 71 | + |
| 72 | + |
| 73 | +def github_repository(repository, fields): |
| 74 | + owner, name = repository_name(repository) |
| 75 | + selection = " ".join(fields) |
| 76 | + query = ( |
| 77 | + "query($owner: String!, $name: String!) { " |
| 78 | + f"repository(owner: $owner, name: $name) {{ {selection} }} " |
| 79 | + "}" |
| 80 | + ) |
| 81 | + response = github_request( |
| 82 | + ["api", "graphql", "-f", f"query={query}", "-F", f"owner={owner}", "-F", f"name={name}"] |
| 83 | + ) |
| 84 | + try: |
| 85 | + return response["data"]["repository"] |
| 86 | + except (KeyError, TypeError) as error: |
| 87 | + raise RuntimeError("GitHub returned an invalid repository response") from error |
| 88 | + |
| 89 | + |
| 90 | +def format_value(value): |
| 91 | + return json.dumps(value, separators=(",", ":"), sort_keys=True) |
| 92 | + |
| 93 | + |
| 94 | +def evaluate_checks(checks, repository, skipped=(), request=github_repository): |
| 95 | + skipped = set(skipped) |
| 96 | + if unknown := skipped - set(checks): |
| 97 | + names = ", ".join(sorted(unknown)) |
| 98 | + raise ValueError(f"Unknown skipped GitHub config checks: {names}") |
| 99 | + |
| 100 | + active_fields = [field for field in checks if field not in skipped] |
| 101 | + payload = None |
| 102 | + request_error = None |
| 103 | + if active_fields: |
| 104 | + try: |
| 105 | + payload = request(repository, active_fields) |
| 106 | + except RuntimeError as error: |
| 107 | + request_error = str(error) |
| 108 | + |
| 109 | + results = [] |
| 110 | + for field, expected in checks.items(): |
| 111 | + if field in skipped: |
| 112 | + results.append(CheckResult(field, "skipped", "skipped by workflow input")) |
| 113 | + continue |
| 114 | + |
| 115 | + if request_error: |
| 116 | + results.append(CheckResult(field, "failed", f"GitHub request failed: {request_error}")) |
| 117 | + continue |
| 118 | + |
| 119 | + if field not in payload: |
| 120 | + results.append(CheckResult(field, "failed", f"GitHub API response has no {field} field")) |
| 121 | + continue |
| 122 | + actual = payload[field] |
| 123 | + |
| 124 | + if type(actual) is not type(expected) or actual != expected: |
| 125 | + message = f"expected {format_value(expected)}, got {format_value(actual)}" |
| 126 | + results.append(CheckResult(field, "failed", message)) |
| 127 | + continue |
| 128 | + |
| 129 | + results.append(CheckResult(field, "passed", format_value(actual))) |
| 130 | + |
| 131 | + return results |
| 132 | + |
| 133 | + |
| 134 | +def annotation_value(value): |
| 135 | + return str(value).replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") |
| 136 | + |
| 137 | + |
| 138 | +def main(): |
| 139 | + try: |
| 140 | + checks = load_config(Path(os.environ["CONFIG_PATH"])) |
| 141 | + skipped = parse_json_list(os.environ.get("SKIP", "[]")) |
| 142 | + repository = os.environ["REPOSITORY"] |
| 143 | + results = evaluate_checks(checks, repository, skipped) |
| 144 | + except (KeyError, OSError, ValueError) as error: |
| 145 | + print(f"::error::{annotation_value(error)}") |
| 146 | + return 1 |
| 147 | + |
| 148 | + print(f"GitHub repository config: {repository}") |
| 149 | + for result in results: |
| 150 | + if result.status == "failed": |
| 151 | + title = annotation_value(f"GitHub config: {result.name}") |
| 152 | + message = annotation_value(result.message) |
| 153 | + print(f"::error title={title}::{message}") |
| 154 | + else: |
| 155 | + print(f"{result.status.upper()} {result.name}: {result.message}") |
| 156 | + |
| 157 | + failed = sum(result.status == "failed" for result in results) |
| 158 | + passed = sum(result.status == "passed" for result in results) |
| 159 | + skipped_count = sum(result.status == "skipped" for result in results) |
| 160 | + print(f"Result: {passed} passed, {failed} failed, {skipped_count} skipped") |
| 161 | + return int(failed > 0) |
| 162 | + |
| 163 | + |
| 164 | +if __name__ == "__main__": |
| 165 | + sys.exit(main()) |
0 commit comments