-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelease_analytics.py
More file actions
888 lines (718 loc) · 34.4 KB
/
Copy pathrelease_analytics.py
File metadata and controls
888 lines (718 loc) · 34.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
import os
import sys
import json
import csv
import re
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple
from collections import Counter, defaultdict
import requests
import click
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn
from rich.table import Table
from rich.panel import Panel
from rich.columns import Columns
GITHUB_API_URL = "https://api.github.com"
console = Console()
# Nomi dei giorni della settimana in italiano
GIORNI_SETTIMANA = ["Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"]
MESI = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno",
"Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"]
def get_github_session(token: Optional[str] = None):
"""Crea una sessione GitHub autenticata."""
if not token:
token = os.environ.get("GITHUB_TOKEN")
if not token:
console.print(
"[bold red]Errore:[/bold red] devi impostare la variabile d'ambiente GITHUB_TOKEN "
"o passare il token con --token",
style="red"
)
console.print("Esempio: [cyan]export GITHUB_TOKEN=tuo_token_personale[/cyan]")
sys.exit(1)
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "release-analytics-script"
})
return session
def validate_date(date_string: str) -> str:
"""Valida il formato della data."""
try:
datetime.strptime(date_string, "%Y-%m-%d")
return date_string
except ValueError:
raise click.BadParameter(f"Data non valida: {date_string}. Usa il formato YYYY-MM-DD")
def get_org_repositories(session, org: str, verbose: bool = False) -> List[Dict]:
"""Ottiene tutti i repository di un'organizzazione."""
repos = []
page = 1
per_page = 100
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
disable=not verbose
) as progress:
task = progress.add_task(f"Recuperando repository di {org}...", total=None)
while True:
resp = session.get(
f"{GITHUB_API_URL}/orgs/{org}/repos",
params={"page": page, "per_page": per_page, "type": "all"}
)
if resp.status_code == 403:
console.print("[bold red]Errore:[/bold red] Rate limit raggiunto o permessi insufficienti")
sys.exit(1)
if resp.status_code != 200:
console.print(f"[bold red]Errore nel recupero dei repository:[/bold red] {resp.status_code}")
console.print(f"Risposta: {resp.text}")
sys.exit(1)
data = resp.json()
if not data:
break
repos.extend(data)
if verbose:
progress.update(task, description=f"Trovati {len(repos)} repository...")
if len(data) < per_page:
break
page += 1
console.print(f"[green]✓[/green] Trovati [bold]{len(repos)}[/bold] repository.")
return repos
def get_releases_for_repo(session, owner: str, repo: str, verbose: bool = False) -> List[Dict]:
"""Ottiene tutte le release di un repository."""
releases = []
page = 1
per_page = 100
while True:
resp = session.get(
f"{GITHUB_API_URL}/repos/{owner}/{repo}/releases",
params={"page": page, "per_page": per_page}
)
if resp.status_code == 403:
if verbose:
console.print(f" [yellow][WARN][/yellow] Permessi insufficienti per {owner}/{repo}")
break
if resp.status_code == 404:
# Repository senza release o non accessibile
break
if resp.status_code != 200:
if verbose:
console.print(f" [yellow][WARN][/yellow] Errore {resp.status_code} per {owner}/{repo}")
break
data = resp.json()
if not data:
break
# Aggiungi informazioni sul repository a ogni release
for release in data:
release["repo_name"] = repo
release["repo_owner"] = owner
release["repo_full_name"] = f"{owner}/{repo}"
releases.extend(data)
if len(data) < per_page:
break
page += 1
return releases
def get_all_releases_for_org(session, org: str, repo_filter: Optional[List[str]] = None, verbose: bool = False) -> List[Dict]:
"""Ottiene tutte le release di tutti i repository di un'organizzazione.
Args:
session: Sessione GitHub autenticata
org: Nome dell'organizzazione
repo_filter: Lista opzionale di nomi di repository da analizzare (se None, analizza tutti)
verbose: Mostra informazioni dettagliate
"""
repos = get_org_repositories(session, org, verbose)
if not repos:
return []
# Filtra i repository se specificato
if repo_filter:
repo_filter_set = {r.lower().strip() for r in repo_filter} # Case-insensitive
repos = [r for r in repos if r.get("name", "").lower() in repo_filter_set]
if not repos:
console.print(f"[yellow]Nessun repository trovato nella lista specificata.[/yellow]")
console.print(f"[dim]Repository cercati: {', '.join(repo_filter)}[/dim]")
return []
if verbose:
console.print(f"[dim]Filtrati {len(repos)} repository dalla lista specificata[/dim]")
all_releases = []
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
console=console,
disable=not verbose
) as progress:
task = progress.add_task("Recuperando release da tutti i repository...", total=len(repos))
for repo in repos:
repo_name = repo.get("name", "")
owner = repo.get("owner", {}).get("login", org)
releases = get_releases_for_repo(session, owner, repo_name, verbose)
all_releases.extend(releases)
if verbose:
progress.update(task, advance=1, description=f"Trovate {len(all_releases)} release totali...")
console.print(f"[green]✓[/green] Trovate [bold]{len(all_releases)}[/bold] release totali da [bold]{len(repos)}[/bold] repository.")
return all_releases
def get_release_compare(session, owner: str, repo: str, base: str, head: str) -> Optional[Dict]:
"""Ottiene il confronto tra due tag/commit."""
try:
resp = session.get(
f"{GITHUB_API_URL}/repos/{owner}/{repo}/compare/{base}...{head}"
)
if resp.status_code == 200:
return resp.json()
except:
pass
return None
def get_commits_for_release(session, release: Dict, previous_release: Optional[Dict] = None, verbose: bool = False) -> Dict:
"""Ottiene informazioni sui commit per una release."""
tag_name = release.get("tag_name", "")
published_at = release.get("published_at", "")
owner = release.get("repo_owner", "")
repo = release.get("repo_name", "")
# Se c'è una release precedente dello stesso repo, confronta i tag
if previous_release and previous_release.get("repo_full_name") == release.get("repo_full_name"):
prev_tag = previous_release.get("tag_name", "")
compare_data = get_release_compare(session, owner, repo, prev_tag, tag_name)
if compare_data:
commits = compare_data.get("commits", [])
files = compare_data.get("files", [])
# Estrai autori unici
authors = set()
for commit in commits:
author = commit.get("author")
if author:
authors.add(author.get("login", ""))
else:
commit_info = commit.get("commit", {})
author_info = commit_info.get("author", {})
authors.add(author_info.get("name", "Unknown"))
return {
"commit_count": len(commits),
"file_count": len(files),
"authors": list(authors),
"author_count": len(authors),
"files": files
}
# Fallback: cerca commit dal tag fino al commit precedente
# Per semplicità, restituiamo dati base
return {
"commit_count": 0,
"file_count": 0,
"authors": [],
"author_count": 0,
"files": []
}
def filter_releases_by_date(releases: List[Dict], from_date: str, to_date: str, verbose: bool = False) -> List[Dict]:
"""Filtra le release per periodo."""
from_dt = datetime.strptime(from_date, "%Y-%m-%d")
to_dt = datetime.strptime(to_date, "%Y-%m-%d") + timedelta(days=1) # Include il giorno finale
filtered = []
skipped_no_date = 0
skipped_out_of_range = 0
for release in releases:
published_at = release.get("published_at")
if not published_at:
skipped_no_date += 1
continue
try:
# Parse della data ISO con timezone
# GitHub API restituisce date in formato ISO 8601 con Z (UTC)
release_dt_str = published_at.replace("Z", "+00:00")
release_dt = datetime.fromisoformat(release_dt_str)
# Converti in UTC naive per il confronto (solo la data, senza time)
# Prendi solo la parte data (YYYY-MM-DD) per confronto corretto
release_date_only = release_dt.date() if hasattr(release_dt, 'date') else release_dt.replace(tzinfo=None).date()
from_date_only = from_dt.date()
to_date_only = to_dt.date()
# Confronta solo le date (ignora l'ora)
if from_date_only <= release_date_only < to_date_only:
filtered.append(release)
else:
skipped_out_of_range += 1
except Exception as e:
if verbose:
console.print(f" [yellow][WARN][/yellow] Errore parsing data '{published_at}': {e}")
continue
if verbose:
console.print(f"[dim]Filtro date: {len(filtered)} match, {skipped_no_date} senza data, {skipped_out_of_range} fuori range[/dim]")
if len(filtered) == 0 and len(releases) > 0:
# Mostra range richiesto e alcune date di esempio
console.print(f"[dim]Range richiesto: {from_date} - {to_date}[/dim]")
console.print("[yellow]Prime 3 release trovate (per debug):[/yellow]")
for i, rel in enumerate(releases[:3]):
pub_at = rel.get("published_at", "N/A")
tag = rel.get("tag_name", "N/A")
repo = rel.get("repo_full_name", "N/A")
console.print(f" {i+1}. {tag} ({repo}): {pub_at}")
return filtered
def parse_release_notes(body: str) -> Dict:
"""Analizza le release notes."""
if not body:
return {
"length": 0,
"word_count": 0,
"emoji_count": 0,
"emojis": [],
"words": []
}
# Conta emoji (pattern base per emoji Unicode)
emoji_pattern = re.compile(
"["
"\U0001F600-\U0001F64F" # emoticons
"\U0001F300-\U0001F5FF" # symbols & pictographs
"\U0001F680-\U0001F6FF" # transport & map symbols
"\U0001F1E0-\U0001F1FF" # flags
"\U00002702-\U000027B0"
"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE
)
emojis = emoji_pattern.findall(body)
# Estrai parole (rimuovi emoji e caratteri speciali)
words_text = emoji_pattern.sub("", body)
words = re.findall(r'\b\w+\b', words_text.lower())
return {
"length": len(body),
"word_count": len(words),
"emoji_count": len(emojis),
"emojis": emojis,
"words": words
}
def detect_breaking_changes(body: str) -> bool:
"""Rileva breaking changes nelle release notes."""
if not body:
return False
body_lower = body.lower()
breaking_keywords = [
"breaking change",
"breaking changes",
"breaking",
"⚠️",
"🚨",
"major",
"incompatible"
]
return any(keyword in body_lower for keyword in breaking_keywords)
def calculate_time_metrics(releases: List[Dict]) -> Dict:
"""Calcola metriche temporali."""
if not releases:
return {}
giorni_count = Counter()
ore_count = Counter()
mesi_count = Counter()
notturne = 0
weekend = 0
date_releases = []
for release in releases:
published_at = release.get("published_at")
if not published_at:
continue
try:
dt = datetime.fromisoformat(published_at.replace("Z", "+00:00"))
giorno_settimana = dt.weekday() # 0=Lunedì, 6=Domenica
ora = dt.hour
mese = dt.month - 1 # 0-based
giorni_count[giorno_settimana] += 1
ore_count[ora] += 1
mesi_count[mese] += 1
if ora >= 0 and ora < 6: # Dalle 00:00 alle 06:00
notturne += 1
if giorno_settimana >= 5: # Sabato (5) o Domenica (6)
weekend += 1
date_releases.append(dt)
except:
continue
# Calcola intervallo minimo tra release
min_interval = None
if len(date_releases) > 1:
date_releases.sort()
intervals = []
for i in range(1, len(date_releases)):
interval = (date_releases[i] - date_releases[i-1]).total_seconds() / 3600 # in ore
intervals.append(interval)
if intervals:
min_interval = min(intervals)
# Trova giorno più produttivo
giorno_piu_produttivo = None
if giorni_count:
giorno_num = giorni_count.most_common(1)[0][0]
giorno_piu_produttivo = GIORNI_SETTIMANA[giorno_num]
# Trova ora preferita
ora_preferita = None
if ore_count:
ora_preferita = ore_count.most_common(1)[0][0]
# Trova mese più attivo
mese_piu_attivo = None
if mesi_count:
mese_num = mesi_count.most_common(1)[0][0]
mese_piu_attivo = MESI[mese_num]
return {
"giorno_piu_produttivo": giorno_piu_produttivo,
"ora_preferita": ora_preferita,
"intervallo_minimo_ore": min_interval,
"mese_piu_attivo": mese_piu_attivo,
"release_notturne": notturne,
"release_weekend": weekend,
"distribuzione_giorni": {GIORNI_SETTIMANA[k]: v for k, v in giorni_count.items()},
"distribuzione_ore": dict(ore_count),
"distribuzione_mesi": {MESI[k]: v for k, v in mesi_count.items()}
}
def calculate_content_metrics(releases: List[Dict]) -> Dict:
"""Calcola metriche di contenuto."""
if not releases:
return {}
longest_note = None
longest_length = 0
most_emoji = None
most_emoji_count = 0
all_words = []
commit_counts = []
author_counts = []
for release in releases:
body = release.get("body", "")
notes_data = parse_release_notes(body)
# Release note più lunga
if notes_data["length"] > longest_length:
longest_length = notes_data["length"]
longest_note = {
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"length": longest_length,
"word_count": notes_data["word_count"],
"repo_full_name": release.get("repo_full_name", "")
}
# Release più emotiva
if notes_data["emoji_count"] > most_emoji_count:
most_emoji_count = notes_data["emoji_count"]
most_emoji = {
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"emoji_count": most_emoji_count,
"emojis": notes_data["emojis"][:10], # Prime 10 emoji
"repo_full_name": release.get("repo_full_name", "")
}
# Raccogli parole
all_words.extend(notes_data["words"])
# Commit e autori (se disponibili nei dati della release)
commit_count = release.get("commit_count", 0)
author_count = release.get("author_count", 0)
if commit_count > 0:
commit_counts.append({
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"commit_count": commit_count,
"repo_full_name": release.get("repo_full_name", "")
})
if author_count > 0:
author_counts.append({
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"author_count": author_count,
"repo_full_name": release.get("repo_full_name", "")
})
# Parole più usate
word_counter = Counter(all_words)
# Rimuovi parole comuni
stop_words = {"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for", "of", "with", "by", "is", "are", "was", "were", "be", "been", "have", "has", "had", "do", "does", "did", "will", "would", "should", "could", "may", "might", "must", "can", "this", "that", "these", "those", "i", "you", "he", "she", "it", "we", "they", "what", "which", "who", "when", "where", "why", "how", "all", "each", "every", "both", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"}
filtered_words = {k: v for k, v in word_counter.items() if k not in stop_words and len(k) > 2}
top_words = dict(Counter(filtered_words).most_common(10))
# Release con più commit
release_piu_commit = max(commit_counts, key=lambda x: x["commit_count"]) if commit_counts else None
# Release con più autori
release_piu_autori = max(author_counts, key=lambda x: x["author_count"]) if author_counts else None
return {
"release_note_piu_lunga": longest_note,
"release_piu_emotiva": most_emoji,
"parole_piu_usate": top_words,
"release_piu_commit": release_piu_commit,
"release_piu_autori": release_piu_autori
}
def calculate_collaboration_metrics(releases: List[Dict]) -> Dict:
"""Calcola metriche di collaborazione."""
if not releases:
return {}
author_counter = Counter()
solo_releases = 0
collaborative_releases = []
for release in releases:
author = release.get("author", {}).get("login", "Unknown")
author_counter[author] += 1
author_count = release.get("author_count", 0)
if author_count == 0:
# Se non abbiamo i dati dai commit, assumiamo 1 autore (chi ha fatto la release)
author_count = 1
if author_count == 1:
solo_releases += 1
else:
collaborative_releases.append({
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"author_count": author_count,
"authors": release.get("authors", []),
"repo_full_name": release.get("repo_full_name", "")
})
# Chi ha rilasciato di più
autore_piu_frequente = author_counter.most_common(1)[0] if author_counter else None
# Release più collaborativa
release_piu_collaborativa = max(collaborative_releases, key=lambda x: x["author_count"]) if collaborative_releases else None
return {
"autore_piu_frequente": {
"username": autore_piu_frequente[0],
"count": autore_piu_frequente[1]
} if autore_piu_frequente else None,
"release_piu_collaborativa": release_piu_collaborativa,
"release_solitario": solo_releases,
"release_collaborative": len(collaborative_releases)
}
def calculate_technical_metrics(releases: List[Dict]) -> Dict:
"""Calcola metriche tecniche."""
if not releases:
return {}
file_counts = []
breaking_changes_releases = []
for release in releases:
file_count = release.get("file_count", 0)
if file_count > 0:
file_counts.append({
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"file_count": file_count,
"repo_full_name": release.get("repo_full_name", "")
})
body = release.get("body", "")
if detect_breaking_changes(body):
breaking_changes_releases.append({
"tag": release.get("tag_name", ""),
"title": release.get("name", ""),
"repo_full_name": release.get("repo_full_name", "")
})
# Release più rischiosa (più file modificati)
release_piu_rischiosa = max(file_counts, key=lambda x: x["file_count"]) if file_counts else None
# Release più pulita (meno file modificati, escludendo quelle con 0 file)
release_piu_pulita = min(file_counts, key=lambda x: x["file_count"]) if file_counts else None
return {
"release_piu_rischiosa": release_piu_rischiosa,
"release_piu_pulita": release_piu_pulita,
"release_breaking_changes": breaking_changes_releases,
"count_breaking_changes": len(breaking_changes_releases)
}
def analyze_releases(session, releases: List[Dict], verbose: bool = False) -> Dict:
"""Analizza tutte le release e calcola le metriche."""
if not releases:
return {}
# Ordina release per repository e poi per data (più vecchie prima)
releases_sorted = sorted(releases, key=lambda x: (x.get("repo_full_name", ""), x.get("published_at", "")))
# Arricchisci con dati sui commit
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
BarColumn(),
TaskProgressColumn(),
console=console,
disable=not verbose
) as progress:
task = progress.add_task("Analizzando release...", total=len(releases_sorted))
# Raggruppa per repository per trovare la release precedente corretta
releases_by_repo = defaultdict(list)
for release in releases_sorted:
repo_name = release.get("repo_full_name", "")
releases_by_repo[repo_name].append(release)
for repo_name, repo_releases in releases_by_repo.items():
for i, release in enumerate(repo_releases):
previous_release = repo_releases[i-1] if i > 0 else None
commit_data = get_commits_for_release(session, release, previous_release, verbose)
release.update(commit_data)
if verbose:
progress.update(task, advance=1)
# Calcola tutte le metriche
time_metrics = calculate_time_metrics(releases_sorted)
content_metrics = calculate_content_metrics(releases_sorted)
collaboration_metrics = calculate_collaboration_metrics(releases_sorted)
technical_metrics = calculate_technical_metrics(releases_sorted)
return {
"totale_release": len(releases_sorted),
"metriche_temporali": time_metrics,
"metriche_contenuto": content_metrics,
"metriche_collaborazione": collaboration_metrics,
"metriche_tecniche": technical_metrics
}
def print_results(results: Dict, org: str = None):
"""Stampa i risultati in formato tabella."""
console.print()
title = f"[bold cyan]Analisi Release - {results['totale_release']} release analizzate[/bold cyan]"
if org:
title += f"\n[dim]Organizzazione: {org}[/dim]"
console.print(Panel.fit(title, border_style="cyan"))
console.print()
# Metriche temporali
time_metrics = results.get("metriche_temporali", {})
if time_metrics:
table_time = Table(title="📅 Metriche Temporali", show_header=True, header_style="bold yellow")
table_time.add_column("Metrica", style="cyan")
table_time.add_column("Valore", style="green")
if time_metrics.get("giorno_piu_produttivo"):
table_time.add_row("Giorno più produttivo", time_metrics["giorno_piu_produttivo"])
if time_metrics.get("ora_preferita") is not None:
table_time.add_row("Ora preferita", f"{time_metrics['ora_preferita']}:00")
if time_metrics.get("intervallo_minimo_ore"):
table_time.add_row("Intervallo minimo tra release", f"{time_metrics['intervallo_minimo_ore']:.1f} ore")
if time_metrics.get("mese_piu_attivo"):
table_time.add_row("Mese più attivo", time_metrics["mese_piu_attivo"])
table_time.add_row("Release notturne (00:00-06:00)", str(time_metrics.get("release_notturne", 0)))
table_time.add_row("Release nel weekend", str(time_metrics.get("release_weekend", 0)))
console.print(table_time)
console.print()
# Metriche di contenuto
content_metrics = results.get("metriche_contenuto", {})
if content_metrics:
table_content = Table(title="📝 Metriche di Contenuto", show_header=True, header_style="bold yellow")
table_content.add_column("Metrica", style="cyan")
table_content.add_column("Valore", style="green")
if content_metrics.get("release_note_piu_lunga"):
note = content_metrics["release_note_piu_lunga"]
repo_info = f" ({note.get('repo_full_name', '')})" if note.get('repo_full_name') else ""
table_content.add_row("Release note più lunga", f"{note['tag']}{repo_info} ({note['length']} caratteri, {note['word_count']} parole)")
if content_metrics.get("release_piu_emotiva"):
emoji = content_metrics["release_piu_emotiva"]
repo_info = f" ({emoji.get('repo_full_name', '')})" if emoji.get('repo_full_name') else ""
table_content.add_row("Release più emotiva", f"{emoji['tag']}{repo_info} ({emoji['emoji_count']} emoji)")
if content_metrics.get("parole_piu_usate"):
words = content_metrics["parole_piu_usate"]
top_words_str = ", ".join([f"{k} ({v})" for k, v in list(words.items())[:5]])
table_content.add_row("Parole più usate", top_words_str)
if content_metrics.get("release_piu_commit"):
commit = content_metrics["release_piu_commit"]
repo_info = f" ({commit.get('repo_full_name', '')})" if commit.get('repo_full_name') else ""
table_content.add_row("Release con più commit", f"{commit['tag']}{repo_info} ({commit['commit_count']} commit)")
if content_metrics.get("release_piu_autori"):
autori = content_metrics["release_piu_autori"]
repo_info = f" ({autori.get('repo_full_name', '')})" if autori.get('repo_full_name') else ""
table_content.add_row("Release con più autori", f"{autori['tag']}{repo_info} ({autori['author_count']} autori)")
console.print(table_content)
console.print()
# Metriche di collaborazione
collab_metrics = results.get("metriche_collaborazione", {})
if collab_metrics:
table_collab = Table(title="👥 Metriche di Collaborazione", show_header=True, header_style="bold yellow")
table_collab.add_column("Metrica", style="cyan")
table_collab.add_column("Valore", style="green")
if collab_metrics.get("autore_piu_frequente"):
autore = collab_metrics["autore_piu_frequente"]
table_collab.add_row("Chi ha rilasciato di più", f"{autore['username']} ({autore['count']} release)")
if collab_metrics.get("release_piu_collaborativa"):
collab = collab_metrics["release_piu_collaborativa"]
repo_info = f" ({collab.get('repo_full_name', '')})" if collab.get('repo_full_name') else ""
table_collab.add_row("Release più collaborativa", f"{collab['tag']}{repo_info} ({collab['author_count']} autori)")
table_collab.add_row("Release solitarie", str(collab_metrics.get("release_solitario", 0)))
table_collab.add_row("Release collaborative", str(collab_metrics.get("release_collaborative", 0)))
console.print(table_collab)
console.print()
# Metriche tecniche
tech_metrics = results.get("metriche_tecniche", {})
if tech_metrics:
table_tech = Table(title="⚙️ Metriche Tecniche", show_header=True, header_style="bold yellow")
table_tech.add_column("Metrica", style="cyan")
table_tech.add_column("Valore", style="green")
if tech_metrics.get("release_piu_rischiosa"):
risk = tech_metrics["release_piu_rischiosa"]
repo_info = f" ({risk.get('repo_full_name', '')})" if risk.get('repo_full_name') else ""
table_tech.add_row("Release più rischiosa (più file)", f"{risk['tag']}{repo_info} ({risk['file_count']} file)")
if tech_metrics.get("release_piu_pulita"):
clean = tech_metrics["release_piu_pulita"]
repo_info = f" ({clean.get('repo_full_name', '')})" if clean.get('repo_full_name') else ""
table_tech.add_row("Release più pulita (meno file)", f"{clean['tag']}{repo_info} ({clean['file_count']} file)")
table_tech.add_row("Release con breaking changes", str(tech_metrics.get("count_breaking_changes", 0)))
console.print(table_tech)
def export_json(results: Dict, filename: str):
"""Esporta i risultati in formato JSON."""
with open(filename, 'w', encoding='utf-8') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
console.print(f"[green]✓[/green] Risultati esportati in [cyan]{filename}[/cyan]")
def parse_repo_list(repos_input: Optional[str], repos_file: Optional[str]) -> Optional[List[str]]:
"""Parsa la lista di repository da stringa o file."""
repo_list = []
# Leggi da file se specificato
if repos_file:
try:
with open(repos_file, 'r', encoding='utf-8') as f:
repo_list = [line.strip() for line in f if line.strip() and not line.strip().startswith('#')]
console.print(f"[dim]Letti {len(repo_list)} repository dal file {repos_file}[/dim]")
except FileNotFoundError:
console.print(f"[bold red]Errore:[/bold red] File non trovato: {repos_file}")
sys.exit(1)
except Exception as e:
console.print(f"[bold red]Errore:[/bold red] Impossibile leggere il file {repos_file}: {e}")
sys.exit(1)
# Aggiungi repository dalla stringa se specificata
if repos_input:
repos_from_string = [r.strip() for r in repos_input.split(',') if r.strip()]
repo_list.extend(repos_from_string)
# Rimuovi duplicati mantenendo l'ordine
if repo_list:
seen = set()
unique_list = []
for repo in repo_list:
repo_lower = repo.lower()
if repo_lower not in seen:
seen.add(repo_lower)
unique_list.append(repo)
return unique_list
return None
@click.command()
@click.option("--org", required=True, help="Organizzazione GitHub")
@click.option("--repos", help="Lista di repository da analizzare (separati da virgola, es: repo1,repo2,repo3)")
@click.option("--repos-file", help="File con lista di repository da analizzare (un repository per riga, righe vuote e commenti con # vengono ignorati)")
@click.option("--from-date", callback=lambda ctx, param, value: validate_date(value) if value else None, help="Data inizio filtro (YYYY-MM-DD) - opzionale")
@click.option("--to-date", callback=lambda ctx, param, value: validate_date(value) if value else None, help="Data fine filtro (YYYY-MM-DD) - opzionale")
@click.option("--token", help="Token GitHub (alternativa a GITHUB_TOKEN env var)")
@click.option("--output", type=click.Choice(["table", "json"], case_sensitive=False), default="table", help="Formato di output")
@click.option("--export", help="File di esportazione (solo per JSON)")
@click.option("--verbose", "-v", is_flag=True, help="Mostra informazioni dettagliate")
def main(org, repos, repos_file, from_date, to_date, token, output, export, verbose):
"""
Analizza le release di tutti i repository di un'organizzazione GitHub e calcola metriche complete.
Include metriche temporali, di contenuto, di collaborazione e tecniche.
Puoi specificare una lista di repository da analizzare usando --repos (separati da virgola)
o --repos-file (file con un repository per riga).
"""
session = get_github_session(token)
# Parsa la lista di repository se specificata
repo_filter = parse_repo_list(repos, repos_file)
# Ottieni tutte le release di tutti i repository dell'organizzazione (o solo quelli filtrati)
all_releases = get_all_releases_for_org(session, org, repo_filter, verbose)
if not all_releases:
console.print("[yellow]Nessuna release trovata nell'organizzazione.[/yellow]")
return
# Filtra per periodo se specificato
if from_date and to_date:
releases = filter_releases_by_date(all_releases, from_date, to_date, verbose)
console.print(f"[dim]Filtrate {len(releases)} release nel periodo {from_date} - {to_date}[/dim]")
# Debug: mostra alcune date delle release per capire il problema
if verbose and len(releases) == 0 and len(all_releases) > 0:
console.print("[yellow]Debug: Prime 5 release trovate (per verificare formato date):[/yellow]")
for i, rel in enumerate(all_releases[:5]):
pub_at = rel.get("published_at", "N/A")
tag = rel.get("tag_name", "N/A")
repo = rel.get("repo_full_name", "N/A")
console.print(f" {i+1}. {tag} ({repo}): {pub_at}")
else:
releases = all_releases
if not releases:
console.print("[yellow]Nessuna release nel periodo specificato.[/yellow]")
return
# Analizza le release
results = analyze_releases(session, releases, verbose)
# Output
if output == "json":
if export:
export_json(results, export)
else:
console.print(json.dumps(results, indent=2, ensure_ascii=False))
else: # table
print_results(results, org)
if export:
export_json(results, export)
if __name__ == "__main__":
main()