Skip to content

Commit 293c9eb

Browse files
committed
Skip unsupported branch coverage uploads
1 parent b519b7c commit 293c9eb

5 files changed

Lines changed: 540 additions & 45 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@ jobs:
1919
- name: Install dependencies
2020
run: uv sync --locked --group dev
2121
- name: Run unit tests
22-
run: uv run python -m unittest test_upload_coverage.py test_status_report.py test_post_upload_coverage.py -v
22+
run: uv run python -m unittest test_upload_coverage.py test_status_report.py test_post_upload_coverage.py test_resolve_upload_context.py -v

‎README.md‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Upload a Cobertura XML coverage report to GitHub's code coverage API.
1212
label: code-coverage/jacoco
1313
```
1414
15-
The action handles everything else automatically: gzip/base64 encoding, resolving the correct commit SHA and ref, detecting PR number (from both `pull_request` and `push` events), and calling the upload API.
15+
The action handles everything else automatically: event routing, gzip/base64 encoding, resolving the correct commit SHA and ref, detecting PR numbers from both `pull_request` and `push` events, and calling the upload API.
1616

1717
## Inputs
1818

@@ -35,7 +35,7 @@ permissions:
3535
code-quality: write
3636
```
3737

38-
For push-only workflows where the action looks up PR numbers via `gh pr list`, also add `pull-requests: read`.
38+
For push-only workflows where the action looks up PR numbers, also add `pull-requests: read`.
3939
The runner must have the GitHub CLI installed. GitHub-hosted runners include it by default.
4040

4141
## Error handling
@@ -72,12 +72,24 @@ If you want the action to return immediately after the upload request instead of
7272

7373
## Event handling
7474

75-
The action auto-detects the event type and resolves the correct values:
75+
The action auto-detects the event type and resolves the correct behavior:
7676

77-
- **`pull_request` / `pull_request_target`**: Uses the PR head SHA and ref (not the merge commit), and includes the PR number.
78-
- **`push`**: Uses `github.sha` and `github.ref`, and looks up whether the branch has an open PR via `gh pr list`.
77+
- **`pull_request` / `pull_request_target`**: Uses the PR head SHA (not the merge commit) and includes the PR number.
78+
- **Default-branch `push`**: Uses `github.sha` and `github.ref`.
79+
- **Non-default branch `push` with an open PR**: Looks up the PR number and uploads coverage for the pushed commit.
80+
- **Non-default branch `push` without an open PR**: Skips successfully instead of sending an upload request the API cannot associate with a PR.
7981

80-
This means it works with both patterns — workflows triggered by `pull_request` and push-only workflows that serve PRs via branch pushes.
82+
Configure workflows to run for pull requests and pushes to the default branch:
83+
84+
```yaml
85+
on:
86+
push:
87+
branches: [main]
88+
pull_request:
89+
branches: [main]
90+
```
91+
92+
Push-only workflows can upload PR coverage by granting `pull-requests: read`. Repositories may also use broader `push` triggers for other CI requirements; pushes without an open PR are skipped safely.
8193

8294
## Full example (separate upload job)
8395

@@ -102,14 +114,12 @@ jobs:
102114
# ... build and generate cobertura.xml ...
103115
104116
- uses: actions/upload-artifact@v4
105-
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
106117
with:
107118
name: cobertura-report
108119
path: cobertura.xml
109120
110121
upload-coverage:
111122
needs: build
112-
if: ${{ !cancelled() && needs.build.result == 'success' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }}
113123
runs-on: ubuntu-latest
114124
permissions:
115125
contents: read

