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,237 @@
1
+ import json
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Dict, Optional, Any
5
+ from cryptography.fernet import Fernet
6
+ from pydantic import BaseModel, Field
7
+ from datetime import datetime
8
+
9
+
10
+ class RepoSpecificAuth(BaseModel):
11
+ token: Optional[str] = None
12
+ username: Optional[str] = None
13
+ last_export: Optional[datetime] = None
14
+
15
+
16
+ class RepoSettings(BaseModel):
17
+ output_dir: Optional[str] = None
18
+ last_export: Optional[datetime] = None
19
+ include_closed: bool = True
20
+ export_comments: bool = True
21
+
22
+
23
+ class GlobalSettings(BaseModel):
24
+ default_output_dir: str = "./exports"
25
+ concurrent_repos: int = 3
26
+ api_rate_limit_buffer: int = 100
27
+
28
+
29
+ class AuthSettings(BaseModel):
30
+ global_token: Optional[str] = None
31
+ repo_specific: Dict[str, RepoSpecificAuth] = Field(default_factory=dict)
32
+
33
+
34
+ class Config(BaseModel):
35
+ global_settings: GlobalSettings = Field(default_factory=GlobalSettings)
36
+ authentication: AuthSettings = Field(default_factory=AuthSettings)
37
+ repositories: Dict[str, RepoSettings] = Field(default_factory=dict)
38
+
39
+
40
+ class ConfigManager:
41
+ def __init__(self):
42
+ self.config_dir = Path.home() / ".config" / "github-issue-exporter-tool"
43
+ self.config_file = self.config_dir / "config.json"
44
+ self.key_file = self.config_dir / "key.key"
45
+ self._ensure_config_dir()
46
+ self._cipher = self._get_or_create_cipher()
47
+ self._config: Optional[Config] = None
48
+
49
+ def _ensure_config_dir(self):
50
+ """Create config directory if it doesn't exist."""
51
+ self.config_dir.mkdir(parents=True, exist_ok=True)
52
+
53
+ # Set restrictive permissions on config directory
54
+ os.chmod(self.config_dir, 0o700)
55
+
56
+ def _get_or_create_cipher(self) -> Fernet:
57
+ """Get or create encryption cipher for credential storage."""
58
+ if self.key_file.exists():
59
+ with open(self.key_file, 'rb') as f:
60
+ key = f.read()
61
+ else:
62
+ key = Fernet.generate_key()
63
+ with open(self.key_file, 'wb') as f:
64
+ f.write(key)
65
+ # Set restrictive permissions on key file
66
+ os.chmod(self.key_file, 0o600)
67
+
68
+ return Fernet(key)
69
+
70
+ def _encrypt_value(self, value: str) -> str:
71
+ """Encrypt a string value."""
72
+ return self._cipher.encrypt(value.encode()).decode()
73
+
74
+ def _decrypt_value(self, encrypted_value: str) -> str:
75
+ """Decrypt a string value."""
76
+ return self._cipher.decrypt(encrypted_value.encode()).decode()
77
+
78
+ def _encrypt_config_data(self, config_dict: Dict[str, Any]) -> Dict[str, Any]:
79
+ """Encrypt sensitive data in config dictionary."""
80
+ encrypted = config_dict.copy()
81
+
82
+ # Encrypt global token
83
+ if encrypted.get("authentication", {}).get("global_token"):
84
+ encrypted["authentication"]["global_token"] = self._encrypt_value(
85
+ encrypted["authentication"]["global_token"]
86
+ )
87
+
88
+ # Encrypt repo-specific credentials
89
+ for repo_name, auth_data in encrypted.get("authentication", {}).get("repo_specific", {}).items():
90
+ if auth_data.get("token"):
91
+ encrypted["authentication"]["repo_specific"][repo_name]["token"] = self._encrypt_value(
92
+ auth_data["token"]
93
+ )
94
+ if auth_data.get("username"):
95
+ encrypted["authentication"]["repo_specific"][repo_name]["username"] = self._encrypt_value(
96
+ auth_data["username"]
97
+ )
98
+
99
+ return encrypted
100
+
101
+ def _decrypt_config_data(self, encrypted_dict: Dict[str, Any]) -> Dict[str, Any]:
102
+ """Decrypt sensitive data in config dictionary."""
103
+ decrypted = encrypted_dict.copy()
104
+
105
+ # Decrypt global token
106
+ if decrypted.get("authentication", {}).get("global_token"):
107
+ try:
108
+ decrypted["authentication"]["global_token"] = self._decrypt_value(
109
+ decrypted["authentication"]["global_token"]
110
+ )
111
+ except Exception:
112
+ # If decryption fails, clear the token
113
+ decrypted["authentication"]["global_token"] = None
114
+
115
+ # Decrypt repo-specific credentials
116
+ for repo_name, auth_data in decrypted.get("authentication", {}).get("repo_specific", {}).items():
117
+ if auth_data.get("token"):
118
+ try:
119
+ decrypted["authentication"]["repo_specific"][repo_name]["token"] = self._decrypt_value(
120
+ auth_data["token"]
121
+ )
122
+ except Exception:
123
+ decrypted["authentication"]["repo_specific"][repo_name]["token"] = None
124
+
125
+ if auth_data.get("username"):
126
+ try:
127
+ decrypted["authentication"]["repo_specific"][repo_name]["username"] = self._decrypt_value(
128
+ auth_data["username"]
129
+ )
130
+ except Exception:
131
+ decrypted["authentication"]["repo_specific"][repo_name]["username"] = None
132
+
133
+ return decrypted
134
+
135
+ def load_config(self) -> Config:
136
+ """Load configuration from file."""
137
+ if self._config is not None:
138
+ return self._config
139
+
140
+ if not self.config_file.exists():
141
+ self._config = Config()
142
+ return self._config
143
+
144
+ try:
145
+ with open(self.config_file, 'r') as f:
146
+ encrypted_data = json.load(f)
147
+
148
+ decrypted_data = self._decrypt_config_data(encrypted_data)
149
+ self._config = Config.model_validate(decrypted_data)
150
+ return self._config
151
+ except Exception as e:
152
+ # If config is corrupted, start fresh
153
+ self._config = Config()
154
+ return self._config
155
+
156
+ def save_config(self, config: Optional[Config] = None):
157
+ """Save configuration to file."""
158
+ if config is None:
159
+ config = self._config
160
+
161
+ if config is None:
162
+ return
163
+
164
+ config_dict = config.model_dump()
165
+ encrypted_data = self._encrypt_config_data(config_dict)
166
+
167
+ with open(self.config_file, 'w') as f:
168
+ json.dump(encrypted_data, f, indent=2, default=str)
169
+
170
+ # Set restrictive permissions on config file
171
+ os.chmod(self.config_file, 0o600)
172
+ self._config = config
173
+
174
+ def get_repo_token(self, repo_full_name: str) -> Optional[str]:
175
+ """Get authentication token for a specific repository."""
176
+ config = self.load_config()
177
+
178
+ # Check for repo-specific token first
179
+ repo_auth = config.authentication.repo_specific.get(repo_full_name)
180
+ if repo_auth and repo_auth.token:
181
+ return repo_auth.token
182
+
183
+ # Fall back to global token
184
+ return config.authentication.global_token
185
+
186
+ def set_repo_token(self, repo_full_name: str, token: str):
187
+ """Set authentication token for a specific repository."""
188
+ config = self.load_config()
189
+
190
+ if repo_full_name not in config.authentication.repo_specific:
191
+ config.authentication.repo_specific[repo_full_name] = RepoSpecificAuth()
192
+
193
+ config.authentication.repo_specific[repo_full_name].token = token
194
+ self.save_config(config)
195
+
196
+ def set_global_token(self, token: str):
197
+ """Set global authentication token."""
198
+ config = self.load_config()
199
+ config.authentication.global_token = token
200
+ self.save_config(config)
201
+
202
+ def get_repo_settings(self, repo_full_name: str) -> RepoSettings:
203
+ """Get settings for a specific repository."""
204
+ config = self.load_config()
205
+ return config.repositories.get(repo_full_name, RepoSettings())
206
+
207
+ def update_repo_settings(self, repo_full_name: str, settings: RepoSettings):
208
+ """Update settings for a specific repository."""
209
+ config = self.load_config()
210
+ config.repositories[repo_full_name] = settings
211
+ self.save_config(config)
212
+
213
+ def update_last_export(self, repo_full_name: str, export_time: datetime):
214
+ """Update last export time for a repository."""
215
+ config = self.load_config()
216
+
217
+ if repo_full_name not in config.repositories:
218
+ config.repositories[repo_full_name] = RepoSettings()
219
+
220
+ config.repositories[repo_full_name].last_export = export_time
221
+
222
+ # Also update in auth section if exists
223
+ if repo_full_name in config.authentication.repo_specific:
224
+ config.authentication.repo_specific[repo_full_name].last_export = export_time
225
+
226
+ self.save_config(config)
227
+
228
+ def get_global_settings(self) -> GlobalSettings:
229
+ """Get global settings."""
230
+ config = self.load_config()
231
+ return config.global_settings
232
+
233
+ def update_global_settings(self, settings: GlobalSettings):
234
+ """Update global settings."""
235
+ config = self.load_config()
236
+ config.global_settings = settings
237
+ self.save_config(config)
@@ -0,0 +1,344 @@
1
+ import asyncio
2
+ from typing import List, Dict, Any, Optional, Tuple
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ from rich.console import Console
6
+ from rich.progress import Progress, TaskID, SpinnerColumn, TextColumn, BarColumn, TimeRemainingColumn
7
+
8
+ from .config import ConfigManager
9
+ from .auth import AuthenticationHandler
10
+ from .filesystem import FileSystemManager
11
+ from .github_client import GitHubAPIClient
12
+ from .transformer import DataTransformer
13
+
14
+
15
+ class ExportResult:
16
+ def __init__(self, repo_full_name: str):
17
+ self.repo_full_name = repo_full_name
18
+ self.success = False
19
+ self.exported_count = 0
20
+ self.skipped_count = 0
21
+ self.error_count = 0
22
+ self.errors: List[str] = []
23
+ self.total_issues = 0
24
+ self.export_time: Optional[datetime] = None
25
+
26
+ def add_error(self, error: str):
27
+ self.errors.append(error)
28
+ self.error_count += 1
29
+
30
+ def mark_success(self, exported: int, skipped: int, total: int):
31
+ self.success = True
32
+ self.exported_count = exported
33
+ self.skipped_count = skipped
34
+ self.total_issues = total
35
+ self.export_time = datetime.now()
36
+
37
+
38
+ class ExportEngine:
39
+ def __init__(self, config_manager: ConfigManager, console: Console):
40
+ self.config_manager = config_manager
41
+ self.console = console
42
+ self.auth_handler = AuthenticationHandler(config_manager, console)
43
+ self.filesystem = FileSystemManager()
44
+ self.transformer = DataTransformer()
45
+
46
+ async def export_repository(self, repo_full_name: str, force: bool = False,
47
+ state: str = "all", include_comments: bool = True,
48
+ output_dir: Optional[str] = None, show_progress: bool = True) -> ExportResult:
49
+ """Export issues from a single repository."""
50
+ result = ExportResult(repo_full_name)
51
+
52
+ try:
53
+ # Get authentication token BEFORE starting any progress indicators
54
+ token = await self.auth_handler.ensure_authentication(repo_full_name)
55
+
56
+ # If authentication failed or was cancelled, return error
57
+ if token is False: # Explicitly cancelled or failed
58
+ result.add_error("Authentication failed or was cancelled")
59
+ return result
60
+
61
+ # Set up filesystem with custom output directory if specified
62
+ if output_dir:
63
+ self.filesystem = FileSystemManager(output_dir)
64
+
65
+ async with GitHubAPIClient(token, self.console) as github_client:
66
+ # Get repository information
67
+ try:
68
+ repo_data = await github_client.get_repository_info(repo_full_name)
69
+ except Exception as e:
70
+ result.add_error(f"Failed to fetch repository info: {str(e)}")
71
+ return result
72
+
73
+ repo_owner = repo_data["owner"]["login"]
74
+ repo_name = repo_data["name"]
75
+
76
+ # Ensure output directory exists
77
+ self.filesystem.ensure_repo_directory(repo_owner, repo_name)
78
+
79
+ # Now that authentication is complete, show progress for actual work
80
+ if show_progress:
81
+ progress_mgr = Progress(
82
+ SpinnerColumn(),
83
+ TextColumn("[progress.description]{task.description}"),
84
+ BarColumn(),
85
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
86
+ TimeRemainingColumn(),
87
+ console=self.console
88
+ )
89
+ else:
90
+ from contextlib import nullcontext
91
+ progress_mgr = nullcontext()
92
+
93
+ with progress_mgr as progress:
94
+
95
+ # Get issue count estimate for debugging
96
+ try:
97
+ count_info = await github_client.get_issues_count_estimate(repo_full_name, state)
98
+ self.console.print(f"[dim]Repository reports {count_info['open_issues_from_repo']} open issues[/dim]")
99
+ self.console.print(f"[dim]Pagination estimates {count_info['estimated_total_from_pagination']} total items across {count_info['total_pages']} pages[/dim]")
100
+ except Exception:
101
+ pass # Don't fail the export if this fails
102
+
103
+ # Fetch all issues
104
+ if show_progress:
105
+ issues_task = progress.add_task(
106
+ f"[cyan]Fetching issues from {repo_full_name}...",
107
+ total=None
108
+ )
109
+
110
+ try:
111
+ issues = await github_client.get_all_issues(
112
+ repo_full_name, state=state
113
+ )
114
+ if show_progress:
115
+ progress.update(issues_task, completed=1)
116
+ except Exception as e:
117
+ result.add_error(f"Failed to fetch issues: {str(e)}")
118
+ return result
119
+
120
+ if not issues:
121
+ self.console.print(f"[yellow]No issues found in {repo_full_name}[/yellow]")
122
+ result.mark_success(0, 0, 0)
123
+ return result
124
+
125
+ result.total_issues = len(issues)
126
+
127
+ # Filter issues that need updating
128
+ issues_to_process = []
129
+ for issue in issues:
130
+ issue_number = issue["number"]
131
+ existing_file = self.filesystem.find_existing_issue_file(
132
+ repo_owner, repo_name, issue_number
133
+ )
134
+
135
+ if force or not existing_file:
136
+ issues_to_process.append(issue)
137
+ else:
138
+ # Check if file needs update
139
+ issue_updated = self.transformer.get_issue_updated_datetime(issue)
140
+ if self.filesystem.needs_update(existing_file, issue_updated):
141
+ issues_to_process.append(issue)
142
+ else:
143
+ result.skipped_count += 1
144
+
145
+ if not issues_to_process:
146
+ self.console.print(f"[green]All issues in {repo_full_name} are up to date[/green]")
147
+ result.mark_success(0, result.skipped_count, result.total_issues)
148
+ return result
149
+
150
+ # Fetch issue details with comments
151
+ if show_progress:
152
+ details_task = progress.add_task(
153
+ f"[cyan]Fetching issue details and comments...",
154
+ total=len(issues_to_process)
155
+ )
156
+
157
+ try:
158
+ if include_comments:
159
+ issues_with_comments = await github_client.fetch_issues_with_comments(
160
+ repo_full_name, issues_to_process
161
+ )
162
+ if show_progress:
163
+ progress.update(details_task, completed=len(issues_to_process))
164
+ else:
165
+ # Create issue data without comments
166
+ issues_with_comments = [
167
+ {"issue": issue, "comments": []}
168
+ for issue in issues_to_process
169
+ ]
170
+ if show_progress:
171
+ progress.update(details_task, completed=len(issues_to_process))
172
+ except Exception as e:
173
+ result.add_error(f"Failed to fetch issue details: {str(e)}")
174
+ return result
175
+
176
+ # Process and save issues
177
+ if show_progress:
178
+ save_task = progress.add_task(
179
+ f"[cyan]Saving issues to files...",
180
+ total=len(issues_with_comments)
181
+ )
182
+
183
+ for issue_data in issues_with_comments:
184
+ try:
185
+ # Transform data
186
+ transformed_data = self.transformer.transform_issue(
187
+ repo_data, issue_data, issue_data["comments"]
188
+ )
189
+
190
+ # Write to file
191
+ file_path = self.filesystem.write_issue_file(
192
+ repo_owner, repo_name, transformed_data
193
+ )
194
+
195
+ result.exported_count += 1
196
+ if show_progress:
197
+ progress.update(save_task, advance=1)
198
+
199
+ except Exception as e:
200
+ result.add_error(f"Failed to save issue {issue_data['issue'].get('number', 'unknown')}: {str(e)}")
201
+ if show_progress:
202
+ progress.update(save_task, advance=1)
203
+
204
+ # Update last export time
205
+ self.config_manager.update_last_export(repo_full_name, datetime.now())
206
+
207
+ result.mark_success(result.exported_count, result.skipped_count, result.total_issues)
208
+
209
+ except Exception as e:
210
+ result.add_error(f"Unexpected error: {str(e)}")
211
+
212
+ return result
213
+
214
+ async def export_repositories(self, repo_names: List[str], force: bool = False,
215
+ state: str = "all", include_comments: bool = True,
216
+ output_dir: Optional[str] = None,
217
+ max_concurrent: int = 3) -> List[ExportResult]:
218
+ """Export issues from multiple repositories with limited concurrency."""
219
+
220
+ if output_dir:
221
+ self.filesystem = FileSystemManager(output_dir)
222
+
223
+ semaphore = asyncio.Semaphore(max_concurrent)
224
+
225
+ async def export_single_repo(repo_name: str) -> ExportResult:
226
+ async with semaphore:
227
+ return await self.export_repository(
228
+ repo_name, force=force, state=state,
229
+ include_comments=include_comments, output_dir=output_dir,
230
+ show_progress=False # Don't show individual progress when in batch mode
231
+ )
232
+
233
+ # Show overall progress
234
+ self.console.print(f"[bold blue]Starting export of {len(repo_names)} repositories...[/bold blue]")
235
+
236
+ # Create tasks for all repositories
237
+ tasks = [export_single_repo(repo_name) for repo_name in repo_names]
238
+
239
+ # Execute with progress tracking only when there are multiple repos
240
+ results = []
241
+ if len(repo_names) > 1:
242
+ with Progress(
243
+ SpinnerColumn(),
244
+ TextColumn("[progress.description]{task.description}"),
245
+ BarColumn(),
246
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
247
+ console=self.console
248
+ ) as progress:
249
+
250
+ overall_task = progress.add_task(
251
+ "[green]Overall progress...",
252
+ total=len(repo_names)
253
+ )
254
+
255
+ # Process repositories
256
+ for task in asyncio.as_completed(tasks):
257
+ result = await task
258
+ results.append(result)
259
+ progress.update(overall_task, advance=1)
260
+
261
+ # Show immediate feedback
262
+ if result.success:
263
+ self.console.print(
264
+ f"[green]✓[/green] {result.repo_full_name}: "
265
+ f"{result.exported_count} exported, {result.skipped_count} skipped"
266
+ )
267
+ else:
268
+ self.console.print(
269
+ f"[red]✗[/red] {result.repo_full_name}: "
270
+ f"{len(result.errors)} errors"
271
+ )
272
+ else:
273
+ # Single repository - just run it directly without overall progress
274
+ for task in asyncio.as_completed(tasks):
275
+ result = await task
276
+ results.append(result)
277
+
278
+ return results
279
+
280
+ def print_export_summary(self, results: List[ExportResult]):
281
+ """Print summary of export results."""
282
+ if not results:
283
+ return
284
+
285
+ successful_repos = [r for r in results if r.success]
286
+ failed_repos = [r for r in results if not r.success]
287
+
288
+ total_exported = sum(r.exported_count for r in successful_repos)
289
+ total_skipped = sum(r.skipped_count for r in successful_repos)
290
+ total_issues = sum(r.total_issues for r in successful_repos)
291
+
292
+ self.console.print("\n[bold blue]Export Summary[/bold blue]")
293
+ self.console.print("=" * 50)
294
+
295
+ if successful_repos:
296
+ self.console.print(f"[green]Successful repositories: {len(successful_repos)}[/green]")
297
+ self.console.print(f"[green]Total issues exported: {total_exported}[/green]")
298
+ self.console.print(f"[yellow]Total issues skipped: {total_skipped}[/yellow]")
299
+ self.console.print(f"[blue]Total issues processed: {total_issues}[/blue]")
300
+
301
+ if failed_repos:
302
+ self.console.print(f"\n[red]Failed repositories: {len(failed_repos)}[/red]")
303
+ for result in failed_repos:
304
+ self.console.print(f"[red] • {result.repo_full_name}[/red]")
305
+ for error in result.errors[:3]: # Show first 3 errors
306
+ self.console.print(f" - {error}")
307
+ if len(result.errors) > 3:
308
+ self.console.print(f" ... and {len(result.errors) - 3} more errors")
309
+
310
+ # Show file locations
311
+ if successful_repos:
312
+ output_dir = self.filesystem.base_output_dir
313
+ self.console.print(f"\n[blue]Files exported to: {output_dir.absolute()}[/blue]")
314
+
315
+ async def cleanup_deleted_issues(self, repo_full_name: str) -> int:
316
+ """Remove files for issues that no longer exist in the repository."""
317
+ try:
318
+ token = await self.auth_handler.ensure_authentication(repo_full_name)
319
+
320
+ async with GitHubAPIClient(token, self.console) as github_client:
321
+ # Get current issues
322
+ current_issues = await github_client.get_all_issues(repo_full_name, state="all")
323
+ current_issue_numbers = [issue["number"] for issue in current_issues]
324
+
325
+ # Get repository info for directory structure
326
+ repo_data = await github_client.get_repository_info(repo_full_name)
327
+ repo_owner = repo_data["owner"]["login"]
328
+ repo_name = repo_data["name"]
329
+
330
+ # Get existing files
331
+ existing_issues = self.filesystem.list_existing_issues(repo_owner, repo_name)
332
+ existing_issue_numbers = [issue["number"] for issue in existing_issues]
333
+
334
+ # Find deleted issues
335
+ deleted_issue_numbers = set(existing_issue_numbers) - set(current_issue_numbers)
336
+
337
+ # Remove files for deleted issues
338
+ self.filesystem.cleanup_old_files(repo_owner, repo_name, current_issue_numbers)
339
+
340
+ return len(deleted_issue_numbers)
341
+
342
+ except Exception as e:
343
+ self.console.print(f"[red]Error during cleanup: {str(e)}[/red]")
344
+ return 0