-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbug_analytics.py
More file actions
693 lines (589 loc) · 26.3 KB
/
bug_analytics.py
File metadata and controls
693 lines (589 loc) · 26.3 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
import os
import sys
import json
import csv
from datetime import datetime
from typing import List, Dict, Optional
import requests
import click
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.table import Table
from rich.panel import Panel
GITHUB_API_URL = "https://api.github.com"
console = Console()
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": "bug-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 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
def has_bug_label(item: Dict) -> bool:
"""Verifica se un'issue ha la label 'bug' (case-insensitive)."""
labels = item.get("labels", [])
for label in labels:
if label.get("name", "").lower() == "bug":
return True
return False
def search_issues(
session,
org: str,
from_date: str,
to_date: str,
is_bug: Optional[bool] = None,
repos: Optional[List[str]] = None,
verbose: bool = False
):
"""
Cerca issues nell'organizzazione nel periodo specificato.
Args:
session: Sessione GitHub autenticata
org: Nome dell'organizzazione
from_date: Data inizio (YYYY-MM-DD)
to_date: Data fine (YYYY-MM-DD)
is_bug: True per bug, False per non-bug, None per tutte
repos: Lista opzionale di repository da filtrare (es: ["repo1", "repo2"])
verbose: Mostra informazioni dettagliate
"""
all_items = []
# Se ci sono repository specificati, cerca per ogni repository separatamente
# La GitHub Search API non supporta OR diretto tra repository
repos_to_search = repos if repos else [None] # None significa tutti i repository
for repo in repos_to_search:
# Costruisce la query base per issues (non PR)
# Cerchiamo tutte le issues e poi filtriamo per label nel codice
# Questo è più affidabile perché -label:bug può escludere issues senza labels
query_parts = [
f"org:{org}",
"is:issue",
f"created:{from_date}..{to_date}"
]
# Aggiungi filtro repository se specificato
if repo:
query_parts.append(f"repo:{org}/{repo}")
# Se cerchiamo solo bug, possiamo usare il filtro label nella query per efficienza
if is_bug is True:
query_parts.append("label:bug")
query = " ".join(query_parts)
if verbose:
repo_info = f" in {repo}" if repo else ""
console.print(f"[dim]Query di ricerca{repo_info}:[/dim] {query}")
page = 1
per_page = 100
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
disable=not verbose
) as progress:
task_type = "bug" if is_bug is True else ("non-bug" if is_bug is False else "issues")
repo_desc = f" in {repo}" if repo else ""
task = progress.add_task(f"Cercando {task_type}{repo_desc}...", total=None)
while True:
params = {
"q": query,
"per_page": per_page,
"page": page,
}
resp = session.get(f"{GITHUB_API_URL}/search/issues", params=params)
if resp.status_code == 403:
console.print("[bold red]Errore:[/bold red] Rate limit raggiunto o permessi insufficienti")
console.print(f"[dim]Status: {resp.status_code}[/dim]")
if "rate limit" in resp.text.lower():
console.print("[yellow]Suggerimento:[/yellow] Attendi qualche minuto e riprova")
sys.exit(1)
if resp.status_code != 200:
console.print(f"[bold red]Errore nella chiamata alla Search API:[/bold red]")
console.print(f"Status: {resp.status_code}")
console.print(f"Risposta: {resp.text}")
sys.exit(1)
data = resp.json()
items = data.get("items", [])
if not items:
break
# Se non stiamo filtrando per bug nella query, filtriamo nel codice
if is_bug is False:
items = [item for item in items if not has_bug_label(item)]
elif is_bug is None:
# Non filtriamo, prendiamo tutte
pass
all_items.extend(items)
if verbose:
progress.update(task, description=f"Trovate {len(all_items)} {task_type}...")
# Se abbiamo meno di per_page elementi, non ci sono altre pagine
if len(items) < per_page:
break
page += 1
if verbose:
task_type = "bug" if is_bug is True else ("non-bug" if is_bug is False else "issues")
console.print(f"[green]✓[/green] Trovate [bold]{len(all_items)}[/bold] {task_type} create nel periodo.")
return all_items
def search_merged_prs(
session,
org: str,
from_date: str,
to_date: str,
is_bug: Optional[bool] = None,
repos: Optional[List[str]] = None,
verbose: bool = False
):
"""
Cerca PR merged con/senza label bug nel periodo specificato.
Args:
session: Sessione GitHub autenticata
org: Nome dell'organizzazione
from_date: Data inizio (YYYY-MM-DD)
to_date: Data fine (YYYY-MM-DD)
is_bug: True per bug (label:bug), False per non-bug (-label:bug), None per tutte
repos: Lista opzionale di repository da filtrare (es: ["repo1", "repo2"])
verbose: Mostra informazioni dettagliate
"""
all_items = []
# Se ci sono repository specificati, cerca per ogni repository separatamente
# La GitHub Search API non supporta OR diretto tra repository
repos_to_search = repos if repos else [None] # None significa tutti i repository
for repo in repos_to_search:
# Costruisce la query per PR merged
query_parts = [
f"org:{org}",
"is:pr",
"is:merged",
f"merged:{from_date}..{to_date}"
]
# Aggiungi filtro repository se specificato
if repo:
query_parts.append(f"repo:{org}/{repo}")
# Filtra per label bug o non-bug
if is_bug is True:
query_parts.append("label:bug")
elif is_bug is False:
query_parts.append("-label:bug")
query = " ".join(query_parts)
if verbose:
repo_info = f" in {repo}" if repo else ""
console.print(f"[dim]Query di ricerca{repo_info}:[/dim] {query}")
page = 1
per_page = 100
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
disable=not verbose
) as progress:
task_type = "bug" if is_bug is True else ("non-bug" if is_bug is False else "PR")
repo_desc = f" in {repo}" if repo else ""
task = progress.add_task(f"Cercando PR merged ({task_type}){repo_desc}...", total=None)
while True:
params = {
"q": query,
"per_page": per_page,
"page": page,
}
resp = session.get(f"{GITHUB_API_URL}/search/issues", params=params)
if resp.status_code == 403:
console.print("[bold red]Errore:[/bold red] Rate limit raggiunto o permessi insufficienti")
console.print(f"[dim]Status: {resp.status_code}[/dim]")
if "rate limit" in resp.text.lower():
console.print("[yellow]Suggerimento:[/yellow] Attendi qualche minuto e riprova")
sys.exit(1)
if resp.status_code != 200:
console.print(f"[bold red]Errore nella chiamata alla Search API:[/bold red]")
console.print(f"Status: {resp.status_code}")
console.print(f"Risposta: {resp.text}")
sys.exit(1)
data = resp.json()
items = data.get("items", [])
if not items:
break
# Se non stiamo filtrando per bug nella query, filtriamo nel codice
if is_bug is False:
items = [item for item in items if not has_bug_label(item)]
elif is_bug is None:
# Non filtriamo, prendiamo tutte
pass
all_items.extend(items)
if verbose:
progress.update(task, description=f"Trovate {len(all_items)} PR merged ({task_type})...")
# Se abbiamo meno di per_page elementi, non ci sono altre pagine
if len(items) < per_page:
break
page += 1
if verbose:
task_type = "bug" if is_bug is True else ("non-bug" if is_bug is False else "PR")
console.print(f"[green]✓[/green] Trovate [bold]{len(all_items)}[/bold] PR merged ({task_type}) nel periodo.")
return all_items
def analyze_issues(
session,
org: str,
from_date: str,
to_date: str,
repos: Optional[List[str]] = None,
only_bugs: bool = False,
verbose: bool = False
) -> Dict:
"""
Analizza bug e non-bug aperti e risolti nel periodo specificato.
Args:
session: Sessione GitHub autenticata
org: Nome dell'organizzazione
from_date: Data inizio (YYYY-MM-DD)
to_date: Data fine (YYYY-MM-DD)
repos: Lista opzionale di repository da filtrare
only_bugs: Se True, cerca solo i bug (per ridurre chiamate API)
verbose: Mostra informazioni dettagliate
"""
if verbose:
if repos:
console.print(f"[cyan]Analizzando {len(repos)} repository specifici...[/cyan]")
if only_bugs:
console.print("[yellow]Modalità ottimizzata: cercando solo i bug per ridurre le chiamate API[/yellow]")
console.print("[cyan]Fase 1: Cercando bug aperti...[/cyan]")
# Cerca bug aperti nel periodo
bug_aperti = search_issues(session, org, from_date, to_date, is_bug=True, repos=repos, verbose=verbose)
# Cerca non-bug solo se only_bugs è False
if only_bugs:
if verbose:
console.print("[dim]Saltando ricerca non-bug (modalità ottimizzata con repository specifici)[/dim]")
non_bug_aperti = []
else:
if verbose:
console.print("[cyan]Fase 2: Cercando non-bug aperti...[/cyan]")
# Cerca non-bug aperti nel periodo
non_bug_aperti = search_issues(session, org, from_date, to_date, is_bug=False, repos=repos, verbose=verbose)
if verbose:
console.print("[cyan]Fase 3: Cercando bug risolti (PR merged con label bug)...[/cyan]")
# Cerca bug risolti (PR merged con label bug) nel periodo
bug_chiusi = search_merged_prs(session, org, from_date, to_date, is_bug=True, repos=repos, verbose=verbose)
# Cerca non-bug risolti solo se only_bugs è False
if only_bugs:
if verbose:
console.print("[dim]Saltando ricerca non-bug risolti (modalità ottimizzata con repository specifici)[/dim]")
non_bug_chiusi = []
else:
if verbose:
console.print("[cyan]Fase 4: Cercando non-bug risolti (PR merged senza label bug)...[/cyan]")
# Cerca non-bug risolti (PR merged senza label bug) nel periodo
non_bug_chiusi = search_merged_prs(session, org, from_date, to_date, is_bug=False, repos=repos, verbose=verbose)
if verbose:
console.print(f"[dim]Bug aperti trovati: {len(bug_aperti)}[/dim]")
console.print(f"[dim]Non-bug aperti trovati: {len(non_bug_aperti)}[/dim]")
console.print(f"[dim]Bug chiusi trovati: {len(bug_chiusi)}[/dim]")
console.print(f"[dim]Non-bug chiusi trovati: {len(non_bug_chiusi)}[/dim]")
# Filtra le issues aperte: solo quelle create nel periodo che sono ancora aperte
# Le issues chiuse nel periodo vengono conteggiate solo come "risolte"
bug_aperti_filtrati = [
item for item in bug_aperti
if item["state"] == "open"
]
non_bug_aperti_filtrati = [
item for item in non_bug_aperti
if item["state"] == "open"
]
if verbose:
console.print(f"[dim]Bug aperti ancora aperti: {len(bug_aperti_filtrati)}[/dim]")
console.print(f"[dim]Non-bug aperti ancora aperti: {len(non_bug_aperti_filtrati)}[/dim]")
# Prepara i dati per il risultato
def format_issue(item):
labels = [label["name"] for label in item.get("labels", [])]
repo = item.get("repository_url", "").split("/")[-1] if item.get("repository_url") else ""
# Per le PR merged, usiamo merged_at invece di closed_at
merged_at = item.get("pull_request", {}).get("merged_at", "") if item.get("pull_request") else ""
return {
"number": item["number"],
"title": item["title"],
"url": item.get("html_url", ""),
"repo": repo,
"state": item["state"],
"created_at": item.get("created_at", ""),
"closed_at": merged_at or item.get("closed_at", ""),
"merged_at": merged_at,
"labels": labels
}
def format_pr(item):
"""Formatta una PR come se fosse un'issue per compatibilità."""
labels = [label["name"] for label in item.get("labels", [])]
repo = item.get("repository_url", "").split("/")[-1] if item.get("repository_url") else ""
merged_at = item.get("pull_request", {}).get("merged_at", "") if item.get("pull_request") else ""
return {
"number": item["number"],
"title": item["title"],
"url": item.get("html_url", ""),
"repo": repo,
"state": "closed" if merged_at else item.get("state", ""),
"created_at": item.get("created_at", ""),
"closed_at": merged_at,
"merged_at": merged_at,
"labels": labels
}
return {
"bug": {
"aperti": [format_issue(item) for item in bug_aperti_filtrati],
"risolti": [format_pr(item) for item in bug_chiusi],
"totale_aperti": len(bug_aperti_filtrati),
"totale_risolti": len(bug_chiusi)
},
"non_bug": {
"aperti": [format_issue(item) for item in non_bug_aperti_filtrati],
"risolti": [format_pr(item) for item in non_bug_chiusi],
"totale_aperti": len(non_bug_aperti_filtrati),
"totale_risolti": len(non_bug_chiusi)
},
"periodo": {
"da": from_date,
"a": to_date
}
}
def print_table_results(results: Dict, show_details: bool = True):
"""Stampa i risultati in formato tabella."""
table = Table(title="Analisi Bug e Non-Bug", show_header=True, header_style="bold magenta")
table.add_column("Categoria", style="cyan", no_wrap=True)
table.add_column("Aperti", justify="right", style="yellow")
table.add_column("Risolti", justify="right", style="green")
table.add_column("Totale", justify="right", style="bold")
bug_aperti = results["bug"]["totale_aperti"]
bug_risolti = results["bug"]["totale_risolti"]
bug_totale = bug_aperti + bug_risolti
non_bug_aperti = results["non_bug"]["totale_aperti"]
non_bug_risolti = results["non_bug"]["totale_risolti"]
non_bug_totale = non_bug_aperti + non_bug_risolti
table.add_row(
"[bold red]Bug[/bold red]",
str(bug_aperti),
str(bug_risolti),
f"[bold]{bug_totale}[/bold]"
)
table.add_row(
"[bold blue]Non-Bug[/bold blue]",
str(non_bug_aperti),
str(non_bug_risolti),
f"[bold]{non_bug_totale}[/bold]"
)
table.add_row(
"[bold]Totale[/bold]",
f"[bold]{bug_aperti + non_bug_aperti}[/bold]",
f"[bold]{bug_risolti + non_bug_risolti}[/bold]",
f"[bold]{bug_totale + non_bug_totale}[/bold]"
)
console.print()
console.print(table)
console.print(f"[dim]Periodo: {results['periodo']['da']} - {results['periodo']['a']}[/dim]")
if show_details:
console.print()
if results["bug"]["aperti"]:
console.print(Panel.fit(
"\n".join([
f"#{issue['number']} - {issue['title']} ({issue['repo']})"
for issue in results["bug"]["aperti"]
]),
title="[yellow]Bug Aperti[/yellow]",
border_style="yellow"
))
if results["bug"]["risolti"]:
console.print()
console.print(Panel.fit(
"\n".join([
f"#{issue['number']} - {issue['title']} ({issue['repo']})"
for issue in results["bug"]["risolti"]
]),
title="[green]Bug Risolti[/green]",
border_style="green"
))
if results["non_bug"]["aperti"]:
console.print()
console.print(Panel.fit(
"\n".join([
f"#{issue['number']} - {issue['title']} ({issue['repo']})"
for issue in results["non_bug"]["aperti"]
]),
title="[yellow]Non-Bug Aperti[/yellow]",
border_style="yellow"
))
if results["non_bug"]["risolti"]:
console.print()
console.print(Panel.fit(
"\n".join([
f"#{issue['number']} - {issue['title']} ({issue['repo']})"
for issue in results["non_bug"]["risolti"]
]),
title="[green]Non-Bug Risolti[/green]",
border_style="green"
))
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 export_csv(results: Dict, filename: str):
"""Esporta i risultati in formato CSV."""
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow([
"Tipo", "Stato", "Numero", "Titolo", "Repository", "URL",
"Data Creazione", "Data Chiusura", "Labels"
])
for issue in results["bug"]["aperti"]:
writer.writerow([
"Bug",
"Aperto",
issue["number"],
issue["title"],
issue["repo"],
issue["url"],
issue["created_at"],
issue["closed_at"],
", ".join(issue["labels"])
])
for issue in results["bug"]["risolti"]:
writer.writerow([
"Bug",
"Risolto",
issue["number"],
issue["title"],
issue["repo"],
issue["url"],
issue["created_at"],
issue["closed_at"],
", ".join(issue["labels"])
])
for issue in results["non_bug"]["aperti"]:
writer.writerow([
"Non-Bug",
"Aperto",
issue["number"],
issue["title"],
issue["repo"],
issue["url"],
issue["created_at"],
issue["closed_at"],
", ".join(issue["labels"])
])
for issue in results["non_bug"]["risolti"]:
writer.writerow([
"Non-Bug",
"Risolto",
issue["number"],
issue["title"],
issue["repo"],
issue["url"],
issue["created_at"],
issue["closed_at"],
", ".join(issue["labels"])
])
console.print(f"[green]✓[/green] Risultati esportati in [cyan]{filename}[/cyan]")
@click.command()
@click.option("--org", required=True, help="Organizzazione GitHub (es. Gamindo)")
@click.option("--from-date", required=True, callback=lambda ctx, param, value: validate_date(value) if value else None, help="Data inizio (YYYY-MM-DD)")
@click.option("--to-date", required=True, callback=lambda ctx, param, value: validate_date(value) if value else None, help="Data fine (YYYY-MM-DD)")
@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("--all-types", is_flag=True, help="Cerca sia bug che non-bug anche con repository specificati (default: solo bug con --repos)")
@click.option("--token", help="Token GitHub (alternativa a GITHUB_TOKEN env var)")
@click.option("--output", type=click.Choice(["table", "json", "csv"], case_sensitive=False), default="table", help="Formato di output")
@click.option("--export", help="File di esportazione (solo per JSON/CSV)")
@click.option("--verbose", "-v", is_flag=True, help="Mostra informazioni dettagliate")
@click.option("--no-details", is_flag=True, help="Non mostrare il dettaglio delle issues")
def main(org, from_date, to_date, repos, repos_file, all_types, token, output, export, verbose, no_details):
"""
Analizza bug e non-bug aperti e risolti in un'organizzazione GitHub nel periodo specificato.
Le issues sono classificate come "bug" se hanno la label "bug", altrimenti come "non-bug".
Puoi filtrare per repository specifici usando --repos o --repos-file. Se non specificato,
analizza tutti i repository dell'organizzazione.
NOTA: Quando specifichi repository con --repos o --repos-file, per default cerca solo i bug
per ridurre le chiamate API e evitare rate limit. Usa --all-types per cercare anche i non-bug.
"""
session = get_github_session(token)
# Parsa la lista di repository se specificata
repo_list = parse_repo_list(repos, repos_file)
if verbose:
console.print(f"[cyan]Analisi issues per organizzazione:[/cyan] {org}")
console.print(f"[cyan]Periodo:[/cyan] {from_date} - {to_date}")
if repo_list:
console.print(f"[cyan]Repository da analizzare:[/cyan] {len(repo_list)} ({', '.join(repo_list[:5])}{'...' if len(repo_list) > 5 else ''})")
if not all_types:
console.print("[yellow]Modalità ottimizzata: cercando solo i bug (usa --all-types per cercare anche i non-bug)[/yellow]")
else:
console.print(f"[cyan]Repository:[/cyan] Tutti i repository dell'organizzazione")
console.print()
# Determina se cercare solo i bug: solo se ci sono repository specificati E all_types è False
only_bugs = repo_list is not None and len(repo_list) > 0 and not all_types
results = analyze_issues(
session,
org=org,
from_date=from_date,
to_date=to_date,
repos=repo_list,
only_bugs=only_bugs,
verbose=verbose
)
# Output
if output == "json":
if export:
export_json(results, export)
else:
console.print(json.dumps(results, indent=2, ensure_ascii=False))
elif output == "csv":
if not export:
export = "bug_results.csv"
export_csv(results, export)
else: # table
print_table_results(results, show_details=not no_details)
if export:
if export.endswith('.json'):
export_json(results, export)
elif export.endswith('.csv'):
export_csv(results, export)
else:
console.print("[yellow]Formato file non riconosciuto. Usa .json o .csv[/yellow]")
if __name__ == "__main__":
main()