‎action.yml‎

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,19 @@ inputs:
2727
runs:
2828
using: composite
2929
steps:
30+
- name: Check coverage upload eligibility
31+
id: eligibility
32+
shell: bash
33+
env:
34+
GH_TOKEN: ${{ inputs.token }}
35+
COVERAGE_DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
36+
COVERAGE_PR_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
37+
COVERAGE_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
38+
COVERAGE_PR_NUMBER: ${{ github.event.pull_request.number }}
39+
run: python3 "$GITHUB_ACTION_PATH/resolve_upload_context.py"
40+
3041
- name: Upload coverage report
42+
if: steps.eligibility.outputs.should_upload == 'true'
3143
shell: bash
3244
env:
3345
GH_TOKEN: ${{ inputs.token }}
@@ -39,47 +51,16 @@ runs:
3951
GITHUB_EVENT_NAME: ${{ github.event_name }}
4052
GITHUB_REPOSITORY: ${{ github.repository }}
4153
GITHUB_API_URL: ${{ github.api_url }}
54+
COMMIT_OID: ${{ steps.eligibility.outputs.commit_oid }}
55+
REF: ${{ steps.eligibility.outputs.ref }}
56+
PR_NUMBER: ${{ steps.eligibility.outputs.pr_number }}
4257
run: |
4358
set -euo pipefail
4459
45-
export GH_HOST="${GITHUB_SERVER_URL#*://}"
46-
47-
if [ "$GITHUB_EVENT_NAME" = "merge_group" ]; then
48-
echo "::warning::Skipping coverage upload for merge queue. Configure your workflow to upload coverage for PRs and the default branch instead. To avoid spinning up a runner, add \"if: github.event_name != 'merge_group'\" to the upload job."
49-
exit 0
50-
fi
51-
52-
if [ "${{ github.event.pull_request.head.repo.full_name }}" != "" ] && \
53-
[ "${{ github.event.pull_request.head.repo.full_name }}" != "$GITHUB_REPOSITORY" ]; then
54-
echo "::notice::Skipping coverage upload for fork PR (from ${{ github.event.pull_request.head.repo.full_name }})"
55-
exit 0
56-
fi
57-
58-
if [ "$GITHUB_EVENT_NAME" = "pull_request" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_target" ]; then
59-
COMMIT_OID="${{ github.event.pull_request.head.sha }}"
60-
REF=""
61-
PR_NUMBER="${{ github.event.pull_request.number }}"
62-
else
63-
COMMIT_OID="${{ github.sha }}"
64-
REF="${{ github.ref }}"
65-
if ! PR_NUMBER=$(gh pr list \
66-
--repo "$GITHUB_REPOSITORY" \
67-
--head "${{ github.ref_name }}" \
68-
--state open \
69-
--json number \
70-
--jq '.[0].number // empty'); then
71-
echo "::error::Failed to query pull requests using the GitHub CLI. Ensure gh is installed and the workflow grants pull-requests: read permission."
72-
exit 1
73-
fi
74-
fi
75-
76-
COMMIT_OID="$COMMIT_OID" \
77-
REF="$REF" \
78-
PR_NUMBER="$PR_NUMBER" \
7960
python3 "$GITHUB_ACTION_PATH/upload_coverage.py"
8061
8162
- name: Post-step telemetry
82-
if: always() && env._COVERAGE_TELEMETRY_STARTED_AT != ''
63+
if: always() && steps.eligibility.outputs.should_upload == 'true' && env._COVERAGE_TELEMETRY_STARTED_AT != ''
8364
shell: bash
8465
env:
8566
GH_TOKEN: ${{ inputs.token }}
@@ -89,5 +70,5 @@ runs:
8970
WAIT_FOR_PROCESSING_TIMEOUT: ${{ inputs.wait-for-processing-timeout }}
9071
GITHUB_REPOSITORY: ${{ github.repository }}
9172
GITHUB_API_URL: ${{ github.api_url }}
92-
COMMIT_OID: ${{ github.event.pull_request.head.sha || github.sha }}
73+
COMMIT_OID: ${{ steps.eligibility.outputs.commit_oid }}
9374
run: python3 "$GITHUB_ACTION_PATH/post_upload_coverage.py"

‎resolve_upload_context.py‎

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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

Comments
 (0)