diff --git a/services/github/pulls_manager.py b/services/github/pulls_manager.py index dcf75d59..1c277fe4 100644 --- a/services/github/pulls_manager.py +++ b/services/github/pulls_manager.py @@ -2,6 +2,7 @@ from config import GITHUB_API_URL, TIMEOUT, PER_PAGE from services.github.create_headers import create_headers from services.github.github_types import BaseArgs +from services.github.user_manager import check_user_is_collaborator from utils.handle_exceptions import handle_exceptions @@ -15,9 +16,24 @@ def add_reviewers(base_args: BaseArgs): base_args["token"], base_args["reviewers"], ) + + # Check if the reviewers are collaborators because reviewers must be collaborators + valid_reviewers: list[str] = [] + for reviewer in reviewers: + is_collaborator = check_user_is_collaborator( + owner=owner, repo=repo, user=reviewer, token=token + ) + if is_collaborator: + valid_reviewers.append(reviewer) + + # If no valid reviewers, return + if not valid_reviewers: + return + + # Add the reviewers to the pull request url = f"{GITHUB_API_URL}/repos/{owner}/{repo}/pulls/{pr_number}/requested_reviewers" headers = create_headers(token=token) - json = {"reviewers": reviewers} + json = {"reviewers": valid_reviewers} response = requests.post(url=url, headers=headers, json=json, timeout=TIMEOUT) response.raise_for_status() diff --git a/services/github/user_manager.py b/services/github/user_manager.py new file mode 100644 index 00000000..0d2479c7 --- /dev/null +++ b/services/github/user_manager.py @@ -0,0 +1,14 @@ +import requests +from config import GITHUB_API_URL, TIMEOUT +from services.github.create_headers import create_headers +from utils.handle_exceptions import handle_exceptions + + +@handle_exceptions(default_return_value=False, raise_on_error=False) +def check_user_is_collaborator(owner: str, repo: str, user: str, token: str) -> bool: + """https://docs.github.com/en/rest/collaborators/collaborators?apiVersion=2022-11-28#check-if-a-user-is-a-repository-collaborator""" + url = f"{GITHUB_API_URL}/repos/{owner}/{repo}/collaborators/{user}" + headers = create_headers(token=token) + response = requests.get(url=url, headers=headers, timeout=TIMEOUT) + response.raise_for_status() + return response.status_code == 204