|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +from collections.abc import Mapping |
| 5 | +from dataclasses import dataclass |
| 6 | +from pathlib import Path |
| 7 | +from typing import Callable, Optional |
| 8 | +from urllib.parse import urlparse |
| 9 | + |
| 10 | + |
| 11 | +@dataclass(frozen=True) |
| 12 | +class UploadContext: |
| 13 | + should_upload: bool |
| 14 | + commit_oid: str = "" |
| 15 | + ref: str = "" |
| 16 | + pr_number: str = "" |
| 17 | + annotation_level: str = "" |
| 18 | + message: str = "" |
| 19 | + |
| 20 | + |
| 21 | +@dataclass(frozen=True) |
| 22 | +class PullRequestLookup: |
| 23 | + number: str = "" |
| 24 | + error: str = "" |
| 25 | + |
| 26 | + |
| 27 | +def _find_open_pull_request(environ: Mapping[str, str]) -> PullRequestLookup: |
| 28 | + repository = environ.get("GITHUB_REPOSITORY", "") |
| 29 | + ref_name = environ.get("GITHUB_REF_NAME", "") |
| 30 | + command_environment = dict(environ) |
| 31 | + server_url = environ.get("GITHUB_SERVER_URL", "") |
| 32 | + if server_url: |
| 33 | + command_environment["GH_HOST"] = urlparse(server_url).netloc |
| 34 | + |
| 35 | + try: |
| 36 | + result = subprocess.run( |
| 37 | + [ |
| 38 | + "gh", |
| 39 | + "pr", |
| 40 | + "list", |
| 41 | + "--repo", |
| 42 | + repository, |
| 43 | + "--head", |
| 44 | + ref_name, |
| 45 | + "--state", |
| 46 | + "open", |
| 47 | + "--json", |
| 48 | + "number", |
| 49 | + "--jq", |
| 50 | + ".[0].number // empty", |
| 51 | + ], |
| 52 | + capture_output=True, |
| 53 | + check=False, |
| 54 | + env=command_environment, |
| 55 | + text=True, |
| 56 | + ) |
| 57 | + except OSError as error: |
| 58 | + return PullRequestLookup(error=f"unable to run gh: {error}") |
| 59 | + |
| 60 | + if result.returncode != 0: |
| 61 | + return PullRequestLookup( |
| 62 | + error=result.stderr.strip() or f"gh exited with status {result.returncode}" |
| 63 | + ) |
| 64 | + |
| 65 | + return PullRequestLookup(number=result.stdout.strip()) |
| 66 | + |
| 67 | + |
| 68 | +def resolve_upload_context( |
| 69 | + environ: Optional[Mapping[str, str]] = None, |
| 70 | + pull_request_lookup: Optional[Callable[[Mapping[str, str]], PullRequestLookup]] = None, |
| 71 | +) -> UploadContext: |
| 72 | + env = dict(os.environ if environ is None else environ) |
| 73 | + lookup = _find_open_pull_request if pull_request_lookup is None else pull_request_lookup |
| 74 | + event_name = env.get("GITHUB_EVENT_NAME", "") |
| 75 | + repository = env.get("GITHUB_REPOSITORY", "") |
| 76 | + ref = env.get("GITHUB_REF", "") |
| 77 | + |
| 78 | + if event_name == "merge_group": |
| 79 | + return UploadContext( |
| 80 | + should_upload=False, |
| 81 | + annotation_level="warning", |
| 82 | + message=( |
| 83 | + "Skipping coverage upload for merge queue. Coverage should be uploaded " |
| 84 | + "for pull requests and the default branch instead." |
| 85 | + ), |
| 86 | + ) |
| 87 | + |
| 88 | + if event_name in {"pull_request", "pull_request_target"}: |
| 89 | + head_repository = env.get("COVERAGE_PR_HEAD_REPOSITORY", "") |
| 90 | + if head_repository and head_repository != repository: |
| 91 | + return UploadContext( |
| 92 | + should_upload=False, |
| 93 | + annotation_level="notice", |
| 94 | + message=f"Skipping coverage upload for fork PR from {head_repository}.", |
| 95 | + ) |
| 96 | + |
| 97 | + return UploadContext( |
| 98 | + should_upload=True, |
| 99 | + commit_oid=env.get("COVERAGE_PR_HEAD_SHA", ""), |
| 100 | + pr_number=env.get("COVERAGE_PR_NUMBER", ""), |
| 101 | + ) |
| 102 | + |
| 103 | + if event_name == "push": |
| 104 | + default_branch = env.get("COVERAGE_DEFAULT_BRANCH", "") |
| 105 | + is_non_default_branch = ( |
| 106 | + default_branch |
| 107 | + and ref.startswith("refs/heads/") |
| 108 | + and ref != f"refs/heads/{default_branch}" |
| 109 | + ) |
| 110 | + if is_non_default_branch: |
| 111 | + pull_request = lookup(env) |
| 112 | + if pull_request.number: |
| 113 | + return UploadContext( |
| 114 | + should_upload=True, |
| 115 | + commit_oid=env.get("GITHUB_SHA", ""), |
| 116 | + ref=ref, |
| 117 | + pr_number=pull_request.number, |
| 118 | + ) |
| 119 | + |
| 120 | + if pull_request.error: |
| 121 | + return UploadContext( |
| 122 | + should_upload=False, |
| 123 | + annotation_level="error", |
| 124 | + message=( |
| 125 | + "Failed to query pull requests using the GitHub CLI: " |
| 126 | + f"{pull_request.error}. Ensure gh is installed and the workflow " |
| 127 | + "grants pull-requests: read permission." |
| 128 | + ), |
| 129 | + ) |
| 130 | + |
| 131 | + return UploadContext( |
| 132 | + should_upload=False, |
| 133 | + annotation_level="notice", |
| 134 | + message=( |
| 135 | + "Skipping coverage upload for non-default branch push because no " |
| 136 | + "open pull request was found." |
| 137 | + ), |
| 138 | + ) |
| 139 | + |
| 140 | + return UploadContext( |
| 141 | + should_upload=True, |
| 142 | + commit_oid=env.get("GITHUB_SHA", ""), |
| 143 | + ref=ref, |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def _append_lines(file_path: str, lines: list[str]) -> None: |
| 148 | + if not file_path: |
| 149 | + return |
| 150 | + with Path(file_path).open("a", encoding="utf-8") as stream: |
| 151 | + for line in lines: |
| 152 | + stream.write(f"{line}\n") |
| 153 | + |
| 154 | + |
| 155 | +def main(environ: Optional[Mapping[str, str]] = None) -> int: |
| 156 | + env = dict(os.environ if environ is None else environ) |
| 157 | + context = resolve_upload_context(env) |
| 158 | + output_file_path = env.get("GITHUB_OUTPUT", "") |
| 159 | + summary_file_path = env.get("GITHUB_STEP_SUMMARY", "") |
| 160 | + |
| 161 | + _append_lines( |
| 162 | + output_file_path, |
| 163 | + [ |
| 164 | + f"should_upload={str(context.should_upload).lower()}", |
| 165 | + f"commit_oid={context.commit_oid}", |
| 166 | + f"ref={context.ref}", |
| 167 | + f"pr_number={context.pr_number}", |
| 168 | + ], |
| 169 | + ) |
| 170 | + |
| 171 | + if not context.should_upload: |
| 172 | + print(f"::{context.annotation_level}::{context.message}") |
| 173 | + outcome = "failed" if context.annotation_level == "error" else "skipped" |
| 174 | + _append_lines( |
| 175 | + summary_file_path, |
| 176 | + [f"### Code coverage upload {outcome}", "", context.message], |
| 177 | + ) |
| 178 | + |
| 179 | + return 1 if context.annotation_level == "error" else 0 |
| 180 | + |
| 181 | + |
| 182 | +if __name__ == "__main__": |
| 183 | + raise SystemExit(main()) |
0 commit comments