Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1466 lines (1205 loc) · 54.8 KB
/
Copy pathmain.py
File metadata and controls
1466 lines (1205 loc) · 54.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main entry point for GitHub Analyzer CLI.
This module provides the main() entry point and the GitHubAnalyzer
orchestrator class that coordinates the analysis workflow.
Supports multiple data sources:
- GitHub: Repository analysis with commits, PRs, issues
- Jira: Issue tracking with comments and metadata
Security features (Feature 006):
- File permission checks on sensitive files (FR-007)
- Verbose mode for API audit logging (FR-009)
"""
from __future__ import annotations
import argparse
import logging
import os
import re
import sys
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Callable
from src.github_analyzer.analyzers import (
CommitAnalyzer,
ContributorTracker,
IssueAnalyzer,
PullRequestAnalyzer,
calculate_quality_metrics,
)
from src.github_analyzer.api import GitHubClient, RepositoryStats
from src.github_analyzer.cli.output import TerminalOutput
from src.github_analyzer.config import AnalyzerConfig, Repository
from src.github_analyzer.config.settings import DataSource, JiraConfig
from src.github_analyzer.config.validation import load_jira_projects
from src.github_analyzer.core.exceptions import (
ConfigurationError,
GitHubAnalyzerError,
RateLimitError,
)
from src.github_analyzer.core.security import check_file_permissions
from src.github_analyzer.exporters import CSVExporter, JiraExporter
# Module logger for security warnings
_logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from src.github_analyzer.api.jira_client import JiraProject
from src.github_analyzer.api.models import Commit, Issue, PullRequest, QualityMetrics
class GitHubAnalyzer:
"""Main analyzer orchestrator.
Coordinates the full analysis workflow:
1. Load configuration and repositories
2. Fetch data from GitHub API
3. Analyze commits, PRs, issues
4. Calculate metrics
5. Export to CSV
"""
def __init__(self, config: AnalyzerConfig, fetch_pr_details: bool = False) -> None:
"""Initialize analyzer with configuration.
Args:
config: Analyzer configuration.
fetch_pr_details: If True, fetch full PR details (slower).
"""
self._config = config
self._output = TerminalOutput(verbose=config.verbose)
self._client = GitHubClient(config)
self._exporter = CSVExporter(config.output_dir)
# Initialize analyzers
self._commit_analyzer = CommitAnalyzer(self._client)
self._pr_analyzer = PullRequestAnalyzer(self._client, fetch_details=fetch_pr_details)
self._issue_analyzer = IssueAnalyzer(self._client)
self._contributor_tracker = ContributorTracker()
# Storage for results
self._all_commits: list[Commit] = []
self._all_prs: list[PullRequest] = []
self._all_issues: list[Issue] = []
self._repo_stats: list[RepositoryStats] = []
self._quality_metrics: list[QualityMetrics] = []
def run(self, repositories: list[Repository]) -> None:
"""Run full analysis on all repositories.
Args:
repositories: List of validated repositories to analyze.
"""
since = datetime.now(timezone.utc) - timedelta(days=self._config.days)
self._output.log(f"Starting analysis for {len(repositories)} repositories")
self._output.log(f"Analysis period: {self._config.days} days (since {since.date()})")
# Analyze each repository
for idx, repo in enumerate(repositories, 1):
self._output.progress(idx, len(repositories), f"Analyzing {repo.full_name}")
try:
self._analyze_repository(repo, since)
except RateLimitError as e:
self._output.error("Rate limit exceeded", e.details)
break
except GitHubAnalyzerError as e:
self._output.log(f"Error analyzing {repo.full_name}: {e.message}", "warning")
continue
# Track contributors from collected data
self._track_contributors()
# Generate productivity analysis
productivity = self._contributor_tracker.generate_analysis(self._config.days)
# Export all data
files = self._export_all(productivity)
# Show summary
self._show_summary(files)
def _analyze_repository(self, repo: Repository, since: datetime) -> None:
"""Analyze a single repository.
Args:
repo: Repository to analyze.
since: Start date for analysis.
"""
self._output.log(f"Fetching commits for {repo.full_name}", "info")
commits = self._commit_analyzer.fetch_and_analyze(repo, since)
self._all_commits.extend(commits)
self._output.log(f"Fetching pull requests for {repo.full_name}", "info")
prs = self._pr_analyzer.fetch_and_analyze(repo, since)
self._all_prs.extend(prs)
self._output.log(f"Fetching issues for {repo.full_name}", "info")
issues = self._issue_analyzer.fetch_and_analyze(repo, since)
self._all_issues.extend(issues)
# Calculate repository stats
commit_stats = self._commit_analyzer.get_stats(commits)
pr_stats = self._pr_analyzer.get_stats(prs)
issue_stats = self._issue_analyzer.get_stats(issues)
repo_stat = RepositoryStats(
repository=repo.full_name,
total_commits=commit_stats["total"],
merge_commits=commit_stats["merge_commits"],
revert_commits=commit_stats["revert_commits"],
total_additions=commit_stats["total_additions"],
total_deletions=commit_stats["total_deletions"],
unique_authors=commit_stats["unique_authors"],
total_prs=pr_stats["total"],
merged_prs=pr_stats["merged"],
open_prs=pr_stats["open"],
avg_time_to_merge_hours=pr_stats["avg_time_to_merge_hours"],
total_issues=issue_stats["total"],
closed_issues=issue_stats["closed"],
open_issues=issue_stats["open"],
bug_issues=issue_stats["bugs"],
analysis_period_days=self._config.days,
)
self._repo_stats.append(repo_stat)
# Calculate quality metrics
quality = calculate_quality_metrics(repo, commits, prs)
self._quality_metrics.append(quality)
self._output.log(
f"{repo.full_name}: {len(commits)} commits, {len(prs)} PRs, {len(issues)} issues",
"success",
)
def _track_contributors(self) -> None:
"""Track contributor statistics from all data."""
for commit in self._all_commits:
self._contributor_tracker.record_commit(commit)
for pr in self._all_prs:
self._contributor_tracker.record_pr(pr)
for issue in self._all_issues:
self._contributor_tracker.record_issue(issue)
def _export_all(self, productivity: list) -> list[Path]:
"""Export all data to CSV files.
Args:
productivity: Productivity analysis results.
Returns:
List of created file paths.
"""
self._output.log("Exporting data to CSV files", "info")
files = []
files.append(self._exporter.export_commits(self._all_commits))
files.append(self._exporter.export_pull_requests(self._all_prs))
files.append(self._exporter.export_issues(self._all_issues))
files.append(self._exporter.export_repository_summary(self._repo_stats))
files.append(self._exporter.export_quality_metrics(self._quality_metrics))
files.append(self._exporter.export_productivity(productivity))
files.append(self._exporter.export_contributors(self._contributor_tracker.get_stats()))
return files
def _show_summary(self, files: list[Path]) -> None:
"""Show analysis summary.
Args:
files: List of created file paths.
"""
commit_stats = self._commit_analyzer.get_stats(self._all_commits)
pr_stats = self._pr_analyzer.get_stats(self._all_prs)
issue_stats = self._issue_analyzer.get_stats(self._all_issues)
self._output.summary({
"repositories": len(self._repo_stats),
"commits": commit_stats,
"prs": pr_stats,
"issues": issue_stats,
"files": [str(f) for f in files],
})
self._output.success("Analysis complete!")
def close(self) -> None:
"""Clean up resources."""
self._client.close()
def parse_args() -> argparse.Namespace:
"""Parse command-line arguments.
Returns:
Parsed arguments namespace.
"""
parser = argparse.ArgumentParser(
description="Analyze GitHub repositories and Jira projects, export metrics to CSV.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python dev_analyzer.py --days 7
python dev_analyzer.py --sources github --days 14
python dev_analyzer.py --sources jira --days 30
python dev_analyzer.py --sources github,jira --output ./reports
""",
)
parser.add_argument(
"--sources", "-s",
type=str,
default="auto",
help="Data sources to analyze: auto, github, jira, or github,jira (default: auto)",
)
parser.add_argument(
"--days", "-d",
type=int,
default=None,
help="Number of days to analyze (default: 30, or GITHUB_ANALYZER_DAYS env var)",
)
parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Output directory for CSV files (default: github_export)",
)
parser.add_argument(
"--repos", "-r",
type=str,
default=None,
help="Path to repos.txt file (default: repos.txt)",
)
parser.add_argument(
"--jira-projects", "-j",
type=str,
default=None,
help="Path to jira_projects.txt file (default: jira_projects.txt)",
)
parser.add_argument(
"--quiet", "-q",
action="store_true",
help="Suppress verbose output",
)
parser.add_argument(
"--verbose", "-v",
action="store_true",
help="Enable verbose mode with API audit logging (Feature 006, FR-009)",
)
parser.add_argument(
"--full",
action="store_true",
help="Fetch full PR details (slower, includes additions/deletions per PR)",
)
return parser.parse_args()
def prompt_yes_no(question: str, default: bool = False) -> bool:
"""Prompt user for yes/no answer.
Args:
question: Question to ask.
default: Default value if user presses Enter.
Returns:
True for yes, False for no.
"""
default_hint = "[Y/n]" if default else "[y/N]"
try:
answer = input(f"{question} {default_hint}: ").strip().lower()
if not answer:
return default
return answer in ("y", "yes", "s", "si", "sì")
except (EOFError, KeyboardInterrupt):
print()
return default
def prompt_int(question: str, default: int) -> int:
"""Prompt user for integer value.
Args:
question: Question to ask.
default: Default value if user presses Enter.
Returns:
Integer value entered by user.
"""
try:
answer = input(f"{question} [{default}]: ").strip()
if not answer:
return default
return int(answer)
except ValueError:
print(f"Invalid number, using default: {default}")
return default
except (EOFError, KeyboardInterrupt):
print()
return default
def parse_sources_list(sources_str: str) -> list[DataSource]:
"""Parse sources string to list of DataSource.
Args:
sources_str: Comma-separated source names (e.g., "github,jira").
Returns:
List of DataSource values.
Raises:
ValueError: If unknown source name.
"""
sources = []
for name in sources_str.lower().split(","):
name = name.strip()
if name == "github":
sources.append(DataSource.GITHUB)
elif name == "jira":
sources.append(DataSource.JIRA)
elif name:
raise ValueError(f"Unknown source: {name}. Valid sources: github, jira")
return sources
def auto_detect_sources() -> list[DataSource]:
"""Auto-detect available data sources from environment.
Checks for credentials in environment variables:
- GitHub: GITHUB_TOKEN
- Jira: JIRA_URL, JIRA_EMAIL, JIRA_API_TOKEN
Returns:
List of DataSource values for which credentials are available.
"""
sources = []
# Check for GitHub token
if os.environ.get("GITHUB_TOKEN", "").strip():
sources.append(DataSource.GITHUB)
# Check for Jira credentials (all required)
jira_url = os.environ.get("JIRA_URL", "").strip()
jira_email = os.environ.get("JIRA_EMAIL", "").strip()
jira_token = os.environ.get("JIRA_API_TOKEN", "").strip()
if jira_url and jira_email and jira_token:
sources.append(DataSource.JIRA)
return sources
def validate_sources(sources: list[DataSource]) -> None:
"""Validate that required credentials exist for sources.
Args:
sources: List of data sources to validate.
Raises:
ValueError: If credentials are missing for a requested source.
"""
for source in sources:
if source == DataSource.GITHUB:
if not os.environ.get("GITHUB_TOKEN", "").strip():
raise ValueError(
"GitHub source requested but GITHUB_TOKEN environment variable not set"
)
elif source == DataSource.JIRA:
jira_url = os.environ.get("JIRA_URL", "").strip()
jira_email = os.environ.get("JIRA_EMAIL", "").strip()
jira_token = os.environ.get("JIRA_API_TOKEN", "").strip()
if not (jira_url and jira_email and jira_token):
raise ValueError(
"Jira source requested but Jira credentials incomplete. "
"Set JIRA_URL, JIRA_EMAIL, and JIRA_API_TOKEN environment variables."
)
# GitHub repository validation patterns (per spec Validation Patterns section)
REPO_FORMAT_PATTERN = re.compile(r"^[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$")
ORG_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$")
def validate_repo_format(repo: str) -> bool:
"""Validate repository name format (owner/repo).
Per spec FR-011 and Validation Patterns section:
- Pattern: ^[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$
- Valid: owner/repo, my-org/my-repo, user123/project_v2
Args:
repo: Repository string to validate.
Returns:
True if valid format, False otherwise.
"""
if not repo or not repo.strip():
return False
return bool(REPO_FORMAT_PATTERN.match(repo.strip()))
def validate_org_name(org: str) -> bool:
"""Validate organization name format.
Per spec Validation Patterns section:
- Pattern: ^[a-zA-Z0-9]([a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$
- Rules: 1-39 chars, alphanumeric and hyphens, cannot start/end with hyphen
- Double hyphens (--) are not allowed
Args:
org: Organization name to validate.
Returns:
True if valid format, False otherwise.
"""
if not org or not org.strip():
return False
org = org.strip()
if len(org) > 39:
return False
# Double hyphens not allowed
if "--" in org:
return False
# Single character is valid
if len(org) == 1:
return org.isalnum()
return bool(ORG_NAME_PATTERN.match(org))
# =============================================================================
# Feature 005: Smart Repository Filtering - Helper Functions
# =============================================================================
def get_cutoff_date(days: int) -> date:
"""Calculate activity cutoff date from number of days (Feature 005 - T007).
Per spec FR-002: Filtering logic uses cutoff_date = today - days.
Repos with pushed_at >= cutoff_date are considered active.
Args:
days: Number of days to look back from today.
Returns:
date object representing the cutoff date (inclusive boundary).
Example:
>>> get_cutoff_date(30) # If today is 2025-11-29
datetime.date(2025, 10, 30)
"""
return datetime.now(timezone.utc).date() - timedelta(days=days)
def filter_by_activity(repos: list[dict], cutoff: date) -> list[dict]:
"""Filter repositories by pushed_at date (Feature 005 - T008).
Per spec FR-002: Filters repos where pushed_at >= cutoff_date.
Uses client-side filtering for personal repos (Search API user:
qualifier only returns owned repos, missing collaborator access).
Args:
repos: List of repository dicts with 'pushed_at' field
(ISO 8601 format: "2025-11-28T10:00:00Z").
cutoff: Cutoff date - repos pushed on or after this date are active.
Returns:
List of active repositories (pushed_at >= cutoff).
Repos without pushed_at or with null value are excluded.
Example:
>>> repos = [{"full_name": "user/repo", "pushed_at": "2025-11-28T10:00:00Z"}]
>>> filter_by_activity(repos, date(2025, 11, 1))
[{"full_name": "user/repo", "pushed_at": "2025-11-28T10:00:00Z"}]
"""
active_repos = []
for repo in repos:
pushed_at_str = repo.get("pushed_at")
if not pushed_at_str:
# Skip repos without pushed_at (treat as inactive)
continue
try:
# Parse ISO 8601 timestamp (e.g., "2025-11-28T10:00:00Z")
pushed_at = datetime.fromisoformat(pushed_at_str.replace("Z", "+00:00"))
repo_date = pushed_at.date()
# Include if pushed_at >= cutoff (inclusive boundary per spec)
if repo_date >= cutoff:
active_repos.append(repo)
except (ValueError, AttributeError):
# Skip repos with invalid date format
continue
return active_repos
def display_activity_stats(total: int, active: int, days: int) -> None:
"""Display repository activity statistics (Feature 005 - T009).
Per spec FR-007: Display format is exactly:
"{total} repos found, {active} with activity in last {days} days"
Args:
total: Total number of repositories.
active: Number of active repositories (pushed in analysis period).
days: Number of days in the analysis period.
Example output:
135 repos found, 28 with activity in last 30 days
"""
print(f"{total} repos found, {active} with activity in last {days} days")
def format_repo_list(repos: list[dict]) -> str:
"""Format GitHub repositories for display.
Per spec Display Format section:
- N. owner/repo-name - Description (truncated to 50 chars)
- N. owner/private-repo - [private] Description here
Args:
repos: List of repository dictionaries with full_name, private, description.
Returns:
Formatted string for terminal display.
"""
lines = []
for idx, repo in enumerate(repos, 1):
full_name = repo.get("full_name", "unknown")
is_private = repo.get("private", False)
description = repo.get("description") or ""
# Truncate description to 50 chars
if len(description) > 50:
description = description[:47] + "..."
# Build display line
if is_private:
if description:
lines.append(f" {idx}. {full_name} - [private] {description}")
else:
lines.append(f" {idx}. {full_name} - [private]")
else:
if description:
lines.append(f" {idx}. {full_name} - {description}")
else:
lines.append(f" {idx}. {full_name}")
return "\n".join(lines)
def load_github_repos_from_file(repos_file: str) -> list[str]:
"""Load repository names from repos.txt file.
Args:
repos_file: Path to repos.txt file.
Returns:
List of repository names (owner/repo format), or empty if file missing/empty.
"""
try:
path = Path(repos_file)
if not path.exists():
return []
content = path.read_text().strip()
if not content:
return []
repos = []
for line in content.splitlines():
line = line.strip()
# Skip comments and empty lines
if not line or line.startswith("#"):
continue
# Handle full URLs
if line.startswith("http"):
# Extract owner/repo from URL
# https://github.com/owner/repo or https://github.com/owner/repo.git
parts = line.rstrip("/").rstrip(".git").split("/")
if len(parts) >= 2:
repos.append(f"{parts[-2]}/{parts[-1]}")
else:
repos.append(line)
return repos
except OSError:
return []
def _handle_rate_limit(e: RateLimitError, log: Callable[[str, str], None]) -> None:
"""Handle rate limit error with wait time display (FR-008, T049).
Per spec Edge Cases: Show wait time to user.
Args:
e: RateLimitError with reset_time.
log: Logging function.
"""
import time as time_module
if e.reset_time:
wait_seconds = max(0, e.reset_time - int(time_module.time()))
log(f"Rate limit exceeded. Waiting {wait_seconds} seconds...", "warning")
else:
log("Rate limit exceeded. Please try again later.", "warning")
def _handle_zero_active_repos(
repos: list[dict],
days: int,
total_count: int,
) -> tuple[list[dict] | None, int | None, bool]:
"""Handle zero active repositories scenario with options (FR-009).
Per spec Edge Case #1 and FR-009: When no repos have activity in the
analysis period, offer user three options:
[1] Include all repos - proceed with unfiltered repos
[2] Adjust timeframe - prompt for new days value and refilter
[3] Cancel - return to menu
Args:
repos: Full list of repositories (unfiltered).
days: Current timeframe in days.
total_count: Total number of repos for display.
Returns:
Tuple of (active_repos, new_days, should_exit):
- (repos, days, False): Use all repos with current days (option 1)
- (filtered_repos, new_days, False): Refiltered repos with new timeframe (option 2)
- (None, None, False): User cancelled (option 3) - return to menu
- (None, None, True): EOF/KeyboardInterrupt - exit completely
"""
print(f"⚠️ No repositories have been pushed to in the last {days} days.")
print("Options:")
print(f" [1] Include all {total_count} repositories anyway")
print(f" [2] Adjust timeframe (currently {days} days)")
print(" [3] Cancel")
try:
zero_choice = input("\nYour choice: ").strip()
except (EOFError, KeyboardInterrupt):
return None, None, True # Exit completely
if zero_choice == "1":
# Include all repos
return repos, days, False
elif zero_choice == "2":
# Adjust timeframe
try:
new_days_input = input("Enter new timeframe in days: ").strip()
new_days = int(new_days_input)
if new_days <= 0:
print("Invalid number of days. Must be positive.")
return None, None, False # Return to menu
except ValueError:
print("Invalid input. Please enter a number.")
return None, None, False # Return to menu
except (EOFError, KeyboardInterrupt):
return None, None, True # Exit completely
# Refilter with new timeframe
print("\nRechecking...")
new_cutoff = get_cutoff_date(new_days)
new_active = filter_by_activity(repos, new_cutoff)
display_activity_stats(total=total_count, active=len(new_active), days=new_days)
return new_active, new_days, False
else:
# Cancel (option 3 or any other input)
return None, None, False # Return to menu
def select_github_repos(
repos_file: str,
github_token: str,
interactive: bool = True,
output: TerminalOutput | None = None,
days: int = 30,
) -> list[str]:
"""Select GitHub repositories from file or interactively (Feature 004 + 005).
Per spec FR-001 to FR-014 (Feature 004) and Feature 005 Smart Filtering:
- Display interactive menu when repos.txt is missing or empty
- Options: [A] All personal, [S] Specify manually, [O] Organization,
[L] Select from list, [Q] Quit/Skip
- Apply activity filtering for [A], [L], [O] options (Feature 005)
- Display activity statistics per FR-007
- Confirmation prompt with [Y/n/all] per FR-006
Args:
repos_file: Path to repos.txt file.
github_token: GitHub API token for API calls.
interactive: If True, prompt user when file is missing/empty.
If False (--quiet mode), skip prompts per FR-013.
output: Optional TerminalOutput for consistent logging.
days: Analysis period in days for activity filtering (default 30).
Returns:
List of repository names (owner/repo format) to analyze.
"""
# Helper for consistent output
def log(msg: str, level: str = "info") -> None:
if output:
output.log(msg, level)
else:
print(msg)
# Try loading from file first (FR-001)
file_repos = load_github_repos_from_file(repos_file)
if file_repos:
return file_repos
# No file or empty - need to prompt or skip
if not interactive:
# FR-013, FR-014: Non-interactive mode skips prompts
log("No repos.txt found. Skipping GitHub analysis in non-interactive mode.", "info")
return []
# Display menu per FR-002
print("\nOptions:")
print(" [A] Analyze ALL accessible repositories")
print(" [S] Specify repository names manually (owner/repo format)")
print(" [O] Analyze organization repositories")
print(" [L] Select from list by number (e.g., 1,3,5 or 1-3)")
print(" [Q] Quit/Skip GitHub analysis")
# Create client for API calls - use provided token
config = AnalyzerConfig(github_token=github_token)
client = GitHubClient(config)
try:
while True:
try:
choice = input("\nYour choice [A/S/O/L/Q]: ").strip().upper()
except (EOFError, KeyboardInterrupt):
# FR-004: Handle EOF/KeyboardInterrupt gracefully
log("GitHub analysis skipped.", "warning")
return []
if choice == "A":
# FR-005: List all user repos with activity filtering (Feature 005)
log("Fetching your repositories...", "info")
try:
repos = client.list_user_repos()
if not repos:
log("No repositories found for your account.", "warning")
continue
# Feature 005: Apply activity filtering
cutoff = get_cutoff_date(days)
active_repos = filter_by_activity(repos, cutoff)
# Display activity statistics (FR-007)
display_activity_stats(total=len(repos), active=len(active_repos), days=days)
# Handle zero active repos (FR-009)
current_days = days
if not active_repos:
result_repos, new_days, should_exit = _handle_zero_active_repos(
repos, current_days, len(repos)
)
if should_exit:
return [] # EOF/KeyboardInterrupt - exit completely
if result_repos is None:
continue # User cancelled - return to menu
active_repos = result_repos
if new_days is not None:
current_days = new_days
# Confirmation prompt (FR-006)
try:
confirm = input(f"Proceed with {len(active_repos)} active repositories? [Y/n/all]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
log("GitHub analysis skipped.", "warning")
return []
if confirm == "n":
continue # Return to menu
elif confirm == "all":
# Use all repos (bypass filter)
repo_names = [r["full_name"] for r in repos]
else:
# Default (Y or Enter): use active repos only
repo_names = [r["full_name"] for r in active_repos]
log(f"Using {len(repo_names)} repositories.", "success")
return repo_names
except RateLimitError as e:
_handle_rate_limit(e, log)
continue
except GitHubAnalyzerError as e:
log(f"Error fetching repositories: {e.message}", "error")
continue
elif choice == "S":
# FR-009: Manual specification
try:
manual_input = input("Enter repository names (owner/repo, comma-separated): ").strip()
except (EOFError, KeyboardInterrupt):
log("GitHub analysis skipped.", "warning")
return []
if not manual_input:
log("No repositories entered.", "warning")
continue
# Parse and validate (FR-011, FR-012)
manual_repos = [r.strip() for r in manual_input.split(",") if r.strip()]
valid_repos = [r for r in manual_repos if validate_repo_format(r)]
invalid_repos = [r for r in manual_repos if not validate_repo_format(r)]
if invalid_repos:
log(f"Invalid repository format ignored: {', '.join(invalid_repos)}", "warning")
if valid_repos:
log(f"Selected {len(valid_repos)} repositories: {', '.join(valid_repos)}", "success")
return valid_repos
else:
log("No valid repository names entered. Try again.", "warning")
elif choice == "O":
# FR-006: Organization repos with Search API filtering (Feature 005)
try:
org_name = input("Enter organization name: ").strip()
except (EOFError, KeyboardInterrupt):
log("GitHub analysis skipped.", "warning")
return []
if not validate_org_name(org_name):
log("Invalid organization name format.", "warning")
continue
log(f"Fetching repositories for organization '{org_name}'...", "info")
try:
# Feature 005: Use Search API for efficient org filtering
cutoff = get_cutoff_date(days)
cutoff_str = cutoff.isoformat()
# Get total org repos count for stats
all_org_repos = client.list_org_repos(org_name)
total_count = len(all_org_repos)
if total_count == 0:
log(f"No repositories found in organization '{org_name}'.", "warning")
continue
# Get active repos via Search API
search_result = client.search_active_org_repos(org_name, cutoff_str)
active_repos = search_result.get("items", [])
incomplete = search_result.get("incomplete_results", False)
# Display activity statistics (FR-007)
display_activity_stats(total=total_count, active=len(active_repos), days=days)
# Warn if results may be incomplete
if incomplete:
print("⚠️ Results may be incomplete due to API limitations.")
# Handle zero active repos (FR-009)
current_days = days
if not active_repos:
result_repos, new_days, should_exit = _handle_zero_active_repos(
all_org_repos, current_days, total_count
)
if should_exit:
return [] # EOF/KeyboardInterrupt - exit completely
if result_repos is None:
continue # User cancelled - return to menu
active_repos = result_repos
if new_days is not None:
current_days = new_days
# Confirmation prompt (FR-006)
try:
confirm = input(f"Show {len(active_repos)} active repositories for selection? [Y/n/all]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
log("GitHub analysis skipped.", "warning")
return []
if confirm == "n":
continue # Return to menu
elif confirm == "all":
# Show all repos (bypass filter)
display_repos = all_org_repos
else:
# Default (Y or Enter): show active repos only
display_repos = active_repos
log(f"Showing {len(display_repos)} repositories:", "info")
print(format_repo_list(display_repos))
# Ask for selection
try:
selection_input = input("\nSelect (e.g., 1,3,5 or 1-3 or 'all'): ").strip()
except (EOFError, KeyboardInterrupt):
log("GitHub analysis skipped.", "warning")
return []
indices = parse_project_selection(selection_input, len(display_repos))
if indices:
selected = [display_repos[i]["full_name"] for i in indices]
log(f"Selected {len(selected)} repositories.", "success")
return selected
else:
log("Invalid selection.", "warning")
except RateLimitError as e:
# Feature 005 FR-008: Fallback to unfiltered mode on rate limit
_handle_rate_limit(e, log)
log("Showing all repositories without activity filter.", "info")
try:
all_org_repos = client.list_org_repos(org_name)
if all_org_repos:
log(f"Showing {len(all_org_repos)} repositories (unfiltered):", "info")
print(format_repo_list(all_org_repos))
selection_input = input("\nSelect (e.g., 1,3,5 or 1-3 or 'all'): ").strip()
indices = parse_project_selection(selection_input, len(all_org_repos))
if indices:
selected = [all_org_repos[i]["full_name"] for i in indices]
log(f"Selected {len(selected)} repositories.", "success")
return selected
except (EOFError, KeyboardInterrupt, GitHubAnalyzerError):
pass
continue
except GitHubAnalyzerError as e:
if "404" in str(e):
log(f"Organization '{org_name}' not found or not accessible.", "warning")
else:
log(f"Error fetching organization repos: {e.message}", "error")
continue
elif choice == "L":
# FR-010: Select from personal list with activity filtering (Feature 005)
log("Fetching your repositories...", "info")
try:
repos = client.list_user_repos()
if not repos:
log("No repositories found for your account.", "warning")
continue
# Feature 005: Apply activity filtering
cutoff = get_cutoff_date(days)
active_repos = filter_by_activity(repos, cutoff)
# Display activity statistics (FR-007)
display_activity_stats(total=len(repos), active=len(active_repos), days=days)
# Handle zero active repos (FR-009)
current_days = days
if not active_repos:
result_repos, new_days, should_exit = _handle_zero_active_repos(
repos, current_days, len(repos)
)
if should_exit:
return [] # EOF/KeyboardInterrupt - exit completely