|
| 1 | +""" |
| 2 | +GitHub Related Functions |
| 3 | +""" |
| 4 | +import re |
| 5 | +import requests |
| 6 | +from dateutil.parser import parse |
| 7 | +from .exceptions import GithubGraphQLError |
| 8 | + |
| 9 | +GITHUB_GRAPHQL_API_URL = 'https://api.github.com/graphql' |
| 10 | + |
| 11 | + |
| 12 | +def get_created_datetime(item): |
| 13 | + """ |
| 14 | + Key function for sorting comments by creation date |
| 15 | +
|
| 16 | + :param item: |
| 17 | + :return: |
| 18 | + """ |
| 19 | + return parse(item['created_at']) |
| 20 | + |
| 21 | + |
| 22 | +def parse_github_link_header(link_value) -> dict: |
| 23 | + """ |
| 24 | + A parser for the github assigned HTTP HEADER, 'Link' value, used for paging. |
| 25 | +
|
| 26 | + :param link_value: Value of the 'Link' HTTP HEADER |
| 27 | + :return: Mapping of Conditional Links (next, last, etc) |
| 28 | + """ |
| 29 | + parsed_links = {} |
| 30 | + for value in link_value.split(','): |
| 31 | + url_raw, condition_raw = value.split('; ') |
| 32 | + url = url_raw.strip()[1:-1] |
| 33 | + condition = re.findall(r'\"(.+?)\"', condition_raw.strip())[0] |
| 34 | + parsed_links[condition] = url |
| 35 | + return parsed_links |
| 36 | + |
| 37 | + |
| 38 | +def run_graphql_request(query: str, token: str, raise_on_error: bool=False): |
| 39 | + """ |
| 40 | + Run a GraphQL Query against the github graphql API |
| 41 | +
|
| 42 | + :param query: |
| 43 | + :param token: |
| 44 | + :param raise_on_error: |
| 45 | + :return: |
| 46 | + """ |
| 47 | + headers = {"Authorization": f"token {token}"} |
| 48 | + response = requests.post(GITHUB_GRAPHQL_API_URL, json={"query": query}, headers=headers) |
| 49 | + if response.status_code == 200: |
| 50 | + result = response.json() |
| 51 | + if raise_on_error: |
| 52 | + if not result['data'] and result['errors']: |
| 53 | + raise GithubGraphQLError(result['errors']) |
| 54 | + return result |
| 55 | + else: |
| 56 | + raise GithubGraphQLError("Query failed to run by returning code of {}. {}".format(response.status_code, query)) |
0 commit comments