|
| 1 | +"""GitHub Utilities""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | + |
| 6 | +from dataclasses import dataclass |
| 7 | +from typing import Any, Callable, cast, Dict, List, Optional |
| 8 | +from urllib.error import HTTPError |
| 9 | +from urllib.parse import quote |
| 10 | +from urllib.request import Request, urlopen |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class GitHubComment: |
| 15 | + body_text: str |
| 16 | + created_at: str |
| 17 | + author_login: str |
| 18 | + author_association: str |
| 19 | + editor_login: Optional[str] |
| 20 | + database_id: int |
| 21 | + |
| 22 | + |
| 23 | +def gh_fetch_url( |
| 24 | + url: str, *, |
| 25 | + headers: Optional[Dict[str, str]] = None, |
| 26 | + data: Optional[Dict[str, Any]] = None, |
| 27 | + method: Optional[str] = None, |
| 28 | + reader: Callable[[Any], Any] = lambda x: x.read() |
| 29 | +) -> Any: |
| 30 | + if headers is None: |
| 31 | + headers = {} |
| 32 | + token = os.environ.get("GITHUB_TOKEN") |
| 33 | + if token is not None and url.startswith('https://api.github.com/'): |
| 34 | + headers['Authorization'] = f'token {token}' |
| 35 | + data_ = json.dumps(data).encode() if data is not None else None |
| 36 | + try: |
| 37 | + with urlopen(Request(url, headers=headers, data=data_, method=method)) as conn: |
| 38 | + return reader(conn) |
| 39 | + except HTTPError as err: |
| 40 | + if err.code == 403 and all(key in err.headers for key in ['X-RateLimit-Limit', 'X-RateLimit-Used']): |
| 41 | + print(f"""Rate limit exceeded: |
| 42 | + Used: {err.headers['X-RateLimit-Used']} |
| 43 | + Limit: {err.headers['X-RateLimit-Limit']} |
| 44 | + Remaining: {err.headers['X-RateLimit-Remaining']} |
| 45 | + Resets at: {err.headers['x-RateLimit-Reset']}""") |
| 46 | + raise |
| 47 | + |
| 48 | + |
| 49 | +def gh_fetch_json( |
| 50 | + url: str, |
| 51 | + params: Optional[Dict[str, Any]] = None, |
| 52 | + data: Optional[Dict[str, Any]] = None |
| 53 | +) -> List[Dict[str, Any]]: |
| 54 | + headers = {'Accept': 'application/vnd.github.v3+json'} |
| 55 | + if params is not None and len(params) > 0: |
| 56 | + url += '?' + '&'.join(f"{name}={quote(str(val))}" for name, val in params.items()) |
| 57 | + return cast(List[Dict[str, Any]], gh_fetch_url(url, headers=headers, data=data, reader=json.load)) |
| 58 | + |
| 59 | +def _gh_fetch_json_any( |
| 60 | + url: str, |
| 61 | + params: Optional[Dict[str, Any]] = None, |
| 62 | + data: Optional[Dict[str, Any]] = None |
| 63 | +) -> Any: |
| 64 | + headers = {'Accept': 'application/vnd.github.v3+json'} |
| 65 | + if params is not None and len(params) > 0: |
| 66 | + url += '?' + '&'.join(f"{name}={quote(str(val))}" for name, val in params.items()) |
| 67 | + return gh_fetch_url(url, headers=headers, data=data, reader=json.load) |
| 68 | + |
| 69 | + |
| 70 | +def gh_fetch_json_list( |
| 71 | + url: str, |
| 72 | + params: Optional[Dict[str, Any]] = None, |
| 73 | + data: Optional[Dict[str, Any]] = None |
| 74 | +) -> List[Dict[str, Any]]: |
| 75 | + return cast(List[Dict[str, Any]], _gh_fetch_json_any(url, params, data)) |
| 76 | + |
| 77 | + |
| 78 | +def gh_fetch_json_dict( |
| 79 | + url: str, |
| 80 | + params: Optional[Dict[str, Any]] = None, |
| 81 | + data: Optional[Dict[str, Any]] = None |
| 82 | +) -> Dict[str, Any] : |
| 83 | + return cast(Dict[str, Any], _gh_fetch_json_any(url, params, data)) |
| 84 | + |
| 85 | + |
| 86 | +def _gh_post_comment(url: str, comment: str, dry_run: bool = False) -> List[Dict[str, Any]]: |
| 87 | + if dry_run: |
| 88 | + print(comment) |
| 89 | + return [] |
| 90 | + return gh_fetch_json_list(url, data={"body": comment}) |
| 91 | + |
| 92 | + |
| 93 | +def gh_post_pr_comment(org: str, repo: str, pr_num: int, comment: str, dry_run: bool = False) -> List[Dict[str, Any]]: |
| 94 | + return _gh_post_comment(f'https://api.github.com/repos/{org}/{repo}/issues/{pr_num}/comments', comment, dry_run) |
| 95 | + |
| 96 | + |
| 97 | +def gh_post_commit_comment(org: str, repo: str, sha: str, comment: str, dry_run: bool = False) -> List[Dict[str, Any]]: |
| 98 | + return _gh_post_comment(f'https://api.github.com/repos/{org}/{repo}/commits/{sha}/comments', comment, dry_run) |
| 99 | + |
| 100 | + |
| 101 | +def gh_delete_comment(org: str, repo: str, comment_id: int) -> None: |
| 102 | + url = f"https://api.github.com/repos/{org}/{repo}/issues/comments/{comment_id}" |
| 103 | + gh_fetch_url(url, method="DELETE") |
0 commit comments