-
Notifications
You must be signed in to change notification settings - Fork 1
/
gh2slack.py
executable file
·376 lines (335 loc) · 11 KB
/
gh2slack.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/usr/bin/env python3
"""Get GH issues/pull requests and post them to Slack.
2017/Nov/18 @ Zdenek Styblik <[email protected]>
"""
import argparse
import logging
import re
import sys
import time
import traceback
import urllib.parse
from typing import Dict
from typing import List
from typing import Set
import requests
import rss2irc # noqa: I202
import rss2slack # noqa: I202
from lib import CachedData # noqa: I202
from lib import config_options # noqa: I202
ALIASES = {
"issues": "issue",
"pulls": "pr",
}
DEFAULT_HTTP_PROTO = "https"
DEFAULT_GH_URL = "github.com"
RE_LINK_REL_NEXT = re.compile(r"<(?P<next>.*)>; rel=\"next")
def format_message(
logger: logging.Logger,
owner: str,
repo: str,
section: str,
html_url: str,
cache_item: Dict,
) -> Dict:
"""Return formatted message as Slack's BlockKit section."""
try:
title = cache_item["title"].encode("utf-8")
except UnicodeEncodeError:
logger.error(
"Failed to encode title as UTF-8: %s",
repr(cache_item.get("title", None)),
)
logger.error("%s", traceback.format_exc())
title = "Unknown title due to UTF-8 exception, {:s}#{:d}".format(
section, cache_item["number"]
)
try:
message = "[<{}|{}/{}>] <{}|{}#{:d}> | {:s}".format(
cache_item["repository_url"],
owner,
repo,
html_url,
section,
cache_item["number"],
title.decode("utf-8"),
)
except UnicodeDecodeError:
logger.error("Failed to format message: %s", traceback.format_exc())
message = "[{:s}/{:s}] Failed to format message for {:s}#{:d}".format(
owner, repo, section, cache_item["number"]
)
return {
"type": "section",
"text": {
"type": "mrkdwn",
"text": message,
},
}
def get_gh_api_url(owner: str, repo: str, section: str) -> str:
"""Return assembled GitHub API URL."""
return "{}://api.{}/repos/{}".format(
DEFAULT_HTTP_PROTO, DEFAULT_GH_URL, "/".join([owner, repo, section])
)
def get_gh_repository_url(owner: str, repo: str) -> str:
"""Return assembled GitHub Repository URL."""
return "{}://{}/{}/{}".format(
DEFAULT_HTTP_PROTO, DEFAULT_GH_URL, owner, repo
)
def gh_parse_next_page(link_header: str) -> str:
"""Parse link to the next page from GitHub's Link header."""
next_page = ""
for chunk in str(link_header).split('",'):
match = RE_LINK_REL_NEXT.search(chunk)
if match:
next_page = match.groupdict()["next"]
break
return next_page
def gh_request(
logger: logging.Logger, url: str, timeout: int = config_options.HTTP_TIMEOUT
) -> List:
"""Return list of responses from GitHub.
Makes request to GH, follows 'Link' header if present, and returns list
responses.
"""
logger.debug("Requesting %s", url)
user_agent = "gh2slack_{:d}".format(int(time.time()))
rsp = requests.get(
url,
headers={
"Accept": "application/vnd.github.v3+json",
"User-Agent": user_agent,
},
params={"state": "open", "sort": "created"},
timeout=timeout,
)
logger.debug("HTTP Status Code %i", rsp.status_code)
rsp.raise_for_status()
logger.debug("RSP Headers: %s", rsp.headers)
# In order to get everything, we must follow URLs in the 'Link' header as
# long as there is next one to follow.
link_header = rsp.headers.get("link", "")
next_page = gh_parse_next_page(str(link_header))
if not next_page:
return [rsp.json()]
# NOTE: 'state' and 'sort' will be added again, therefore let's get rid off
# them. If we didn't do this, number of params would grow with each
# recursion.
parsed = urllib.parse.urlparse(next_page)
qdict = urllib.parse.parse_qs(parsed.query)
qdict.pop("state", None)
qdict.pop("sort", None)
new_query = urllib.parse.urlencode(qdict, doseq=True)
parsed = parsed._replace(query=new_query)
# FIXME(zstyblik): unlimited recursion. This will require some refactoring.
# However, since nobody is using this, later.
return [rsp.json()] + gh_request(logger, parsed.geturl(), timeout)
def main():
"""Fetch issues/PRs from GitHub and post them to Slack."""
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
logger = logging.getLogger("gh2slack")
args = parse_args()
if args.verbosity:
logger.setLevel(logging.DEBUG)
try:
slack_token = rss2slack.get_slack_token()
url = get_gh_api_url(args.gh_owner, args.gh_repo, args.gh_section)
pages = gh_request(logger, url)
logger.debug("Got %i pages from GH.", len(pages))
if not pages:
logger.info(
"No %s for %s/%s.", args.gh_section, args.gh_owner, args.gh_repo
)
sys.exit(0)
cache = rss2irc.read_cache(logger, args.cache)
scrub_items(logger, cache)
# Note: I have failed to find web link to repo in GH response.
# Therefore, let's create one.
repository_url = get_gh_repository_url(args.gh_owner, args.gh_repo)
item_expiration = int(time.time()) + args.cache_expiration
to_publish = process_page_items(
logger, cache, pages, item_expiration, repository_url
)
if not args.cache_init and to_publish:
slack_client = rss2slack.get_slack_web_client(
slack_token, args.slack_base_url, args.slack_timeout
)
for html_url in to_publish:
cache_item = cache.items[html_url]
try:
msg_blocks = [
format_message(
logger,
args.gh_owner,
args.gh_repo,
ALIASES[args.gh_section],
html_url,
cache_item,
)
]
rss2slack.post_to_slack(
logger,
msg_blocks,
slack_client,
args.slack_channel,
)
except Exception:
logger.error("%s", traceback.format_exc())
cache.items.pop(html_url)
finally:
time.sleep(args.sleep)
rss2irc.write_cache(cache, args.cache)
except Exception:
logger.debug("%s", traceback.format_exc())
# TODO(zstyblik):
# 1. touch error file
# 2. send error message to the channel
finally:
sys.exit(0)
def parse_args() -> argparse.Namespace:
"""Return parsed CLI args."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--cache",
dest="cache",
type=str,
default=None,
help="Path to cache file.",
)
parser.add_argument(
"--cache-expiration",
dest="cache_expiration",
type=int,
default=config_options.CACHE_EXPIRATION,
help="Time, in seconds, for how long to keep items " "in cache.",
)
parser.add_argument(
"--cache-init",
dest="cache_init",
action="store_true",
default=False,
help=(
"Prevents posting news to IRC. This is useful "
"when bootstrapping new RSS feed."
),
)
parser.add_argument(
"--gh-owner",
dest="gh_owner",
required=True,
type=str,
help="Owner/org of the repository to track.",
)
parser.add_argument(
"--gh-repo",
dest="gh_repo",
required=True,
type=str,
help="Repository of owner/org to track.",
)
parser.add_argument(
"--gh-section",
dest="gh_section",
required=True,
choices=["issues", "pulls"],
help='GH "section" to track.',
)
parser.add_argument(
"--slack-base-url",
dest="slack_base_url",
type=str,
default=rss2slack.SLACK_BASE_URL,
help="Base URL for Slack client.",
)
parser.add_argument(
"--slack-channel",
dest="slack_channel",
type=str,
required=True,
help="Name of Slack channel to send formatted news to.",
)
parser.add_argument(
"--slack-timeout",
dest="slack_timeout",
type=int,
default=config_options.HTTP_TIMEOUT,
help="Slack API Timeout. Defaults to {:d} seconds.".format(
config_options.HTTP_TIMEOUT
),
)
parser.add_argument(
"--sleep",
dest="sleep",
type=int,
default=2,
help=(
"Sleep between messages in order to avoid "
"possible excess flood/API call rate limit."
),
)
parser.add_argument(
"-v",
"--verbose",
dest="verbosity",
action="store_true",
default=False,
help="Increase logging verbosity.",
)
return parser.parse_args()
def process_page_items(
logger: logging.Logger,
cache: CachedData,
pages: List,
expiration: int,
repository_url: str,
) -> Set:
"""Parse page items, update cache and return items to publish.
:param pages: list of lists, resp. whatever GH API returns
"""
to_publish = set()
page_num = 0
for page_items in pages:
page_num += 1
logger.debug("Page #%i has %i items.", page_num, len(page_items))
for item in page_items:
if (
"html_url" not in item
or "number" not in item
or "title" not in item
):
logger.debug("Item doesn't have required fields: %s", item)
continue
if item["html_url"] in cache.items:
cache.items[item["html_url"]]["expiration"] = expiration
continue
try:
item_number = int(item["number"])
except ValueError:
logger.error("Failed to convert %s to int.", item["number"])
item_number = 0
cache.items[item["html_url"]] = {
"expiration": expiration,
"number": item_number,
"repository_url": repository_url,
"title": item["title"],
}
to_publish.add(item["html_url"])
return to_publish
def scrub_items(logger: logging.Logger, cache: CachedData) -> None:
"""Scrub cache and remove expired items."""
time_now = int(time.time())
for key in list(cache.items.keys()):
try:
expiration = int(cache.items[key]["expiration"])
except (KeyError, ValueError):
logger.error("%s", traceback.format_exc())
logger.error(
"Invalid cache entry will be removed: '%s'", cache.items[key]
)
cache.items.pop(key)
continue
if expiration < time_now:
logger.debug("URL %s has expired.", key)
cache.items.pop(key)
if __name__ == "__main__":
main()