-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub_org_stats.py
More file actions
1920 lines (1564 loc) · 69.4 KB
/
github_org_stats.py
File metadata and controls
1920 lines (1564 loc) · 69.4 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
#!/usr/bin/env python3
"""
GitHub Organization Statistics Tool
==================================
A comprehensive tool for analyzing GitHub organization statistics including:
- Repository metrics and analysis
- Contributor activity and engagement
- Code quality and security insights
- Multi-organization support with GitHub Apps
This is an open-source tool for analyzing GitHub organizations and repositories.
It provides detailed insights into repository activity, contributor engagement,
code quality metrics, and organizational health indicators.
Author: Zohar Babin
License: MIT
Version: 1.1.0
Homepage: https://github.com/zoharbabin/github-org-stats/
"""
# =============================================================================
# IMPORTS AND DEPENDENCIES
# =============================================================================
import argparse
import logging
import sys
import os
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Any, Set
import json
import time
from pathlib import Path
import re
from collections import defaultdict
import base64
from dataclasses import dataclass, asdict
from enum import Enum
import threading
import signal
from contextlib import contextmanager
import pytz
from datetime import timezone
# Third-party imports
try:
import requests
import pandas as pd
import numpy as np
from github import Github
from github.GithubException import GithubException, RateLimitExceededException, UnknownObjectException
import jwt
from tqdm import tqdm
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.worksheet.datavalidation import DataValidation
except ImportError as e:
print(f"Error: Missing required dependency: {e}")
print("Please install required packages: pip install requests pandas PyGithub PyJWT tqdm openpyxl pytz numpy")
sys.exit(1)
# =============================================================================
# CONFIGURATION AND CONSTANTS
# =============================================================================
# API Configuration
GITHUB_API_BASE_URL = "https://api.github.com"
DEFAULT_RATE_LIMIT_DELAY = 1.0
MAX_RETRIES = 3
RETRY_BACKOFF_FACTOR = 2.0
RATE_LIMIT_BUFFER = 100 # Keep this many requests in reserve
# Output Configuration
DEFAULT_OUTPUT_DIR = "output"
DEFAULT_LOG_LEVEL = "INFO"
# Data Collection Defaults
DEFAULT_DAYS_BACK = 30
DEFAULT_MAX_REPOS = 100
# Caching for forbidden operations
FORBIDDEN_CACHE = set()
# Bot account patterns for detection
BOT_PATTERNS = [
r'.*bot$',
r'.*\[bot\]$',
r'^dependabot.*',
r'^renovate.*',
r'^github-actions.*',
r'^codecov.*',
r'^greenkeeper.*',
r'^snyk.*',
r'^whitesource.*',
r'^sonarcloud.*',
r'^imgbot$',
r'^allcontributors.*',
r'^semantic-release.*',
r'^stale.*',
r'^mergify.*',
r'^pre-commit-ci.*'
]
# Compile bot patterns for efficiency
COMPILED_BOT_PATTERNS = [re.compile(pattern, re.IGNORECASE) for pattern in BOT_PATTERNS]
# Excel Configuration
EXCEL_BATCH_SIZE = 100
EXCEL_MAX_CELL_LENGTH = 32767
EXCEL_SHEET_MAX_ROWS = 1048576
DEFAULT_TIMEZONE = 'UTC'
# Progress tracking
PROGRESS_UPDATE_INTERVAL = 10
# =============================================================================
# GITHUB APP AUTHENTICATION SYSTEM
# =============================================================================
def generate_jwt(app_id: int, private_key: str) -> str:
"""
Generate a JWT token for GitHub App authentication.
Args:
app_id: GitHub App ID
private_key: Private key content (PEM format)
Returns:
JWT token string
"""
now = int(time.time())
payload = {
'iat': now - 60, # Issued at time (60 seconds ago to account for clock skew)
'exp': now + 600, # Expires in 10 minutes
'iss': app_id # Issuer (GitHub App ID)
}
return jwt.encode(payload, private_key, algorithm='RS256')
class GitHubAppTokenManager:
"""
Manages GitHub App authentication tokens with caching and automatic refresh.
"""
def __init__(self, app_id: int, private_key: str):
"""
Initialize the token manager.
Args:
app_id: GitHub App ID
private_key: Private key content (PEM format)
"""
self.app_id = app_id
self.private_key = private_key
self._installation_tokens = {}
self._jwt_token = None
self._jwt_expires_at = 0
def get_jwt_token(self) -> str:
"""
Get a valid JWT token, generating a new one if needed.
Returns:
JWT token string
"""
now = time.time()
if not self._jwt_token or now >= self._jwt_expires_at - 60: # Refresh 1 minute early
self._jwt_token = generate_jwt(self.app_id, self.private_key)
self._jwt_expires_at = now + 600 # JWT expires in 10 minutes
return self._jwt_token
def get_installation_token(self, installation_id: int) -> str:
"""
Get an installation access token, using cache if available.
Args:
installation_id: GitHub App installation ID
Returns:
Installation access token
"""
now = time.time()
# Check if we have a cached token that's still valid
if installation_id in self._installation_tokens:
token_info = self._installation_tokens[installation_id]
if now < token_info['expires_at'] - 300: # Refresh 5 minutes early
return token_info['token']
# Get a new installation token
jwt_token = self.get_jwt_token()
headers = {
'Authorization': f'Bearer {jwt_token}',
'Accept': 'application/vnd.github.v3+json'
}
response = requests.post(
f'{GITHUB_API_BASE_URL}/app/installations/{installation_id}/access_tokens',
headers=headers
)
response.raise_for_status()
token_data = response.json()
expires_at = datetime.fromisoformat(
token_data['expires_at'].replace('Z', '+00:00')
).timestamp()
# Cache the token
self._installation_tokens[installation_id] = {
'token': token_data['token'],
'expires_at': expires_at
}
return token_data['token']
# =============================================================================
# AUTHENTICATION FUNCTIONS
# =============================================================================
def load_github_app_creds() -> Tuple[Optional[int], Optional[str]]:
"""
Load GitHub App credentials from environment variables or CLI arguments.
Returns:
Tuple of (app_id, private_key_content) or (None, None) if not available
"""
app_id = os.getenv('GITHUB_APP_ID')
private_key_path = os.getenv('GITHUB_PRIVATE_KEY_PATH')
if app_id and private_key_path:
try:
with open(private_key_path, 'r') as f:
private_key = f.read()
return int(app_id), private_key
except (FileNotFoundError, ValueError) as e:
logging.getLogger('github_org_stats').warning(
f"Failed to load GitHub App credentials from environment: {e}"
)
return None, None
def parse_installation_ids(installation_str: str) -> Dict[str, int]:
"""
Parse installation IDs from string format.
Supports formats:
- Single ID: "12345"
- Multiple IDs: "org1:12345,org2:67890"
Args:
installation_str: Installation ID string
Returns:
Dictionary mapping organization names to installation IDs
"""
installations = {}
if ',' in installation_str:
# Multiple installations format: "org1:id1,org2:id2"
for pair in installation_str.split(','):
if ':' in pair:
org, install_id = pair.strip().split(':', 1)
installations[org.strip()] = int(install_id.strip())
else:
# Fallback: treat as single ID for default org
installations['default'] = int(pair.strip())
else:
# Single installation ID
if ':' in installation_str:
org, install_id = installation_str.split(':', 1)
installations[org.strip()] = int(install_id.strip())
else:
installations['default'] = int(installation_str)
return installations
def get_installation_id(org_name: str, token_manager: GitHubAppTokenManager,
specified_installations: Optional[Dict[str, int]] = None) -> int:
"""
Get the installation ID for a specific organization.
Args:
org_name: Organization name
token_manager: GitHub App token manager
specified_installations: Pre-specified installation mappings
Returns:
Installation ID for the organization
Raises:
ValueError: If installation ID cannot be determined
"""
# Check if installation ID was explicitly specified
if specified_installations:
if org_name in specified_installations:
return specified_installations[org_name]
elif 'default' in specified_installations:
return specified_installations['default']
# Query GitHub API to find installation for organization
jwt_token = token_manager.get_jwt_token()
headers = {
'Authorization': f'Bearer {jwt_token}',
'Accept': 'application/vnd.github.v3+json'
}
response = requests.get(f'{GITHUB_API_BASE_URL}/app/installations', headers=headers)
response.raise_for_status()
installations = response.json()
for installation in installations:
if installation['account']['login'].lower() == org_name.lower():
return installation['id']
raise ValueError(f"No GitHub App installation found for organization: {org_name}")
def get_installation_token(app_id: int, private_key: str, installation_id: int) -> str:
"""
Get an installation access token for GitHub App authentication.
Args:
app_id: GitHub App ID
private_key: Private key content (PEM format)
installation_id: Installation ID
Returns:
Installation access token
"""
token_manager = GitHubAppTokenManager(app_id, private_key)
return token_manager.get_installation_token(installation_id)
def load_private_key(private_key_path: str) -> str:
"""
Load and cache private key from file.
Args:
private_key_path: Path to private key file
Returns:
Private key content
Raises:
FileNotFoundError: If private key file doesn't exist
ValueError: If private key format is invalid
"""
if not os.path.exists(private_key_path):
raise FileNotFoundError(f"Private key file not found: {private_key_path}")
try:
with open(private_key_path, 'r') as f:
private_key = f.read()
# Basic validation - check if it looks like a PEM key
if not private_key.strip().startswith('-----BEGIN'):
raise ValueError("Private key file does not appear to be in PEM format")
return private_key
except Exception as e:
raise ValueError(f"Failed to load private key: {e}")
# =============================================================================
# RATE LIMITING & ERROR HANDLING
# =============================================================================
def print_rate_limit(github_client: Github) -> None:
"""
Print current rate limit status.
Args:
github_client: GitHub client instance
"""
try:
rate_limit = github_client.get_rate_limit()
core = rate_limit.core
search = rate_limit.search
logger = logging.getLogger('github_org_stats')
logger.info(f"Rate Limit Status:")
logger.info(f" Core API: {core.remaining}/{core.limit} (resets at {core.reset})")
logger.info(f" Search API: {search.remaining}/{search.limit} (resets at {search.reset})")
except Exception as e:
logging.getLogger('github_org_stats').warning(f"Could not fetch rate limit: {e}")
def robust_github_call(func, *args, max_retries: int = MAX_RETRIES, **kwargs):
"""
Execute a GitHub API call with robust error handling and retry logic.
Args:
func: Function to call
*args: Positional arguments for the function
max_retries: Maximum number of retry attempts
**kwargs: Keyword arguments for the function
Returns:
Function result or None if all retries failed
"""
logger = logging.getLogger('github_org_stats')
for attempt in range(max_retries + 1):
try:
return func(*args, **kwargs)
except RateLimitExceededException as e:
if attempt < max_retries:
wait_time = e.retry_after if hasattr(e, 'retry_after') else 60
logger.warning(f"Rate limit exceeded. Waiting {wait_time} seconds...")
time.sleep(wait_time)
continue
else:
logger.error("Rate limit exceeded and max retries reached")
return None
except UnknownObjectException as e:
# Don't retry for 404 errors
logger.debug(f"Resource not found: {e}")
return None
except GithubException as e:
if e.status == 403:
# Forbidden - cache this to avoid repeated attempts
cache_key = f"{func.__name__}:{str(args)}"
FORBIDDEN_CACHE.add(cache_key)
logger.debug(f"Access forbidden (cached): {e}")
return None
elif e.status >= 500 and attempt < max_retries:
# Server error - retry with backoff
wait_time = (RETRY_BACKOFF_FACTOR ** attempt) * DEFAULT_RATE_LIMIT_DELAY
logger.warning(f"Server error {e.status}. Retrying in {wait_time:.1f}s...")
time.sleep(wait_time)
continue
else:
logger.error(f"GitHub API error: {e}")
return None
except Exception as e:
if attempt < max_retries:
wait_time = (RETRY_BACKOFF_FACTOR ** attempt) * DEFAULT_RATE_LIMIT_DELAY
logger.warning(f"Unexpected error: {e}. Retrying in {wait_time:.1f}s...")
time.sleep(wait_time)
continue
else:
logger.error(f"Unexpected error after {max_retries} retries: {e}")
return None
return None
def gh_safe(github_client: Github, func, *args, **kwargs):
"""
Wrapper for GitHub API calls with token refresh handling.
Args:
github_client: GitHub client instance
func: Function to call
*args: Positional arguments
**kwargs: Keyword arguments
Returns:
Function result or None if failed
"""
# Check if this operation is cached as forbidden
cache_key = f"{func.__name__ if hasattr(func, '__name__') else str(func)}:{str(args)}"
if cache_key in FORBIDDEN_CACHE:
return None
# Check rate limit before making call
try:
rate_limit = github_client.get_rate_limit()
if rate_limit.core.remaining < RATE_LIMIT_BUFFER:
logger = logging.getLogger('github_org_stats')
reset_time = rate_limit.core.reset
wait_time = (reset_time - datetime.now()).total_seconds() + 10
if wait_time > 0:
logger.warning(f"Rate limit low ({rate_limit.core.remaining}). Waiting {wait_time:.0f}s...")
time.sleep(wait_time)
except:
pass # Continue if rate limit check fails
return robust_github_call(func, *args, **kwargs)
# =============================================================================
# BOT DETECTION AND FILTERING
# =============================================================================
def is_bot_account(username: str) -> bool:
"""
Check if a username appears to be a bot account.
Args:
username: GitHub username to check
Returns:
True if username matches bot patterns
"""
if not username:
return False
for pattern in COMPILED_BOT_PATTERNS:
if pattern.match(username):
return True
return False
def filter_bot_contributors(contributors: List[Dict[str, Any]], exclude_bots: bool = True) -> List[Dict[str, Any]]:
"""
Filter bot accounts from contributors list.
Args:
contributors: List of contributor dictionaries
exclude_bots: Whether to exclude bot accounts
Returns:
Filtered contributors list
"""
if not exclude_bots:
return contributors
return [
contrib for contrib in contributors
if not is_bot_account(contrib.get('login', ''))
]
# =============================================================================
# GITHUB API HELPER FUNCTIONS
# =============================================================================
def safe_get_commits(repo, since_date: datetime = None) -> List[Any]:
"""
Safely get commits from a repository, handling empty repositories.
Args:
repo: GitHub repository object
since_date: Optional date to filter commits from
Returns:
List of commit objects or empty list if failed
"""
try:
commits_kwargs = {}
if since_date:
commits_kwargs['since'] = since_date
commits = list(repo.get_commits(**commits_kwargs))
return commits
except (GithubException, Exception):
return []
def get_commit_stats(repo, days_back: int = 30) -> Dict[str, Any]:
"""
Get commit statistics with author breakdown.
Args:
repo: GitHub repository object
days_back: Number of days to look back
Returns:
Dictionary with commit statistics
"""
since_date = datetime.now() - timedelta(days=days_back)
commits = safe_get_commits(repo, since_date)
stats = {
'total_commits': len(commits),
'unique_authors': set(),
'commit_authors': defaultdict(int),
'commits_by_day': defaultdict(int)
}
for commit in commits:
if commit.author:
author = commit.author.login
stats['unique_authors'].add(author)
stats['commit_authors'][author] += 1
commit_date = commit.commit.author.date.strftime('%Y-%m-%d')
stats['commits_by_day'][commit_date] += 1
stats['unique_authors'] = len(stats['unique_authors'])
stats['commit_authors'] = dict(stats['commit_authors'])
stats['commits_by_day'] = dict(stats['commits_by_day'])
return stats
def get_code_bytes(repo) -> Dict[str, int]:
"""
Get language statistics for a repository.
Args:
repo: GitHub repository object
Returns:
Dictionary mapping language names to byte counts
"""
try:
languages = repo.get_languages()
return dict(languages) if languages else {}
except (GithubException, Exception):
return {}
def get_repo_topics(repo) -> List[str]:
"""
Get repository topics.
Args:
repo: GitHub repository object
Returns:
List of topic strings
"""
try:
return list(repo.get_topics()) if hasattr(repo, 'get_topics') else []
except (GithubException, Exception):
return []
def get_submodules_info(repo) -> List[Dict[str, str]]:
"""
Parse .gitmodules file to get submodule information.
Args:
repo: GitHub repository object
Returns:
List of dictionaries with submodule info
"""
try:
gitmodules = repo.get_contents('.gitmodules')
content = base64.b64decode(gitmodules.content).decode('utf-8')
submodules = []
current_submodule = {}
for line in content.split('\n'):
line = line.strip()
if line.startswith('[submodule'):
if current_submodule:
submodules.append(current_submodule)
current_submodule = {'name': line.split('"')[1] if '"' in line else ''}
elif '=' in line and current_submodule:
key, value = line.split('=', 1)
current_submodule[key.strip()] = value.strip()
if current_submodule:
submodules.append(current_submodule)
return submodules
except (GithubException, Exception):
return []
def get_sbom_deps(repo) -> Dict[str, List[str]]:
"""
Get dependency information from common dependency files.
Args:
repo: GitHub repository object
Returns:
Dictionary mapping dependency file types to lists of dependencies
"""
deps = {}
# Common dependency files to check
dep_files = {
'package.json': 'npm',
'requirements.txt': 'pip',
'Gemfile': 'gem',
'pom.xml': 'maven',
'build.gradle': 'gradle',
'Cargo.toml': 'cargo',
'go.mod': 'go'
}
for filename, dep_type in dep_files.items():
try:
file_content = repo.get_contents(filename)
content = base64.b64decode(file_content.content).decode('utf-8')
if dep_type == 'npm':
# Parse package.json
try:
import json
pkg_data = json.loads(content)
deps[dep_type] = list(pkg_data.get('dependencies', {}).keys())
except:
deps[dep_type] = []
elif dep_type == 'pip':
# Parse requirements.txt
deps[dep_type] = [line.split('==')[0].split('>=')[0].split('<=')[0].strip()
for line in content.split('\n')
if line.strip() and not line.startswith('#')]
else:
# For other types, just note that the file exists
deps[dep_type] = ['present']
except (GithubException, Exception):
continue
return deps
def get_primary_contributors(repo, limit: int = 10) -> List[Dict[str, Any]]:
"""
Get top contributors to a repository.
Args:
repo: GitHub repository object
limit: Maximum number of contributors to return
Returns:
List of contributor dictionaries
"""
try:
contributors = list(repo.get_contributors())[:limit]
return [
{
'login': contrib.login,
'contributions': contrib.contributions,
'avatar_url': contrib.avatar_url,
'html_url': contrib.html_url
}
for contrib in contributors
]
except (GithubException, Exception):
return []
def get_repo_teams(repo) -> List[Dict[str, str]]:
"""
Get teams with access to a repository.
Args:
repo: GitHub repository object
Returns:
List of team dictionaries
"""
try:
teams = list(repo.get_teams())
return [
{
'name': team.name,
'slug': team.slug,
'permission': getattr(team, 'permission', 'unknown')
}
for team in teams
]
except (GithubException, Exception):
return []
def get_repo_collaborators(repo) -> List[Dict[str, str]]:
"""
Get collaborators for a repository.
Args:
repo: GitHub repository object
Returns:
List of collaborator dictionaries
"""
try:
collaborators = list(repo.get_collaborators())
return [
{
'login': collab.login,
'permissions': getattr(collab, 'permissions', {}),
'role': getattr(collab, 'role_name', 'unknown')
}
for collab in collaborators
]
except (GithubException, Exception):
return []
def get_repo_admins(repo) -> List[str]:
"""
Get admin users for a repository.
Args:
repo: GitHub repository object
Returns:
List of admin usernames
"""
try:
collaborators = get_repo_collaborators(repo)
return [
collab['login']
for collab in collaborators
if collab.get('permissions', {}).get('admin', False)
]
except (GithubException, Exception):
return []
def get_branches_tags_counts(repo) -> Dict[str, int]:
"""
Count branches and tags in a repository.
Args:
repo: GitHub repository object
Returns:
Dictionary with branch and tag counts
"""
try:
branches = list(repo.get_branches())
tags = list(repo.get_tags())
return {
'branches_count': len(branches),
'tags_count': len(tags)
}
except (GithubException, Exception):
return {'branches_count': 0, 'tags_count': 0}
def get_release_info(repo) -> Dict[str, Any]:
"""
Get latest release information.
Args:
repo: GitHub repository object
Returns:
Dictionary with release information
"""
try:
releases = list(repo.get_releases())
if releases:
latest = releases[0]
return {
'latest_release': latest.tag_name,
'release_date': latest.published_at.isoformat() if latest.published_at else None,
'release_url': latest.html_url,
'total_releases': len(releases)
}
else:
return {'latest_release': None, 'total_releases': 0}
except (GithubException, Exception):
return {'latest_release': None, 'total_releases': 0}
def get_actions_info(repo) -> Dict[str, Any]:
"""
Get GitHub Actions workflow information.
Args:
repo: GitHub repository object
Returns:
Dictionary with Actions information
"""
try:
workflows = list(repo.get_workflows())
workflow_runs = list(repo.get_workflow_runs())[:10] # Get last 10 runs
return {
'workflows_count': len(workflows),
'recent_runs': len(workflow_runs),
'workflows': [
{
'name': wf.name,
'state': wf.state,
'path': wf.path
}
for wf in workflows
]
}
except (GithubException, Exception):
return {'workflows_count': 0, 'recent_runs': 0, 'workflows': []}
def get_default_branch_protection(repo) -> Dict[str, Any]:
"""
Check default branch protection settings.
Args:
repo: GitHub repository object
Returns:
Dictionary with branch protection information
"""
try:
default_branch = repo.default_branch
branch = repo.get_branch(default_branch)
protection = branch.get_protection()
return {
'protected': True,
'required_status_checks': bool(protection.required_status_checks),
'enforce_admins': protection.enforce_admins,
'required_pull_request_reviews': bool(protection.required_pull_request_reviews),
'restrictions': bool(protection.restrictions)
}
except (GithubException, Exception):
return {'protected': False}
def get_latest_commit_info(repo) -> Dict[str, Any]:
"""
Get latest commit information.
Args:
repo: GitHub repository object
Returns:
Dictionary with latest commit information
"""
try:
commits = list(repo.get_commits())
if commits:
latest = commits[0]
return {
'sha': latest.sha,
'author': latest.author.login if latest.author else 'unknown',
'date': latest.commit.author.date.isoformat(),
'message': latest.commit.message[:100] + '...' if len(latest.commit.message) > 100 else latest.commit.message
}
else:
return {}
except (GithubException, Exception):
return {}
# =============================================================================
# LANGUAGE NAME SANITIZATION SYSTEM
# =============================================================================
def sanitize_language_names(repo_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Sanitize problematic language names to prevent Excel column name conflicts.
This function addresses the issue where Excel sanitizes the "#" character in column names,
causing "languages.C#" to become "languages.C" and creating conflicts with actual C language data.
Args:
repo_data: List of repository dictionaries containing language data
Returns:
List of repository dictionaries with sanitized language names
"""
import copy
logger = logging.getLogger('github_org_stats')
# Define language name mappings for problematic characters
language_mappings = {
'C#': 'CSharp',
'C++': 'CPlusPlus',
'F#': 'FSharp'
}
sanitized_languages = []
transformation_count = 0
for repo in repo_data:
# Create a deep copy to avoid modifying the original data
sanitized_repo = copy.deepcopy(repo)
# Check if repository has language data
if 'languages' in sanitized_repo and isinstance(sanitized_repo['languages'], dict):
original_languages = sanitized_repo['languages']
sanitized_repo_languages = {}
for lang_name, byte_count in original_languages.items():
if lang_name in language_mappings:
new_name = language_mappings[lang_name]
sanitized_repo_languages[new_name] = byte_count
transformation_count += 1
logger.debug(f"Sanitized language name in {sanitized_repo.get('name', 'unknown')}: {lang_name} → {new_name}")
else:
sanitized_repo_languages[lang_name] = byte_count
sanitized_repo['languages'] = sanitized_repo_languages
# Update primary_language if it was one of the sanitized languages (handle independently of languages dict)
if 'primary_language' in sanitized_repo and sanitized_repo['primary_language'] in language_mappings:
old_primary = sanitized_repo['primary_language']
sanitized_repo['primary_language'] = language_mappings[old_primary]