-
Notifications
You must be signed in to change notification settings - Fork 0
/
relies_on.py
299 lines (254 loc) · 9.81 KB
/
relies_on.py
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""Relies-on module."""
import os
import sys
from dataclasses import dataclass
from typing import Any, Callable, Dict, FrozenSet, List, Tuple
import requests as req
ERR_EXIT_CODE: int = 1
SCC_EXIT_CODE: int = 0
TRIGGER_EVENTS: FrozenSet[str] = frozenset(
{
"branch_protection_rule",
"check_run",
"check_suite",
"create",
"delete",
"deployment",
"deployment_status",
"discussion",
"discussion_comment",
"fork",
"gollum",
"issue_comment",
"issues",
"label",
"milestone",
"page_build",
"project",
"project_card",
"project_column",
"public",
"pull_request",
"pull_request_comment",
"pull_request_review",
"pull_request_review_comment",
"pull_request_target",
"push",
"registry_package",
"release",
"repository_dispatch",
"schedule",
"status",
"watch",
"workflow_call",
"workflow_dispatch",
"workflow_run",
}
)
@dataclass
class Filter:
"""A dataclass for filtering workflow runs.
In all docstring params below we refer to the workflow
which we want to check its status (relay on its status) as WFlow.
:param owner: the username of the repository owner.
:param repo: the repository name.
:param workflow_name: the WFlow name.
:param branch: the branch name where WFlow runs.
:param event: the trigger event type which triggers WFlow.
:param exclude_pull_requests: If true runs on pull requests will be omitted.
:raises SystemExit: when an invalid trigger `event` provided.
"""
def __post_init__(self) -> None:
if self.event and self.event not in TRIGGER_EVENTS:
print(str(self), end="")
print(
f"{self.event!r} trigger event is not a valid trigger event.",
file=sys.stderr,
)
sys.exit(ERR_EXIT_CODE)
# PATH PARAMS
owner: str
repo: str
# MANUAL PARAMS
workflow_name: str
# QUERY PARAMS
branch: str
event: str
exclude_pull_requests: bool
def __str__(self) -> str:
return (
f"\nRepository: {self.owner}/{self.repo}\n"
f"Workflow name: {self.workflow_name}\n"
f"Branch name: {self.branch}\n"
f"Trigger event: {self.event}\n"
f"Exclude PRs: {self.exclude_pull_requests}"
f" {'(default)' if self.exclude_pull_requests else ''}\n\n"
)
class GithubClient:
"""A minimalist client for Github's API.
:param filter_: a `Filter` object for filtring the workflow runs.
"""
ROOT_ENDPOINT: str = "https://api.github.com"
def __init__(self, filter_: Filter) -> None:
self._runs_endpoint = f"/repos/{filter_.owner}/{filter_.repo}/actions/runs"
self._repo_endpoint = f"/repos/{filter_.owner}/{filter_.repo}"
self.filter = filter_
def _build_query_params(self, query_params: Dict[str, object]) -> str:
#: builds and returns stringified query params
#: based on the given key-value `query_params` dict.
params: str = ""
for key, value in query_params.items():
if value:
params += ("&" if params else "") + f"{key}={value}"
if params:
params = "?" + params
return params
def _build_url(self, endpoint: str, query_params: Dict[str, object]) -> str:
#: builds and returns stringified complete url
#: based on the given `endpoint` and the `query_params` dict.
return self.ROOT_ENDPOINT + endpoint + self._build_query_params(query_params)
def _make_request(self, endpoint_url: str) -> Any:
#: makes a GET request safely and returns jsonified results
#: based on the given `endpoint_url` (complete url).
try:
res = req.get(endpoint_url, timeout=5)
assert (
res.status_code == 200
), f"\nUnexpected status code: {res.status_code}.\n"
return res.json()
except (req.ConnectionError, req.Timeout, AssertionError) as err:
print(err, file=sys.stderr)
sys.exit(ERR_EXIT_CODE)
def _report(method: Callable[["GithubClient"], Any]) -> Any: # type: ignore[misc] # noqa: N805,E501
#: A decorator outputs the current filtring (`Filter`/`self.filter`)
#: report in case of SystemExit occurrence.
def wrapper(self, *args, **kwargs) -> Any:
try:
return method( # pylint: disable=not-callable
self, *args, **kwargs
) # type: ignore[call-arg]
except SystemExit as err:
print(str(self.filter), file=sys.stderr)
sys.exit(err.code)
return wrapper
@_report
def _get_default_branch(self) -> str:
#: returns the default branch name based on `self.filter.repository`.
#: this method should be used when no `self.filter.branch` was specified.
url: str = self._build_url(self._repo_endpoint, query_params={})
repository: dict = self._make_request(url)
default_branch: str = repository.get("default_branch", "")
if not default_branch:
print("\nThis repository has no default branch.", file=sys.stderr)
print("Please use the `branch` action input.", file=sys.stderr)
sys.exit(ERR_EXIT_CODE)
return default_branch
@_report
def _get_runs(self) -> List[dict]:
#: returns a list of filtered workflow runs
#: based on `self.filter` PATH and QUERY params.
if not self.filter.branch:
self.filter.branch = self._get_default_branch()
query_params = {
"branch": self.filter.branch,
"event": self.filter.event,
"exclude_pull_requests": self.filter.exclude_pull_requests,
}
url: str = self._build_url(
self._runs_endpoint,
query_params,
)
data: dict = self._make_request(url)
if not data["total_count"]:
print(
"\nNo workflow runs were found based on the given arguments:",
file=sys.stderr,
)
sys.exit(ERR_EXIT_CODE)
return data["workflow_runs"]
@_report
def get_filtered_runs(self) -> List[dict]:
"""Returns a list of filtered workflow runs base on `self.filter`
values including the manual filtering params.
:returns: a list of dicts of workflow runs.
:raises SystemExit: when no workflow run exists
based on `self.filter` values.
"""
runs: List[dict] = self._get_runs()
filtered_runs: List[dict] = []
for run in runs:
if run["repository"]["fork"]:
continue
if run["name"].lower() == self.filter.workflow_name.lower():
filtered_runs.append(run)
if not filtered_runs:
print(
"\nNo workflow runs were found based on the given arguments:",
file=sys.stderr,
)
sys.exit(ERR_EXIT_CODE)
return filtered_runs
def get_exit_code(runs: List[dict]) -> int:
"""Determine an exit code based on the given list of workflow `runs`.
:param runs: a list of dicts of workflow runs.
:returns: an exit code represents the status of the latest workflow run.
"""
lastest_run: dict = runs[0]
if (lastest_run["status"], lastest_run["conclusion"]) == ("completed", "success"):
return SCC_EXIT_CODE
return ERR_EXIT_CODE
def output_conclusion(report: str, exit_code: int) -> None:
"""Outputs a conclusion based on the given `report` and `exit_code`.
:param report: a filtering report.
:param exit_code: an exit code represents pass or fail status.
"""
std = sys.stdout if exit_code == SCC_EXIT_CODE else sys.stderr
status = "succeeded" if exit_code == SCC_EXIT_CODE else "failed"
print("Based on the given arguments:", end="", file=std)
print(report, end="", file=std)
print(f"The latest run has {status}!", file=std)
def get_owner_repo_environs() -> Tuple[str, str]:
"""Returns default values of the `owner` username and `repository` name in
case `INPUT_OWNER` or `INPUT_REPOSITORY` environs are not provided,
otherwise, the values of `INPUT_OWNER` and `INPUT_REPOSITORY` would be
returned as (owner, repo), respectively.
:returns: a tuple of repo owner username and repo name, respectively.
"""
d_owner, d_repo = os.getenv("GITHUB_REPOSITORY", "").split("/")
owner = os.getenv("INPUT_OWNER", "")
if not owner:
owner = d_owner
repo = os.getenv("INPUT_REPOSITORY", "")
if not repo:
repo = d_repo
return owner, repo
def str2bool(val: str) -> bool:
"""A custom str to bool casting.
For `n`, `no`, `f`, `false`, `off`, and `0`
this function will return False otherwise True.
:param val: a value to cast.
:reutrns: casted `val` as bool.
"""
val = val.lower()
if val in {"n", "no", "f", "false", "off", "0"}:
return False
return True # valid only in `relies_on.py` use case.
def main() -> int: # pylint: disable=missing-function-docstring
owner, repo = get_owner_repo_environs()
filter_ = Filter(
owner=owner,
repo=repo,
workflow_name=os.getenv("INPUT_WORKFLOW", ""),
branch=os.getenv("INPUT_BRANCH", ""),
event=os.getenv("INPUT_EVENT", "").lower(),
exclude_pull_requests=str2bool(
os.getenv("INPUT_EXCLUDE_PULL_REQUESTS", "true")
),
)
gh_client = GithubClient(filter_)
runs: List[dict] = gh_client.get_filtered_runs()
exit_code: int = get_exit_code(runs)
output_conclusion(str(filter_), exit_code)
return exit_code
if __name__ == "__main__":
sys.exit(main()) # pragma: no cover