github-issue-exporter 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,241 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import tempfile
5
+ from pathlib import Path
6
+ from typing import List, Optional, Dict, Any
7
+ from datetime import datetime
8
+
9
+
10
+ class FileSystemManager:
11
+ def __init__(self, base_output_dir: str = "./exports"):
12
+ self.base_output_dir = Path(base_output_dir)
13
+
14
+ def slugify(self, text: str) -> str:
15
+ """Convert text to a filesystem-safe slug."""
16
+ # Convert to lowercase
17
+ slug = text.lower()
18
+
19
+ # Replace spaces and special characters with hyphens
20
+ slug = re.sub(r'[^\w\s-]', '', slug)
21
+ slug = re.sub(r'[-\s]+', '-', slug)
22
+
23
+ # Remove leading/trailing hyphens
24
+ slug = slug.strip('-')
25
+
26
+ # Limit length to avoid filesystem issues
27
+ slug = slug[:100]
28
+
29
+ return slug
30
+
31
+ def get_repo_directory(self, repo_owner: str, repo_name: str) -> Path:
32
+ """Get the directory path for a specific repository."""
33
+ return self.base_output_dir / repo_owner / repo_name
34
+
35
+ def get_state_directory(self, repo_owner: str, repo_name: str, state: str) -> Path:
36
+ """Get the directory path for a specific issue state."""
37
+ return self.get_repo_directory(repo_owner, repo_name) / state
38
+
39
+ def ensure_repo_directory(self, repo_owner: str, repo_name: str) -> Path:
40
+ """Ensure the repository directory and state subdirectories exist."""
41
+ repo_dir = self.get_repo_directory(repo_owner, repo_name)
42
+ repo_dir.mkdir(parents=True, exist_ok=True)
43
+
44
+ # Create open and closed subdirectories
45
+ open_dir = self.get_state_directory(repo_owner, repo_name, "open")
46
+ closed_dir = self.get_state_directory(repo_owner, repo_name, "closed")
47
+ open_dir.mkdir(parents=True, exist_ok=True)
48
+ closed_dir.mkdir(parents=True, exist_ok=True)
49
+
50
+ return repo_dir
51
+
52
+ def generate_issue_filename(self, issue_number: int, issue_title: str) -> str:
53
+ """Generate filename for an issue using issue number."""
54
+ slugified_title = self.slugify(issue_title)
55
+ return f"{issue_number}-{slugified_title}.json"
56
+
57
+ def find_existing_issue_file(self, repo_owner: str, repo_name: str, issue_number: int) -> Optional[Path]:
58
+ """Find existing issue file by number in both open and closed directories."""
59
+ pattern = f"{issue_number}-*.json"
60
+
61
+ # Check both open and closed directories
62
+ for state in ["open", "closed"]:
63
+ state_dir = self.get_state_directory(repo_owner, repo_name, state)
64
+ if state_dir.exists():
65
+ matching_files = list(state_dir.glob(pattern))
66
+ if matching_files:
67
+ return matching_files[0] # Return the first match
68
+
69
+ return None
70
+
71
+ def get_file_modification_time(self, file_path: Path) -> Optional[datetime]:
72
+ """Get the modification time of a file."""
73
+ try:
74
+ if file_path.exists():
75
+ timestamp = file_path.stat().st_mtime
76
+ # Return timezone-aware datetime in UTC
77
+ from datetime import timezone
78
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc)
79
+ except Exception:
80
+ pass
81
+ return None
82
+
83
+ def needs_update(self, file_path: Path, issue_updated_at: datetime) -> bool:
84
+ """Check if a file needs to be updated based on modification times."""
85
+ if not file_path.exists():
86
+ return True
87
+
88
+ file_mod_time = self.get_file_modification_time(file_path)
89
+ if file_mod_time is None:
90
+ return True
91
+
92
+ # Need update if issue was modified after file
93
+ return issue_updated_at > file_mod_time
94
+
95
+ def safe_write_json(self, file_path: Path, data: Dict[str, Any]) -> bool:
96
+ """Safely write JSON data to file using temp file and rename pattern."""
97
+ try:
98
+ # Ensure parent directory exists
99
+ file_path.parent.mkdir(parents=True, exist_ok=True)
100
+
101
+ # Write to temporary file first
102
+ with tempfile.NamedTemporaryFile(
103
+ mode='w',
104
+ suffix='.json.tmp',
105
+ dir=file_path.parent,
106
+ delete=False
107
+ ) as temp_file:
108
+ json.dump(data, temp_file, indent=2, default=str, ensure_ascii=False)
109
+ temp_path = Path(temp_file.name)
110
+
111
+ # Atomically rename temp file to final location
112
+ temp_path.rename(file_path)
113
+ return True
114
+
115
+ except Exception as e:
116
+ # Clean up temp file if it exists
117
+ try:
118
+ if 'temp_path' in locals():
119
+ temp_path.unlink(missing_ok=True)
120
+ except Exception:
121
+ pass
122
+ raise e
123
+
124
+ def read_existing_issue(self, file_path: Path) -> Optional[Dict[str, Any]]:
125
+ """Read existing issue data from file."""
126
+ try:
127
+ if file_path.exists():
128
+ with open(file_path, 'r', encoding='utf-8') as f:
129
+ return json.load(f)
130
+ except Exception:
131
+ pass
132
+ return None
133
+
134
+ def list_existing_issues(self, repo_owner: str, repo_name: str) -> List[Dict[str, Any]]:
135
+ """List all existing issue files and their metadata from both open and closed directories."""
136
+ issues = []
137
+
138
+ # Check both open and closed directories
139
+ for state in ["open", "closed"]:
140
+ state_dir = self.get_state_directory(repo_owner, repo_name, state)
141
+
142
+ if not state_dir.exists():
143
+ continue
144
+
145
+ for file_path in state_dir.glob("*.json"):
146
+ try:
147
+ # Extract issue number from filename
148
+ filename = file_path.stem
149
+ issue_number_match = re.match(r'^(\d+)-', filename)
150
+
151
+ if not issue_number_match:
152
+ continue
153
+
154
+ issue_number = int(issue_number_match.group(1))
155
+ mod_time = self.get_file_modification_time(file_path)
156
+
157
+ issue_data = self.read_existing_issue(file_path)
158
+
159
+ issues.append({
160
+ 'number': issue_number,
161
+ 'state': state,
162
+ 'file_path': file_path,
163
+ 'modified_time': mod_time,
164
+ 'data': issue_data
165
+ })
166
+
167
+ except Exception:
168
+ # Skip files that can't be processed
169
+ continue
170
+
171
+ return sorted(issues, key=lambda x: x['number'])
172
+
173
+ def cleanup_old_files(self, repo_owner: str, repo_name: str, current_issue_numbers: List[int]):
174
+ """Remove files for issues that no longer exist."""
175
+ existing_issues = self.list_existing_issues(repo_owner, repo_name)
176
+
177
+ for issue_info in existing_issues:
178
+ if issue_info['number'] not in current_issue_numbers:
179
+ try:
180
+ issue_info['file_path'].unlink()
181
+ except Exception:
182
+ # Ignore errors when deleting files
183
+ pass
184
+
185
+ def get_export_summary(self, repo_owner: str, repo_name: str) -> Dict[str, Any]:
186
+ """Get summary of exported issues for a repository."""
187
+ existing_issues = self.list_existing_issues(repo_owner, repo_name)
188
+
189
+ total_issues = len(existing_issues)
190
+ if total_issues == 0:
191
+ return {
192
+ 'total_issues': 0,
193
+ 'latest_export': None,
194
+ 'oldest_export': None
195
+ }
196
+
197
+ mod_times = [issue['modified_time'] for issue in existing_issues if issue['modified_time']]
198
+
199
+ return {
200
+ 'total_issues': total_issues,
201
+ 'latest_export': max(mod_times) if mod_times else None,
202
+ 'oldest_export': min(mod_times) if mod_times else None
203
+ }
204
+
205
+ def write_issue_file(self, repo_owner: str, repo_name: str, issue_data: Dict[str, Any]) -> Path:
206
+ """Write issue data to file in the appropriate state directory and return the file path."""
207
+ # Ensure repository directory and state subdirectories exist
208
+ self.ensure_repo_directory(repo_owner, repo_name)
209
+
210
+ issue_number = issue_data['issue']['number']
211
+ issue_title = issue_data['issue']['title']
212
+ issue_state = issue_data['issue']['state']
213
+
214
+ # Check if file already exists in either open or closed directory
215
+ existing_file = self.find_existing_issue_file(repo_owner, repo_name, issue_number)
216
+
217
+ # Generate new filename using issue number
218
+ filename = self.generate_issue_filename(issue_number, issue_title)
219
+
220
+ # Determine the correct state directory
221
+ target_state_dir = self.get_state_directory(repo_owner, repo_name, issue_state)
222
+ target_file_path = target_state_dir / filename
223
+
224
+ # If file exists in a different state directory, remove it (state changed)
225
+ if existing_file and existing_file.parent != target_state_dir:
226
+ try:
227
+ existing_file.unlink()
228
+ except Exception:
229
+ pass
230
+
231
+ # If file exists in same state directory but with different title, remove old file
232
+ elif existing_file and existing_file != target_file_path:
233
+ try:
234
+ existing_file.unlink()
235
+ except Exception:
236
+ pass
237
+
238
+ # Write the new file in the correct state directory
239
+ self.safe_write_json(target_file_path, issue_data)
240
+
241
+ return target_file_path
@@ -0,0 +1,334 @@
1
+ import asyncio
2
+ import math
3
+ from typing import List, Dict, Any, Optional, AsyncGenerator
4
+ from datetime import datetime, timedelta
5
+ import httpx
6
+ from rich.console import Console
7
+ from rich.progress import Progress, TaskID
8
+
9
+
10
+ class RateLimitError(Exception):
11
+ """Raised when API rate limit is exceeded."""
12
+ pass
13
+
14
+
15
+ class GitHubAPIClient:
16
+ def __init__(self, token: Optional[str] = None, console: Optional[Console] = None):
17
+ self.token = token
18
+ self.console = console or Console()
19
+ self.base_url = "https://api.github.com"
20
+ self.session: Optional[httpx.AsyncClient] = None
21
+
22
+ # Rate limiting
23
+ self.rate_limit_remaining = 5000
24
+ self.rate_limit_reset = datetime.now()
25
+ self.rate_limit_buffer = 100
26
+
27
+ async def __aenter__(self):
28
+ """Async context manager entry."""
29
+ self.session = httpx.AsyncClient(
30
+ timeout=30.0,
31
+ limits=httpx.Limits(max_keepalive_connections=10, max_connections=20)
32
+ )
33
+ return self
34
+
35
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
36
+ """Async context manager exit."""
37
+ if self.session:
38
+ await self.session.aclose()
39
+
40
+ def _get_headers(self) -> Dict[str, str]:
41
+ """Get request headers with authentication."""
42
+ headers = {
43
+ "Accept": "application/vnd.github.v3+json",
44
+ "User-Agent": "github-issue-exporter/1.0.0"
45
+ }
46
+
47
+ if self.token:
48
+ headers["Authorization"] = f"token {self.token}"
49
+
50
+ return headers
51
+
52
+ async def _handle_rate_limit(self, response: httpx.Response):
53
+ """Handle rate limiting from response headers."""
54
+ if "X-RateLimit-Remaining" in response.headers:
55
+ self.rate_limit_remaining = int(response.headers["X-RateLimit-Remaining"])
56
+
57
+ if "X-RateLimit-Reset" in response.headers:
58
+ reset_timestamp = int(response.headers["X-RateLimit-Reset"])
59
+ self.rate_limit_reset = datetime.fromtimestamp(reset_timestamp)
60
+
61
+ # If we're hitting rate limits, wait
62
+ if response.status_code == 403 and "rate limit" in response.text.lower():
63
+ wait_time = (self.rate_limit_reset - datetime.now()).total_seconds()
64
+ if wait_time > 0:
65
+ self.console.print(f"[yellow]Rate limit exceeded. Waiting {wait_time:.0f} seconds...[/yellow]")
66
+ await asyncio.sleep(wait_time + 1)
67
+ raise RateLimitError("Rate limit exceeded")
68
+
69
+ async def _check_rate_limit_preemptive(self):
70
+ """Check if we should wait before making a request."""
71
+ if self.rate_limit_remaining < self.rate_limit_buffer:
72
+ wait_time = (self.rate_limit_reset - datetime.now()).total_seconds()
73
+ if wait_time > 0:
74
+ self.console.print(f"[yellow]Approaching rate limit. Waiting {wait_time:.0f} seconds...[/yellow]")
75
+ await asyncio.sleep(wait_time + 1)
76
+
77
+ async def _make_request(self, method: str, url: str, **kwargs) -> httpx.Response:
78
+ """Make HTTP request with retry logic and rate limiting."""
79
+ if not self.session:
80
+ raise RuntimeError("Client not initialized. Use async context manager.")
81
+
82
+ full_url = url if url.startswith("http") else f"{self.base_url}{url}"
83
+ headers = self._get_headers()
84
+
85
+ max_retries = 3
86
+ for attempt in range(max_retries):
87
+ try:
88
+ await self._check_rate_limit_preemptive()
89
+
90
+ response = await self.session.request(
91
+ method, full_url, headers=headers, **kwargs
92
+ )
93
+
94
+ await self._handle_rate_limit(response)
95
+
96
+ if response.status_code == 200:
97
+ return response
98
+ elif response.status_code == 403 and "rate limit" in response.text.lower():
99
+ # Rate limit handled in _handle_rate_limit
100
+ continue
101
+ elif response.status_code >= 500:
102
+ # Server error - retry with exponential backoff
103
+ if attempt < max_retries - 1:
104
+ wait_time = 2 ** attempt
105
+ await asyncio.sleep(wait_time)
106
+ continue
107
+
108
+ # Other errors - don't retry
109
+ response.raise_for_status()
110
+ return response
111
+
112
+ except RateLimitError:
113
+ # Rate limit handled, retry
114
+ continue
115
+ except httpx.RequestError as e:
116
+ if attempt < max_retries - 1:
117
+ wait_time = 2 ** attempt
118
+ await asyncio.sleep(wait_time)
119
+ continue
120
+ raise e
121
+
122
+ raise Exception(f"Failed to make request after {max_retries} attempts")
123
+
124
+ async def get_repository_info(self, repo_full_name: str) -> Dict[str, Any]:
125
+ """Get repository information."""
126
+ response = await self._make_request("GET", f"/repos/{repo_full_name}")
127
+ return response.json()
128
+
129
+ async def get_issues_count_estimate(self, repo_full_name: str, state: str = "all") -> Dict[str, int]:
130
+ """Get an estimate of issue counts by checking repository info and first page."""
131
+ repo_info = await self.get_repository_info(repo_full_name)
132
+
133
+ # Repository info gives us total open issues count
134
+ open_issues_count = repo_info.get("open_issues_count", 0)
135
+
136
+ # Get first page to see total from pagination
137
+ first_page = await self.get_issues_page(repo_full_name, 1, state=state)
138
+ total_pages = first_page["total_pages"]
139
+ items_on_first_page = len(first_page["issues"])
140
+
141
+ # Estimate total items (this includes pull requests)
142
+ if total_pages > 1:
143
+ estimated_total = (total_pages - 1) * 100 + items_on_first_page
144
+ else:
145
+ estimated_total = items_on_first_page
146
+
147
+ return {
148
+ "open_issues_from_repo": open_issues_count,
149
+ "estimated_total_from_pagination": estimated_total,
150
+ "total_pages": total_pages,
151
+ "items_on_first_page": items_on_first_page
152
+ }
153
+
154
+ async def get_issues_page(self, repo_full_name: str, page: int = 1, per_page: int = 100,
155
+ state: str = "all") -> Dict[str, Any]:
156
+ """Get a single page of issues."""
157
+ # GitHub API limits per_page to 100 max
158
+ per_page = min(per_page, 100)
159
+
160
+ params = {
161
+ "page": page,
162
+ "per_page": per_page,
163
+ "state": state,
164
+ "sort": "created", # Changed from "updated" to "created" for more consistent pagination
165
+ "direction": "asc" # Ascending to get oldest first, more predictable
166
+ }
167
+
168
+ response = await self._make_request(
169
+ "GET", f"/repos/{repo_full_name}/issues", params=params
170
+ )
171
+
172
+ return {
173
+ "issues": response.json(),
174
+ "total_pages": self._get_total_pages(response),
175
+ "current_page": page
176
+ }
177
+
178
+ def _get_total_pages(self, response: httpx.Response) -> int:
179
+ """Extract total pages from Link header."""
180
+ link_header = response.headers.get("Link", "")
181
+ if not link_header:
182
+ return 1
183
+
184
+ # Parse Link header to find last page
185
+ import re
186
+ for link in link_header.split(","):
187
+ link = link.strip()
188
+ if 'rel="last"' in link:
189
+ # Extract page number from URL - more robust regex
190
+ match = re.search(r'[?&]page=(\d+)', link)
191
+ if match:
192
+ return int(match.group(1))
193
+
194
+ # If no "last" link found, check if there's a "next" link
195
+ # If there's no "next" link, we're on the last page
196
+ for link in link_header.split(","):
197
+ link = link.strip()
198
+ if 'rel="next"' in link:
199
+ # There are more pages, but we don't know how many
200
+ # We'll use a different approach
201
+ return -1 # Signal that we need to paginate manually
202
+
203
+ return 1
204
+
205
+ async def get_all_issues(self, repo_full_name: str, state: str = "all") -> List[Dict[str, Any]]:
206
+ """Get all issues for a repository with pagination."""
207
+ all_issues = []
208
+ page = 1
209
+
210
+ # Get first page to determine total pages
211
+ first_page = await self.get_issues_page(repo_full_name, page, state=state)
212
+ all_issues.extend(first_page["issues"])
213
+ total_pages = first_page["total_pages"]
214
+
215
+ if total_pages == -1:
216
+ # Manual pagination - keep fetching until we get an empty page or less than per_page items
217
+ page = 2
218
+ while True:
219
+ page_result = await self.get_issues_page(repo_full_name, page, state=state)
220
+ issues = page_result["issues"]
221
+
222
+ if not issues or len(issues) == 0:
223
+ break
224
+
225
+ all_issues.extend(issues)
226
+
227
+ # If we got less than per_page items, we're on the last page
228
+ if len(issues) < 100: # per_page default is 100
229
+ break
230
+
231
+ page += 1
232
+ elif total_pages > 1:
233
+ # We know the total pages, fetch them concurrently
234
+ tasks = []
235
+ for page in range(2, total_pages + 1):
236
+ tasks.append(self.get_issues_page(repo_full_name, page, state=state))
237
+
238
+ # Process pages with limited concurrency
239
+ semaphore = asyncio.Semaphore(5) # Limit concurrent requests
240
+
241
+ async def fetch_page(page_task):
242
+ async with semaphore:
243
+ return await page_task
244
+
245
+ page_results = await asyncio.gather(*[fetch_page(task) for task in tasks])
246
+
247
+ for page_result in page_results:
248
+ all_issues.extend(page_result["issues"])
249
+
250
+ # Filter out pull requests (they appear in issues API)
251
+ issues_only = [issue for issue in all_issues if "pull_request" not in issue]
252
+
253
+ # Debug info - can be removed later
254
+ if self.console:
255
+ total_fetched = len(all_issues)
256
+ total_after_filter = len(issues_only)
257
+ pull_requests_filtered = total_fetched - total_after_filter
258
+
259
+ if pull_requests_filtered > 0:
260
+ self.console.print(f"[dim]Fetched {total_fetched} items, filtered out {pull_requests_filtered} pull requests, {total_after_filter} issues remaining[/dim]")
261
+ else:
262
+ self.console.print(f"[dim]Fetched {total_after_filter} issues total[/dim]")
263
+
264
+ return issues_only
265
+
266
+ async def get_issue_comments(self, repo_full_name: str, issue_number: int) -> List[Dict[str, Any]]:
267
+ """Get all comments for a specific issue."""
268
+ all_comments = []
269
+ page = 1
270
+ per_page = 100
271
+
272
+ while True:
273
+ params = {
274
+ "page": page,
275
+ "per_page": per_page
276
+ }
277
+
278
+ response = await self._make_request(
279
+ "GET", f"/repos/{repo_full_name}/issues/{issue_number}/comments",
280
+ params=params
281
+ )
282
+
283
+ comments = response.json()
284
+ if not comments:
285
+ break
286
+
287
+ all_comments.extend(comments)
288
+
289
+ if len(comments) < per_page:
290
+ break
291
+
292
+ page += 1
293
+
294
+ return all_comments
295
+
296
+ async def get_issue_with_comments(self, repo_full_name: str, issue: Dict[str, Any]) -> Dict[str, Any]:
297
+ """Get issue details with comments."""
298
+ issue_number = issue["number"]
299
+
300
+ # Get comments if the issue has any
301
+ comments = []
302
+ if issue.get("comments", 0) > 0:
303
+ comments = await self.get_issue_comments(repo_full_name, issue_number)
304
+
305
+ return {
306
+ "issue": issue,
307
+ "comments": comments
308
+ }
309
+
310
+ async def fetch_issues_with_comments(self, repo_full_name: str, issues: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
311
+ """Fetch all issues with their comments concurrently."""
312
+ semaphore = asyncio.Semaphore(10) # Limit concurrent requests
313
+
314
+ async def fetch_issue_with_comments(issue):
315
+ async with semaphore:
316
+ return await self.get_issue_with_comments(repo_full_name, issue)
317
+
318
+ tasks = [fetch_issue_with_comments(issue) for issue in issues]
319
+ results = await asyncio.gather(*tasks)
320
+
321
+ return results
322
+
323
+ async def test_authentication(self) -> Dict[str, Any]:
324
+ """Test if authentication is working."""
325
+ response = await self._make_request("GET", "/user")
326
+ return response.json()
327
+
328
+ def get_rate_limit_status(self) -> Dict[str, Any]:
329
+ """Get current rate limit status."""
330
+ return {
331
+ "remaining": self.rate_limit_remaining,
332
+ "reset_time": self.rate_limit_reset,
333
+ "seconds_until_reset": (self.rate_limit_reset - datetime.now()).total_seconds()
334
+ }