-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathupload_coverage.py
More file actions
executable file
·213 lines (177 loc) · 6.33 KB
/
upload_coverage.py
File metadata and controls
executable file
·213 lines (177 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env python3
import base64
import gzip
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path
from typing import Mapping, Optional, Tuple
PERMISSIONS_ERROR = (
"Coverage upload returned HTTP {status}. Ensure the calling job has "
"'code-quality: write' permission. See https://github.com/actions/upload-code-coverage#permissions"
)
FAIL_ON_ERROR_HINT = (
"To treat upload errors as warnings, add 'fail-on-error: false' to the action inputs."
)
def emit_annotation(level: str, message: str) -> None:
print(f"::{level}::{message}")
def log_upload_parameters(
*,
commit_oid: str,
ref: str,
pr_number: str,
language: str,
label: str,
file_path: str,
) -> None:
file_size = Path(file_path).stat().st_size
print("::group::Upload parameters")
print(f" commit_oid: {commit_oid}")
print(f" ref: {ref or '<not set>'}")
print(f" pr_number: {pr_number or '<not set>'}")
print(f" language: {language}")
print(f" label: {label}")
print(f" file: {file_path} ({file_size} bytes)")
print("::endgroup::")
def _extract_message(body: str) -> str:
"""Extract the human-readable message from an API JSON response.
Falls back to the raw body if parsing fails or no message field exists.
We intentionally strip documentation_url and other fields because the
docs URL currently 404s (pre-GA).
TODO(GA): Once docs are live, consider including documentation_url in output.
"""
try:
data = json.loads(body)
message = data.get("message", "")
if message:
return message
except (json.JSONDecodeError, AttributeError, TypeError):
pass
return body
def encode_coverage_report(file_path: str) -> str:
data = Path(file_path).read_bytes()
return base64.b64encode(gzip.compress(data)).decode("ascii")
def build_payload(
*,
file_path: str,
language: str,
label: str,
commit_oid: str,
ref: str = "",
pr_number: str = "",
) -> dict:
payload = {
"commit_oid": commit_oid,
"coverage_report": encode_coverage_report(file_path),
"language_name": language,
"label": label,
}
if pr_number:
payload["pull_request_number"] = int(pr_number)
elif ref:
payload["ref"] = ref
else:
raise ValueError("Either PR_NUMBER or REF must be provided")
return payload
def upload_report(
*,
payload: dict,
repository: str,
api_url: str,
token: str,
opener=urllib.request.urlopen,
) -> Tuple[int, str]:
"""Upload the coverage report. Returns (status_code, response_body)."""
request = urllib.request.Request(
url=f"{api_url.rstrip('/')}/repos/{repository}/code-coverage/report",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"Content-Type": "application/json",
},
method="PUT",
)
try:
with opener(request) as response:
body = response.read().decode("utf-8", errors="replace")
return response.getcode(), body
except urllib.error.HTTPError as error:
body = error.read().decode("utf-8", errors="replace")
return error.code, body
except urllib.error.URLError as error:
return 0, str(error.reason)
def handle_response(status: int, body: str, fail_on_error: bool) -> int:
"""Process the upload response. Returns the process exit code."""
if status == 0:
# Network error (could not reach the API)
emit_annotation("error", f"Coverage upload failed: could not reach the API. {FAIL_ON_ERROR_HINT}")
return 1 if fail_on_error else 0
if status == 201:
print("Coverage report uploaded successfully.")
return 0
if status == 200:
# API accepted but did not store (e.g. commit not latest on branch)
try:
message = json.loads(body).get("message", "")
except (json.JSONDecodeError, AttributeError):
message = ""
if message:
emit_annotation("warning", f"Coverage upload returned HTTP 200 (report not stored): {message}")
else:
emit_annotation("warning", "Coverage upload returned HTTP 200 but expected 201. The report may not have been stored.")
return 0
if status >= 400:
if status == 403 and "not authorized" in body.lower():
emit_annotation("error", f"{PERMISSIONS_ERROR.format(status=status)}. {FAIL_ON_ERROR_HINT}")
else:
display_body = _extract_message(body)
emit_annotation("error", f"Coverage upload failed (HTTP {status}): {display_body}. {FAIL_ON_ERROR_HINT}")
return 1 if fail_on_error else 0
# Unexpected status code
emit_annotation("notice", f"Coverage upload returned unexpected HTTP {status}: {body}")
return 0
def main(environ: Optional[Mapping[str, str]] = None, opener=urllib.request.urlopen) -> int:
env = dict(os.environ if environ is None else environ)
file_path = env.get("INPUT_FILE", "")
if not file_path or not Path(file_path).is_file():
emit_annotation("error", f"Coverage file not found: {file_path}")
return 1
fail_on_error = env.get("FAIL_ON_ERROR", "true").lower() != "false"
commit_oid = env.get("COMMIT_OID", "")
ref = env.get("REF", "")
pr_number = env.get("PR_NUMBER", "")
language = env.get("INPUT_LANGUAGE", "")
label = env.get("INPUT_LABEL", "")
log_upload_parameters(
commit_oid=commit_oid,
ref=ref,
pr_number=pr_number,
language=language,
label=label,
file_path=file_path,
)
try:
payload = build_payload(
file_path=file_path,
language=language,
label=label,
commit_oid=commit_oid,
ref=ref,
pr_number=pr_number,
)
except ValueError as error:
emit_annotation("error", str(error))
return 1
status, body = upload_report(
payload=payload,
repository=env.get("GITHUB_REPOSITORY", ""),
api_url=env.get("GITHUB_API_URL", "https://api.github.com"),
token=env.get("GH_TOKEN", ""),
opener=opener,
)
return handle_response(status, body, fail_on_error)
if __name__ == "__main__":
sys.exit(main())