/
github.py
322 lines (260 loc) · 9.62 KB
/
github.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# -*- coding: utf-8 -*-
"""
(c) 2014-2020 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
Michal Konecny <mkonecny@redhat.com>
"""
import logging
from anitya.config import config
from anitya.lib import utilities
from anitya.lib.backends import REQUEST_HEADERS, BaseBackend, http_session
from anitya.lib.exceptions import AnityaPluginException, RateLimitException
API_URL = "https://api.github.com/graphql"
"""
Rate limit threshold (percent)
10 percent of limit is left for users
"""
RATE_LIMIT_THRESHOLD = 0.1
_log = logging.getLogger(__name__)
"""
Reset time that is currently set for GitHub backend.
Used when GitHub starts returning HTTP status code 403,
which doesn't contains this information anymore.
"""
reset_time = "1970-01-01T00:00:00Z"
class GithubBackend(BaseBackend):
"""The custom class for projects hosted on github.com.
This backend is using GitHub API v4 to query releases
for projects hosted on github.com
See: https://developer.github.com/v4/
"""
name = "GitHub"
examples = [
"https://github.com/fedora-infra/fedocal",
"https://github.com/fedora-infra/pkgdb2",
]
@classmethod
def get_version_url(cls, project):
"""Method called to retrieve the url used to check for new version
of the project provided, project that relies on the backend of this plugin.
Attributes:
project (:obj:`anitya.db.models.Project`): Project object whose backend
corresponds to the current plugin.
Returns:
str: url used for version checking
"""
url = ""
if project.version_url:
url = project.version_url
elif project.homepage.startswith("https://github.com/"):
url = project.homepage.replace("https://github.com/", "")
if url.endswith("/"):
url = url[:-1]
if url:
url_template = "https://github.com/%(repo)s/%(release_or_tag)s"
release_or_tag = "releases" if project.releases_only else "tags"
return url_template % {"repo": url, "release_or_tag": release_or_tag}
return url
@classmethod
def _retrieve_versions(cls, owner, repo, project):
query = prepare_query(owner, repo, project.releases_only)
try:
headers = REQUEST_HEADERS.copy()
token = config["GITHUB_ACCESS_TOKEN"]
if not token:
raise AnityaPluginException("github_access_token not configured")
headers["Authorization"] = f"bearer {token}"
resp = http_session.post(
API_URL,
json={"query": query},
headers=headers,
timeout=60,
verify=True,
)
except Exception as err:
_log.debug("%s ERROR: %s", project.name, str(err))
raise AnityaPluginException(
f'Could not call : "{API_URL}" of "{project.name}", '
f"with error: {str(err)}"
) from err
if resp.ok:
json = resp.json()
elif resp.status_code == 403:
_log.info("Github API ratelimit reached.")
raise RateLimitException(reset_time)
else:
raise AnityaPluginException(
f"{project.name}: Server responded with status "
f'"{resp.status_code}": "{resp.reason}"'
)
versions = parse_json(json, project)
_log.debug("Retrieved versions: %s", versions)
return versions
@classmethod
def get_versions(cls, project):
"""Method called to retrieve all the versions (that can be found)
of the projects provided, project that relies on the backend of
this plugin.
Args:
project (:obj:`anitya.db.models.Project`): Project object whose backend
corresponds to the current plugin.
Returns:
:obj:`list`: A list of all the possible releases found
Raises:
AnityaPluginException: A
:obj:`anitya.lib.exceptions.AnityaPluginException` exception
when the versions cannot be retrieved correctly
"""
owner = None
repo = None
url = cls.get_version_url(project)
if url:
url = url.replace("https://github.com/", "")
url = utilities.remove_suffix(url, "/releases")
url = utilities.remove_suffix(url, "/tags")
else:
raise AnityaPluginException(
f"Project {project.name} was incorrectly set up."
)
try:
(owner, repo) = url.split("/")
except ValueError as err:
raise AnityaPluginException(
f"""Project {project.name} was incorrectly set up.
Can't parse owner and repo."""
) from err
versions = cls._retrieve_versions(owner, repo, project)
if len(versions) == 0:
raise AnityaPluginException(f"{project.name}: No upstream version found.")
# Filter retrieved versions
filtered_versions = cls.filter_versions(
[version["version"] for version in versions], project.version_filter
)
return [
version for version in versions if version["version"] in filtered_versions
]
@classmethod
def check_feed(cls): # pragma: no cover
"""Method called to retrieve the latest uploads to a given backend,
via, for example, RSS or an API.
Not Supported
Returns:
:obj:`list`: A list of 4-tuples, containing the project name, homepage, the
backend, and the version.
Raises:
NotImplementedError: If backend does not
support batch updates.
"""
raise NotImplementedError()
def parse_json(json, project):
"""Function for parsing json response
Args:
json (dict): Json dictionary to parse.
project (:obj:`anitya.db.models.Project`): Project object whose backend
corresponds to the current plugin.
Returns:
:obj:`list`: A list of all the possible releases found.
Raises:
AnityaPluginException: A
:obj:`anitya.lib.exceptions.AnityaPluginException` exception
when the versions cannot be retrieved correctly.
RateLimitException: A
:obj:`anitya.lib.exceptions.RateLimitException` exception
when rate limit threshold is reached.
"""
global reset_time # pylint: disable=W0603
# We need to check limit first,
# because exceeding the limit will also return error
try:
limit = json["data"]["rateLimit"]["limit"]
remaining = json["data"]["rateLimit"]["remaining"]
reset_time = json["data"]["rateLimit"]["resetAt"]
_log.debug(
"Github API ratelimit remains %s, will reset at %s UTC",
remaining,
reset_time,
)
if (remaining / limit) <= RATE_LIMIT_THRESHOLD:
raise RateLimitException(reset_time)
except KeyError:
_log.info("Github API ratelimit key is missing. Checking for errors.")
if "errors" in json:
error_str = ""
for error in json["errors"]:
error_str += f"\"{error['type']}\": \"{error['message']}\"\n"
raise AnityaPluginException(
f"{project.name}: Server responded with following errors\n{error_str}"
)
if project.releases_only:
json_data = json["data"]["repository"]["releases"]
else:
json_data = json["data"]["repository"]["refs"]
total_count = json_data["totalCount"]
if project.releases_only:
_log.debug("Received %s releases for %s", total_count, project.name)
else:
_log.debug("Received %s tags for %s", total_count, project.name)
versions = []
for edge in json_data["edges"]:
version = {}
if project.releases_only:
hook = edge["node"]["tag"]
else:
hook = edge["node"]
if hook:
version["version"] = hook["name"]
version["commit_url"] = hook["target"]["commitUrl"]
versions.append(version)
else:
_log.info(
"Skipping release %s on %s, because it doesn't have associated tag",
edge["node"]["name"],
project.name,
)
return versions
def prepare_query(owner, repo, releases_only):
"""Function for preparing GraphQL query for specified repository
Args:
owner (str): Owner of the repository.
repo (str): Repository name.
releases_only (bool): Fetch releases instead of tags.
Returns:
str: GraphQL query.
"""
tag_fragment = "name target { commitUrl }"
fetch_args = {}
if releases_only:
fetch_obj = "releases"
# get release name and follow release -> tag
rel_tag_fragment = f"name tag {{ {tag_fragment} }}"
order_by_field = "CREATED_AT"
else:
fetch_obj = "refs"
rel_tag_fragment = tag_fragment
fetch_args["refPrefix"] = '"refs/tags/"'
order_by_field = "TAG_COMMIT_DATE"
fetch_args["orderBy"] = f"{{field: {order_by_field}, direction: ASC}}"
fetch_args["last"] = "50"
fetch_fragment = (
f"{fetch_obj} ({', '.join(f'{k}: {v}' for k, v in fetch_args.items())})"
)
query = f"""
{{
repository(owner: "{owner}", name: "{repo}") {{
{fetch_fragment} {{
totalCount
edges {{
node {{
{rel_tag_fragment}
}}
}}
}}
}}
rateLimit {{
limit
remaining
resetAt
}}
}}"""
return query