|
| 1 | +import os |
| 2 | +from collections import Counter |
| 3 | +from datetime import datetime |
| 4 | +from typing import Any, Dict, List |
| 5 | + |
| 6 | +import requests |
| 7 | +from json_helpers import load_json, save_json |
| 8 | + |
| 9 | +# from dotenv import load_dotenv |
| 10 | + |
| 11 | +# load_dotenv() |
| 12 | + |
| 13 | +cached_issues_file = "cache/github_issues_cache.json" |
| 14 | + |
| 15 | + |
| 16 | +def get_open_issues( |
| 17 | + repo_owner: str = "digital-land", |
| 18 | + repo_name: str = "planning-application-data-specification", |
| 19 | + github_token: str = None, |
| 20 | +) -> List[Dict[str, Any]]: |
| 21 | + """ |
| 22 | + Fetch all open issues from a GitHub repository. |
| 23 | +
|
| 24 | + Args: |
| 25 | + repo_owner: GitHub repository owner |
| 26 | + repo_name: GitHub repository name |
| 27 | + github_token: GitHub token for authentication (optional) |
| 28 | +
|
| 29 | + Returns: |
| 30 | + List of issue dictionaries |
| 31 | + """ |
| 32 | + # if github_token is None: |
| 33 | + # github_token = os.getenv("GITHUB_TOKEN") |
| 34 | + |
| 35 | + # HEADERS (use token for higher rate limit) |
| 36 | + headers = { |
| 37 | + "Accept": "application/vnd.github+json", |
| 38 | + "X-GitHub-Api-Version": "2022-11-28", |
| 39 | + } |
| 40 | + if github_token: |
| 41 | + headers["Authorization"] = f"Bearer {github_token}" |
| 42 | + |
| 43 | + # PAGINATION VARIABLES |
| 44 | + issues_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/issues" |
| 45 | + params = {"state": "open", "per_page": 100, "page": 1} |
| 46 | + |
| 47 | + all_issues = [] |
| 48 | + |
| 49 | + # PAGINATE THROUGH RESULTS |
| 50 | + while True: |
| 51 | + try: |
| 52 | + response = requests.get(issues_url, headers=headers, params=params) |
| 53 | + |
| 54 | + # Handle rate limiting |
| 55 | + if response.status_code == 403: |
| 56 | + print(f"Error 403: {response.json().get('message', 'Forbidden')}") |
| 57 | + if "rate limit" in response.text.lower(): |
| 58 | + print("You've hit the rate limit. Please:") |
| 59 | + print("1. Wait a bit and try again") |
| 60 | + print( |
| 61 | + "2. Add a GITHUB_TOKEN environment variable for higher limits" |
| 62 | + ) |
| 63 | + break |
| 64 | + |
| 65 | + response.raise_for_status() |
| 66 | + issues = response.json() |
| 67 | + |
| 68 | + if not issues: |
| 69 | + break |
| 70 | + |
| 71 | + for issue in issues: |
| 72 | + # Skip pull requests (they are also issues) |
| 73 | + if "pull_request" not in issue: |
| 74 | + all_issues.append(issue) |
| 75 | + |
| 76 | + params["page"] += 1 |
| 77 | + |
| 78 | + except requests.exceptions.HTTPError as e: |
| 79 | + print(f"HTTP Error: {e}") |
| 80 | + print(f"Response: {response.text}") |
| 81 | + break |
| 82 | + except Exception as e: |
| 83 | + print(f"Unexpected error: {e}") |
| 84 | + break |
| 85 | + |
| 86 | + return all_issues |
| 87 | + |
| 88 | + |
| 89 | +def save_issues_to_file( |
| 90 | + issues: List[Dict[str, Any]], filename: str = cached_issues_file |
| 91 | +): |
| 92 | + data = { |
| 93 | + "fetch_timestamp": datetime.now().isoformat(), |
| 94 | + "fetch_timestamp_human": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), |
| 95 | + "issue_count": len(issues), |
| 96 | + "issues": issues, |
| 97 | + } |
| 98 | + save_json(data, filename) |
| 99 | + |
| 100 | + |
| 101 | +def load_issues_from_file(filename: str = cached_issues_file) -> Dict[str, Any]: |
| 102 | + data = load_json(filename) |
| 103 | + if not data: |
| 104 | + print("No data found.") |
| 105 | + return None |
| 106 | + |
| 107 | + return data |
| 108 | + |
| 109 | + |
| 110 | +def get_issues_with_cache( |
| 111 | + cache_hours: int = 1, force_refresh: bool = False |
| 112 | +) -> tuple[List[Dict[str, Any]], str]: |
| 113 | + """ |
| 114 | + Get issues with caching and timestamp tracking. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + Tuple of (issues_list, last_fetch_time) |
| 118 | + """ |
| 119 | + # Try to load existing cache |
| 120 | + cached_data = load_issues_from_file() |
| 121 | + |
| 122 | + # Check if we need to refresh |
| 123 | + need_refresh = force_refresh |
| 124 | + |
| 125 | + if cached_data: |
| 126 | + last_fetch_time = cached_data.get("fetch_timestamp_human", "Unknown") |
| 127 | + fetch_timestamp = datetime.fromisoformat(cached_data["fetch_timestamp"]) |
| 128 | + age_hours = (datetime.now() - fetch_timestamp).total_seconds() / 3600 |
| 129 | + if age_hours >= cache_hours: |
| 130 | + print(f"Cache is too old ({age_hours:.2f} hours), refreshing...") |
| 131 | + need_refresh = True |
| 132 | + else: |
| 133 | + print("No cached data found, fetching new issues...") |
| 134 | + need_refresh = True |
| 135 | + |
| 136 | + if need_refresh: |
| 137 | + print("Fetching new issues from GitHub...") |
| 138 | + issues = get_open_issues() |
| 139 | + save_issues_to_file(issues) |
| 140 | + last_fetch_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 141 | + return issues, last_fetch_time |
| 142 | + |
| 143 | + return cached_data.get("issues", []), last_fetch_time |
| 144 | + |
| 145 | + |
| 146 | +def count_labels_from_issues(issues: List[Dict[str, Any]]) -> Counter: |
| 147 | + """ |
| 148 | + Count labels from a list of issues. |
| 149 | +
|
| 150 | + Args: |
| 151 | + issues: List of issue dictionaries |
| 152 | +
|
| 153 | + Returns: |
| 154 | + Counter object with label counts |
| 155 | + """ |
| 156 | + label_counter = Counter() |
| 157 | + |
| 158 | + for issue in issues: |
| 159 | + for label in issue["labels"]: |
| 160 | + label_counter[label["name"]] += 1 |
| 161 | + |
| 162 | + return label_counter |
| 163 | + |
| 164 | + |
| 165 | +# USAGE EXAMPLE |
| 166 | +if __name__ == "__main__": |
| 167 | + # Get all open issues (with caching) |
| 168 | + issues, last_fetch_time = get_issues_with_cache() |
| 169 | + |
| 170 | + # Count labels |
| 171 | + label_counter = count_labels_from_issues(issues) |
| 172 | + |
| 173 | + # OUTPUT RESULTS |
| 174 | + print(f"Found {len(issues)} open issues") |
| 175 | + print("\nOpen issues by label:") |
| 176 | + for label, count in label_counter.most_common(): |
| 177 | + print(f"{label}: {count}") |
| 178 | + |
| 179 | + # You can now work with the issues list |
| 180 | + # For example, get issue titles: |
| 181 | + print("\nIssue titles:") |
| 182 | + for issue in issues[:5]: # Show first 5 |
| 183 | + print(f"- {issue['title']}") |
| 184 | + |
| 185 | + print(issues) |
0 commit comments