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,18 @@
1
+ """GitHub Issue Exporter Tool
2
+
3
+ A command-line tool that exports GitHub issues to individual JSON files,
4
+ with incremental updates and credential management. Supports multiple
5
+ repositories with per-repo configuration.
6
+ """
7
+
8
+ try:
9
+ from importlib.metadata import version
10
+ except ImportError:
11
+ # Python < 3.8 fallback
12
+ from importlib_metadata import version
13
+
14
+ try:
15
+ __version__ = version("github-issue-exporter")
16
+ except Exception:
17
+ # Fallback for development/editable installs where metadata might not be available
18
+ __version__ = "dev"
@@ -0,0 +1,6 @@
1
+ """Main entry point for the GitHub Issue Exporter."""
2
+
3
+ from .cli.main import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
File without changes
@@ -0,0 +1,311 @@
1
+ import asyncio
2
+ from pathlib import Path
3
+ from typing import List, Optional
4
+ import typer
5
+ from rich.console import Console
6
+ from rich.table import Table
7
+ from rich.prompt import Confirm
8
+
9
+ from ..core.config import ConfigManager
10
+ from ..core.export_engine import ExportEngine
11
+
12
+
13
+ def version_callback(value: bool):
14
+ """Show version and exit."""
15
+ if value:
16
+ from .. import __version__
17
+ console.print(f"GitHub Issue Exporter v{__version__}")
18
+ raise typer.Exit()
19
+
20
+
21
+ app = typer.Typer(
22
+ name="github-issue-exporter",
23
+ help="Export GitHub issues to individual JSON files with incremental updates.",
24
+ add_completion=False
25
+ )
26
+
27
+ console = Console()
28
+
29
+
30
+ @app.callback()
31
+ def main(
32
+ version: Optional[bool] = typer.Option(
33
+ None,
34
+ "--version",
35
+ callback=version_callback,
36
+ is_eager=True,
37
+ help="Show version and exit"
38
+ )
39
+ ):
40
+ """GitHub Issue Exporter - Export GitHub issues to individual JSON files."""
41
+ return
42
+
43
+
44
+ def parse_repo_list(repo_input: str) -> List[str]:
45
+ """Parse repository input which can be comma-separated or from a file."""
46
+ if Path(repo_input).exists():
47
+ # Read from file
48
+ with open(repo_input, 'r') as f:
49
+ repos = [line.strip() for line in f if line.strip() and not line.startswith('#')]
50
+ return repos
51
+ else:
52
+ # Parse comma-separated list
53
+ return [repo.strip() for repo in repo_input.split(',') if repo.strip()]
54
+
55
+
56
+ @app.command()
57
+ def export(
58
+ repositories: str = typer.Argument(
59
+ ...,
60
+ help="Repository names (owner/repo) separated by commas, or path to file containing repo list"
61
+ ),
62
+ output: Optional[str] = typer.Option(
63
+ None,
64
+ "--output", "-o",
65
+ help="Output directory for exported files (default: ./exports)"
66
+ ),
67
+ force: bool = typer.Option(
68
+ False,
69
+ "--force", "-f",
70
+ help="Force re-export of all issues, ignoring timestamps"
71
+ ),
72
+ state: str = typer.Option(
73
+ "all",
74
+ "--state", "-s",
75
+ help="Issue state to export: open, closed, or all"
76
+ ),
77
+ no_comments: bool = typer.Option(
78
+ False,
79
+ "--no-comments",
80
+ help="Skip exporting issue comments"
81
+ ),
82
+ concurrent: int = typer.Option(
83
+ 3,
84
+ "--concurrent", "-c",
85
+ help="Maximum number of repositories to process concurrently"
86
+ )
87
+ ):
88
+ """Export GitHub issues to JSON files."""
89
+
90
+ if state not in ["open", "closed", "all"]:
91
+ console.print("[red]Error: --state must be one of: open, closed, all[/red]")
92
+ raise typer.Exit(1)
93
+
94
+ if concurrent < 1 or concurrent > 10:
95
+ console.print("[red]Error: --concurrent must be between 1 and 10[/red]")
96
+ raise typer.Exit(1)
97
+
98
+ # Parse repository list
99
+ try:
100
+ repo_list = parse_repo_list(repositories)
101
+ except Exception as e:
102
+ console.print(f"[red]Error parsing repository list: {str(e)}[/red]")
103
+ raise typer.Exit(1)
104
+
105
+ if not repo_list:
106
+ console.print("[red]Error: No repositories specified[/red]")
107
+ raise typer.Exit(1)
108
+
109
+ # Validate repository format
110
+ invalid_repos = []
111
+ for repo in repo_list:
112
+ if '/' not in repo or repo.count('/') != 1:
113
+ invalid_repos.append(repo)
114
+
115
+ if invalid_repos:
116
+ console.print("[red]Error: Invalid repository format. Use 'owner/repo' format.[/red]")
117
+ for repo in invalid_repos:
118
+ console.print(f" Invalid: {repo}")
119
+ raise typer.Exit(1)
120
+
121
+ # Show what will be exported
122
+ console.print(f"[blue]Repositories to export ({len(repo_list)}):[/blue]")
123
+ for repo in repo_list:
124
+ console.print(f" • {repo}")
125
+
126
+ console.print(f"\n[blue]Settings:[/blue]")
127
+ console.print(f" Output directory: {output or './exports'}")
128
+ console.print(f" Issue state: {state}")
129
+ console.print(f" Include comments: {not no_comments}")
130
+ console.print(f" Force re-export: {force}")
131
+ console.print(f" Concurrent repositories: {concurrent}")
132
+
133
+ # Confirm if more than 5 repositories
134
+ if len(repo_list) > 5:
135
+ if not Confirm.ask(f"\nProceed with export of {len(repo_list)} repositories?"):
136
+ console.print("[yellow]Export cancelled.[/yellow]")
137
+ raise typer.Exit(0)
138
+
139
+ # Run export
140
+ async def run_export():
141
+ config_manager = ConfigManager()
142
+ export_engine = ExportEngine(config_manager, console)
143
+
144
+ if len(repo_list) == 1:
145
+ # Single repository - use direct export with progress
146
+ result = await export_engine.export_repository(
147
+ repo_list[0],
148
+ force=force,
149
+ state=state,
150
+ include_comments=not no_comments,
151
+ output_dir=output,
152
+ show_progress=True
153
+ )
154
+ results = [result]
155
+ else:
156
+ # Multiple repositories - use batch export
157
+ results = await export_engine.export_repositories(
158
+ repo_list,
159
+ force=force,
160
+ state=state,
161
+ include_comments=not no_comments,
162
+ output_dir=output,
163
+ max_concurrent=concurrent
164
+ )
165
+
166
+ export_engine.print_export_summary(results)
167
+
168
+ # Return exit code based on results
169
+ failed_count = sum(1 for r in results if not r.success)
170
+ return 1 if failed_count > 0 else 0
171
+
172
+ try:
173
+ exit_code = asyncio.run(run_export())
174
+ raise typer.Exit(exit_code)
175
+ except KeyboardInterrupt:
176
+ console.print("\n[yellow]Export cancelled by user.[/yellow]")
177
+ raise typer.Exit(130)
178
+ except Exception as e:
179
+ console.print(f"[red]Unexpected error: {str(e)}[/red]")
180
+ raise typer.Exit(1)
181
+
182
+
183
+ @app.command()
184
+ def cleanup(
185
+ repository: str = typer.Argument(
186
+ ...,
187
+ help="Repository name (owner/repo) to clean up"
188
+ ),
189
+ output: Optional[str] = typer.Option(
190
+ None,
191
+ "--output", "-o",
192
+ help="Output directory where files are stored (default: ./exports)"
193
+ ),
194
+ dry_run: bool = typer.Option(
195
+ False,
196
+ "--dry-run",
197
+ help="Show what would be deleted without actually deleting"
198
+ )
199
+ ):
200
+ """Remove files for issues that no longer exist in the repository."""
201
+
202
+ if '/' not in repository or repository.count('/') != 1:
203
+ console.print("[red]Error: Invalid repository format. Use 'owner/repo' format.[/red]")
204
+ raise typer.Exit(1)
205
+
206
+ async def run_cleanup():
207
+ config_manager = ConfigManager()
208
+ export_engine = ExportEngine(config_manager, console)
209
+
210
+ if output:
211
+ export_engine.filesystem = export_engine.filesystem.__class__(output)
212
+
213
+ if dry_run:
214
+ console.print(f"[yellow]DRY RUN: Would clean up deleted issues from {repository}[/yellow]")
215
+ # TODO: Implement dry run logic
216
+ return 0
217
+
218
+ try:
219
+ deleted_count = await export_engine.cleanup_deleted_issues(repository)
220
+ if deleted_count > 0:
221
+ console.print(f"[green]Cleaned up {deleted_count} deleted issues from {repository}[/green]")
222
+ else:
223
+ console.print(f"[blue]No deleted issues found in {repository}[/blue]")
224
+ return 0
225
+ except Exception as e:
226
+ console.print(f"[red]Error during cleanup: {str(e)}[/red]")
227
+ return 1
228
+
229
+ try:
230
+ exit_code = asyncio.run(run_cleanup())
231
+ raise typer.Exit(exit_code)
232
+ except KeyboardInterrupt:
233
+ console.print("\n[yellow]Cleanup cancelled by user.[/yellow]")
234
+ raise typer.Exit(130)
235
+
236
+
237
+ @app.command()
238
+ def config(
239
+ show: bool = typer.Option(
240
+ False,
241
+ "--show",
242
+ help="Show current configuration"
243
+ ),
244
+ clear_auth: Optional[str] = typer.Option(
245
+ None,
246
+ "--clear-auth",
247
+ help="Clear stored authentication for repository (or 'global' for global token)"
248
+ ),
249
+ set_output: Optional[str] = typer.Option(
250
+ None,
251
+ "--set-output",
252
+ help="Set default output directory"
253
+ )
254
+ ):
255
+ """Manage configuration and stored credentials."""
256
+
257
+ config_manager = ConfigManager()
258
+
259
+ if show:
260
+ config_data = config_manager.load_config()
261
+
262
+ table = Table(title="GitHub Issue Exporter Configuration")
263
+ table.add_column("Setting", style="cyan")
264
+ table.add_column("Value", style="white")
265
+
266
+ # Global settings
267
+ table.add_row("Default Output Directory", config_data.global_settings.default_output_dir)
268
+ table.add_row("Concurrent Repositories", str(config_data.global_settings.concurrent_repos))
269
+ table.add_row("API Rate Limit Buffer", str(config_data.global_settings.api_rate_limit_buffer))
270
+
271
+ # Authentication info (without showing tokens)
272
+ has_global_token = bool(config_data.authentication.global_token)
273
+ table.add_row("Global Token Set", "Yes" if has_global_token else "No")
274
+
275
+ repo_count = len(config_data.authentication.repo_specific)
276
+ table.add_row("Repository-specific Tokens", str(repo_count))
277
+
278
+ console.print(table)
279
+
280
+ if config_data.repositories:
281
+ console.print("\n[blue]Repository Settings:[/blue]")
282
+ for repo_name, settings in config_data.repositories.items():
283
+ console.print(f" • {repo_name}")
284
+ if settings.output_dir:
285
+ console.print(f" Output: {settings.output_dir}")
286
+ if settings.last_export:
287
+ console.print(f" Last export: {settings.last_export}")
288
+
289
+ elif clear_auth:
290
+ from ..core.auth import AuthenticationHandler
291
+
292
+ auth_handler = AuthenticationHandler(config_manager, console)
293
+
294
+ if clear_auth == "global":
295
+ auth_handler.clear_stored_credentials()
296
+ else:
297
+ auth_handler.clear_stored_credentials(clear_auth)
298
+
299
+ elif set_output:
300
+ config_data = config_manager.load_config()
301
+ config_data.global_settings.default_output_dir = set_output
302
+ config_manager.save_config(config_data)
303
+ console.print(f"[green]Default output directory set to: {set_output}[/green]")
304
+
305
+ else:
306
+ console.print("[yellow]Use --show to view configuration, or other options to modify it.[/yellow]")
307
+ console.print("Run 'github-issue-exporter config --help' for available options.")
308
+
309
+
310
+ if __name__ == "__main__":
311
+ app()
File without changes
@@ -0,0 +1,186 @@
1
+ import asyncio
2
+ from typing import Optional, Tuple
3
+ import httpx
4
+ from rich.console import Console
5
+ from rich.prompt import Prompt
6
+ from .config import ConfigManager
7
+
8
+
9
+ class AuthenticationHandler:
10
+ def __init__(self, config_manager: ConfigManager, console: Console):
11
+ self.config_manager = config_manager
12
+ self.console = console
13
+
14
+ async def is_repo_private(self, repo_full_name: str) -> bool:
15
+ """Check if a repository is private by making an unauthenticated API call."""
16
+ async with httpx.AsyncClient() as client:
17
+ try:
18
+ response = await client.get(
19
+ f"https://api.github.com/repos/{repo_full_name}",
20
+ headers={"Accept": "application/vnd.github.v3+json"}
21
+ )
22
+
23
+ if response.status_code == 200:
24
+ # Public repo - we can access it without auth
25
+ return False
26
+ elif response.status_code == 404:
27
+ # Could be private or doesn't exist
28
+ # We'll need auth to determine which
29
+ return True
30
+ else:
31
+ # Other error - assume we need auth
32
+ return True
33
+ except Exception:
34
+ # Network error - assume we need auth to be safe
35
+ return True
36
+
37
+ async def validate_credentials(self, token: str, repo_full_name: Optional[str] = None) -> Tuple[bool, Optional[str]]:
38
+ """Validate GitHub credentials and optionally check repo access."""
39
+ async with httpx.AsyncClient() as client:
40
+ headers = {
41
+ "Authorization": f"token {token}",
42
+ "Accept": "application/vnd.github.v3+json"
43
+ }
44
+
45
+ try:
46
+ # First, validate the token by checking user info
47
+ response = await client.get("https://api.github.com/user", headers=headers)
48
+
49
+ if response.status_code != 200:
50
+ return False, f"Invalid token: {response.status_code}"
51
+
52
+ user_data = response.json()
53
+ username = user_data.get("login", "unknown")
54
+
55
+ # If repo is specified, check access to it
56
+ if repo_full_name:
57
+ repo_response = await client.get(
58
+ f"https://api.github.com/repos/{repo_full_name}",
59
+ headers=headers
60
+ )
61
+
62
+ if repo_response.status_code == 404:
63
+ return False, f"Repository '{repo_full_name}' not found or no access"
64
+ elif repo_response.status_code != 200:
65
+ return False, f"Cannot access repository: {repo_response.status_code}"
66
+
67
+ return True, username
68
+
69
+ except Exception as e:
70
+ return False, f"Network error: {str(e)}"
71
+
72
+ def prompt_for_token(self, repo_full_name: Optional[str] = None) -> Optional[str]:
73
+ """Prompt user for GitHub token."""
74
+ if repo_full_name:
75
+ self.console.print(f"\n[yellow]Authentication required for repository: {repo_full_name}[/yellow]")
76
+ else:
77
+ self.console.print("\n[yellow]GitHub authentication required[/yellow]")
78
+
79
+ self.console.print("Please provide a GitHub Personal Access Token.")
80
+ self.console.print("You can create one at: https://github.com/settings/tokens")
81
+ self.console.print("Required scopes: 'repo' (for private repos) or 'public_repo' (for public repos)")
82
+
83
+ token = Prompt.ask("\nGitHub Token", password=True)
84
+
85
+ if not token or not token.strip():
86
+ return None
87
+
88
+ return token.strip()
89
+
90
+ async def get_or_prompt_credentials(self, repo_full_name: str) -> Optional[str]:
91
+ """Get existing credentials or prompt for new ones."""
92
+ # Check if we have stored credentials for this repo
93
+ stored_token = self.config_manager.get_repo_token(repo_full_name)
94
+
95
+ if stored_token:
96
+ # Validate stored credentials
97
+ is_valid, result = await self.validate_credentials(stored_token, repo_full_name)
98
+ if is_valid:
99
+ self.console.print(f"[green]Using stored credentials for {repo_full_name} (user: {result})[/green]")
100
+ return stored_token
101
+ else:
102
+ self.console.print(f"[red]Stored credentials for {repo_full_name} are invalid: {result}[/red]")
103
+
104
+ # Check if repo is public and we don't need auth
105
+ is_private = await self.is_repo_private(repo_full_name)
106
+ if not is_private:
107
+ self.console.print(f"[green]Repository {repo_full_name} is public - no authentication required[/green]")
108
+ return None
109
+
110
+ # Need to prompt for credentials
111
+ self.console.print(f"[yellow]Repository {repo_full_name} is private or authentication is required[/yellow]")
112
+
113
+ # Give user up to 3 attempts
114
+ for attempt in range(3):
115
+ token = self.prompt_for_token(repo_full_name)
116
+ if not token:
117
+ self.console.print("[red]Authentication cancelled by user[/red]")
118
+ return False # Explicitly cancelled
119
+
120
+ # Validate the new token
121
+ is_valid, result = await self.validate_credentials(token, repo_full_name)
122
+ if is_valid:
123
+ self.console.print(f"[green]Successfully authenticated as {result}[/green]")
124
+
125
+ # Ask if user wants to store the token
126
+ store_token = Prompt.ask(
127
+ f"Store token for {repo_full_name}? (y/n)",
128
+ choices=["y", "n"],
129
+ default="y"
130
+ )
131
+
132
+ if store_token.lower() == "y":
133
+ self.config_manager.set_repo_token(repo_full_name, token)
134
+ self.console.print("[green]Token stored securely[/green]")
135
+
136
+ return token
137
+ else:
138
+ self.console.print(f"[red]Invalid credentials: {result}[/red]")
139
+ if attempt < 2: # Don't show this on the last attempt
140
+ self.console.print(f"[yellow]Please try again. ({attempt + 1}/3 attempts)[/yellow]")
141
+
142
+ self.console.print("[red]Authentication failed after 3 attempts[/red]")
143
+ return False # Failed after attempts
144
+
145
+ async def ensure_authentication(self, repo_full_name: str):
146
+ """Ensure we have valid authentication for a repository."""
147
+ try:
148
+ return await self.get_or_prompt_credentials(repo_full_name)
149
+ except KeyboardInterrupt:
150
+ self.console.print("\n[red]Authentication cancelled by user[/red]")
151
+ return False
152
+ except Exception as e:
153
+ if str(e).strip():
154
+ self.console.print(f"[red]Authentication error: {str(e)}[/red]")
155
+ else:
156
+ self.console.print("[red]Authentication failed[/red]")
157
+ return False
158
+
159
+ def clear_stored_credentials(self, repo_full_name: Optional[str] = None):
160
+ """Clear stored credentials for a repo or globally."""
161
+ config = self.config_manager.load_config()
162
+
163
+ if repo_full_name:
164
+ if repo_full_name in config.authentication.repo_specific:
165
+ del config.authentication.repo_specific[repo_full_name]
166
+ self.config_manager.save_config(config)
167
+ self.console.print(f"[green]Cleared stored credentials for {repo_full_name}[/green]")
168
+ else:
169
+ self.console.print(f"[yellow]No stored credentials found for {repo_full_name}[/yellow]")
170
+ else:
171
+ # Clear global token
172
+ config.authentication.global_token = None
173
+ self.config_manager.save_config(config)
174
+ self.console.print("[green]Cleared global authentication token[/green]")
175
+
176
+ def get_auth_headers(self, token: Optional[str]) -> dict:
177
+ """Get authentication headers for API requests."""
178
+ headers = {
179
+ "Accept": "application/vnd.github.v3+json",
180
+ "User-Agent": "github-issue-exporter/1.0.0"
181
+ }
182
+
183
+ if token:
184
+ headers["Authorization"] = f"token {token}"
185
+
186
+ return headers