|
1 |
| -from fastapi import HTTPException, logger |
| 1 | +from fastapi import HTTPException |
2 | 2 | import requests
|
| 3 | +import time |
| 4 | +import logging |
3 | 5 |
|
| 6 | +logger = logging.getLogger(__name__) |
4 | 7 |
|
5 |
| -def get_pr_commits(repo_full_name, pr_number, github_token): |
6 |
| - """Fetch the list of commits for a PR from GitHub API.""" |
| 8 | +def get_pr_commits(repo_full_name: str, pr_number: int, github_token: str, retries: int = 3, backoff_factor: float = 0.5): |
| 9 | + """Fetch the list of commits for a PR from GitHub API with retries and exception handling.""" |
7 | 10 | url = f"https://api.github.com/repos/{repo_full_name}/pulls/{pr_number}/commits"
|
8 |
| - print(url) |
9 |
| - headers = {"Authorization": f"{github_token}", "Accept": "application/vnd.github.v3+json"} |
| 11 | + headers = { |
| 12 | + "Authorization": f"{github_token}", |
| 13 | + "Accept": "application/vnd.github.v3+json" |
| 14 | + } |
10 | 15 |
|
11 |
| - response = requests.get(url, headers=headers) |
12 |
| - |
13 |
| - if response.status_code != 200: |
14 |
| - logger.error(f"Failed to fetch commits: {response.text}") |
15 |
| - raise HTTPException(status_code=500, detail="Error fetching PR commits") |
| 16 | + for attempt in range(retries): |
| 17 | + try: |
| 18 | + response = requests.get(url, headers=headers, timeout=10) |
| 19 | + if response.status_code == 200: |
| 20 | + return response.json() |
| 21 | + else: |
| 22 | + logger.warning(f"Attempt {attempt + 1}: GitHub API returned {response.status_code} - {response.text}") |
| 23 | + except requests.exceptions.RequestException as e: |
| 24 | + logger.warning(f"Attempt {attempt + 1}: Request failed with exception: {e}") |
16 | 25 |
|
17 |
| - return response.json() |
| 26 | + sleep_time = backoff_factor * (2 ** attempt) |
| 27 | + time.sleep(sleep_time) |
| 28 | + |
| 29 | + # If all retries fail |
| 30 | + logger.error(f"Failed to fetch commits for PR #{pr_number} in {repo_full_name} after {retries} attempts.") |
| 31 | + raise HTTPException(status_code=502, detail="Failed to fetch PR commits from GitHub") |
0 commit comments