import datetime import os import sys import github import requests GITHUB_API_KEY = os.getenv('GITHUB_API_KEY') GITHUB_REPO_NAME = os.getenv('GITHUB_REPO_NAME') GITHUB_PR_NUM = os.getenv('GITHUB_PR_NUM') CLEANUP_DELETE = os.getenv('CLEANUP_DELETE', 'false') CLEANUP_USERS = os.getenv('CLEANUP_USERS', 'orchardci,orcdjenkins') CLEANUP_TTL = os.getenv('CLEANUP_TTL', '600') if __name__ == '__main__': print('Checking environment variables') if (not GITHUB_API_KEY or not GITHUB_REPO_NAME or not GITHUB_PR_NUM): sys.exit('Error: you need to specify GITHUB_API_KEY, GITHUB_REPO_NAME ' 'and GITHUB_PR_NUM environment variables to analyze and put ' 'comments to Github pull-requests.') CLEANUP_DELETE = True if CLEANUP_DELETE == 'true' else False users = CLEANUP_USERS.split(',') ttl = int(CLEANUP_TTL) now = datetime.datetime.now() print('Checking Github pull-request') try: gh = github.Github(GITHUB_API_KEY) repo = gh.get_repo(GITHUB_REPO_NAME) pr = repo.get_pull(int(GITHUB_PR_NUM)) except github.BadCredentialsException: sys.exit('Error: invalid Github API key specified') except github.UnknownObjectException: sys.exit(f'Error: invalid Github repository name "{GITHUB_REPO_NAME}"' f' or pull-request number "{GITHUB_PR_NUM}" specified') except github.GithubException as exc: sys.exit(f'Error: failed to fetch Github pull-request data: {exc}') if CLEANUP_DELETE: print('Processing pull-request comments') for comment in pr.get_issue_comments(): login = comment.user.login created_at = comment.created_at print(f'Processing comment from {login} at {created_at}') if login not in users: print('Skipping the comment as its sender is not in the list') continue duration = now - created_at if duration.total_seconds() <= ttl: print("Skipping the comment as it's still fresh") continue print('Deleting the comment') comment.delete() else: url = 'https://api.github.com/graphql' headers = {'Authorization': 'token ' + GITHUB_API_KEY} repo_owner, repo_name = GITHUB_REPO_NAME.split('/') print('Fetching pull-request comments') try: query = """ query {{ repository(owner: "{}", name: "{}") {{ pullRequest(number: {}) {{ comments(last: 100) {{ nodes {{ id, createdAt, isMinimized, author {{ login }} }} }} }} }} }} """.format(repo_owner, repo_name, GITHUB_PR_NUM) r = requests.post(url, json={'query': query}, headers=headers) r.raise_for_status() comments = r.json() except requests.exceptions.HTTPError as exc: sys.exit(f'Error: failed to fetch Github pull-request comments: ' f'{exc}') print('Processing pull-request comments') for comment in (comments['data']['repository']['pullRequest'] ['comments']['nodes']): id = comment['id'] login = comment['author']['login'] created_at = datetime.datetime.strptime( comment['createdAt'], '%Y-%m-%dT%H:%M:%SZ') is_minimized = comment['isMinimized'] print(f'Processing comment from {login} at {created_at}') if login not in users: print('Skipping the comment as its sender is not in the list') continue duration = now - created_at if duration.total_seconds() <= ttl: print("Skipping the comment as it's still fresh") continue if is_minimized: print("Skipping the comment as it's already minimized") continue print('Minimizing the comment') try: query = """ mutation {{ minimizeComment( input: {{ classifier: OUTDATED, subjectId: "{}" }} ) {{ minimizedComment {{ isMinimized }} }} }} """.format(id) r = requests.post(url, json={'query': query}, headers=headers) r.raise_for_status() except requests.exceptions.HTTPError as exc: sys.exit(f'Error: failed to minimize Github pull-request ' f'comment: {exc}') print('Done')