-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
1721 lines (1496 loc) · 85.6 KB
/
report.py
File metadata and controls
1721 lines (1496 loc) · 85.6 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
# report.py
"""
Funciones para generación de reportes HTML
"""
import os
import html as html_module
from collections import defaultdict
import datetime
import subprocess
from utils import COMMON_CSS, percentage, bar_width, percentage_value
# --- Función para mostrar rutas relativas ---
def display_fp(fp):
try:
KERNEL_SUBDIR = os.path.join("../../src/kernel/linux")
return os.path.relpath(fp, KERNEL_SUBDIR)
except Exception:
return fp
def generate_html_report(report_data, html_file, kernel_dir="."):
# ...existing code...
# --- Contadores globales sobre incidencias fijadas y saltadas ---
files_with_errors = {f for f, issues in report_data.items() if any(i.get("fixed") for i in issues.get("error", []))}
files_with_warnings = {f for f, issues in report_data.items() if any(i.get("fixed") for i in issues.get("warning", []))}
files_with_errors_skipped = {f for f, issues in report_data.items() if any(not i.get("fixed") for i in issues.get("error", []))}
files_with_warnings_skipped = {f for f, issues in report_data.items() if any(not i.get("fixed") for i in issues.get("warning", []))}
total_files_count = len(files_with_errors | files_with_warnings)
occ_errors_fixed = sum(1 for issues in report_data.values() for i in issues.get("error", []) if i.get("fixed"))
occ_warnings_fixed = sum(1 for issues in report_data.values() for i in issues.get("warning", []) if i.get("fixed"))
occ_errors_skipped = sum(1 for issues in report_data.values() for i in issues.get("error", []) if not i.get("fixed"))
occ_warnings_skipped = sum(1 for issues in report_data.values() for i in issues.get("warning", []) if not i.get("fixed"))
total_occ_count = occ_errors_fixed + occ_warnings_fixed
PCT_CELL_WIDTH = 220
html_out = []
append = html_out.append
timestamp = datetime.datetime.now().strftime("%H:%M:%S %d/%m/%Y")
# --- Header y CSS ---
append("<!doctype html><html><head><meta charset='utf-8'>")
append("<style>")
append(COMMON_CSS)
append("</style></head><body>")
append(f"<h1>Informe Checkpatch Autofix <span style='font-weight:normal'>{timestamp}</span></h1>")
# --- Tabla resumen global ---
append("<h2>Resumen global</h2>")
append("<table>")
append(f"<tr><th>Estado</th><th>Ficheros</th><th style='width:{PCT_CELL_WIDTH}px;'>% Ficheros</th>"
f"<th>Casos</th><th style='width:{PCT_CELL_WIDTH}px;'>% Casos</th></tr>")
# Calcular totales antes del loop
# Totales por categoría
f_count_errors_total = len(files_with_errors | files_with_errors_skipped)
o_count_errors_total = occ_errors_fixed + occ_errors_skipped
f_count_warnings_total = len(files_with_warnings | files_with_warnings_skipped)
o_count_warnings_total = occ_warnings_fixed + occ_warnings_skipped
# Totales generales
total_files_all = len(files_with_errors | files_with_warnings | files_with_errors_skipped | files_with_warnings_skipped)
total_occ_all = o_count_errors_total + o_count_warnings_total
# Errores corregidos (% respecto a errores procesados)
f_count = len(files_with_errors)
o_count = occ_errors_fixed
f_pct = percentage(f_count, f_count_errors_total)
o_pct = percentage(o_count, o_count_errors_total)
f_bar = bar_width(f_count, f_count_errors_total, max_width=PCT_CELL_WIDTH - 50)
o_bar = bar_width(o_count, o_count_errors_total, max_width=PCT_CELL_WIDTH - 50)
append(f"<tr><td class='errors'>ERRORES CORREGIDOS</td>"
f"<td class='num'>{f_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{f_bar}px'></div></div></td>"
f"<td class='num'>{o_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{o_bar}px'></div></div></td></tr>")
# Errores saltados (% respecto a errores procesados)
f_count = len(files_with_errors_skipped)
o_count = occ_errors_skipped
f_pct = percentage(f_count, f_count_errors_total)
o_pct = percentage(o_count, o_count_errors_total)
f_bar = bar_width(f_count, f_count_errors_total, max_width=PCT_CELL_WIDTH - 50)
o_bar = bar_width(o_count, o_count_errors_total, max_width=PCT_CELL_WIDTH - 50)
append(f"<tr><td class='errors'>ERRORES SALTADOS</td>"
f"<td class='num'>{f_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{f_bar}px'></div></div></td>"
f"<td class='num'>{o_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{o_bar}px'></div></div></td></tr>")
# Errores procesados (subtotal) - 100%
f_pct = "100.0%"
o_pct = "100.0%"
f_bar = PCT_CELL_WIDTH - 50
o_bar = PCT_CELL_WIDTH - 50
append(f"<tr><td class='errors' style='font-weight:bold'>ERRORES PROCESADOS</td>"
f"<td class='num' style='font-weight:bold'>{f_count_errors_total}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{f_bar}px'></div></div></td>"
f"<td class='num' style='font-weight:bold'>{o_count_errors_total}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{o_bar}px'></div></div></td></tr>")
# Warnings corregidos (% respecto a warnings procesados)
f_count = len(files_with_warnings)
o_count = occ_warnings_fixed
f_pct = percentage(f_count, f_count_warnings_total)
o_pct = percentage(o_count, o_count_warnings_total)
f_bar = bar_width(f_count, f_count_warnings_total, max_width=PCT_CELL_WIDTH - 50)
o_bar = bar_width(o_count, o_count_warnings_total, max_width=PCT_CELL_WIDTH - 50)
append(f"<tr><td class='warnings'>WARNINGS CORREGIDOS</td>"
f"<td class='num'>{f_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{f_bar}px'></div></div></td>"
f"<td class='num'>{o_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{o_bar}px'></div></div></td></tr>")
# Warnings saltados (% respecto a warnings procesados)
f_count = len(files_with_warnings_skipped)
o_count = occ_warnings_skipped
f_pct = percentage(f_count, f_count_warnings_total)
o_pct = percentage(o_count, o_count_warnings_total)
f_bar = bar_width(f_count, f_count_warnings_total, max_width=PCT_CELL_WIDTH - 50)
o_bar = bar_width(o_count, o_count_warnings_total, max_width=PCT_CELL_WIDTH - 50)
append(f"<tr><td class='warnings'>WARNINGS SALTADOS</td>"
f"<td class='num'>{f_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{f_bar}px'></div></div></td>"
f"<td class='num'>{o_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{o_bar}px'></div></div></td></tr>")
# Warnings procesados (subtotal) - 100%
f_pct = "100.0%"
o_pct = "100.0%"
f_bar = PCT_CELL_WIDTH - 50
o_bar = PCT_CELL_WIDTH - 50
append(f"<tr><td class='warnings' style='font-weight:bold'>WARNINGS PROCESADOS</td>"
f"<td class='num' style='font-weight:bold'>{f_count_warnings_total}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{f_bar}px'></div></div></td>"
f"<td class='num' style='font-weight:bold'>{o_count_warnings_total}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{o_bar}px'></div></div></td></tr>")
# Total corregidos (% respecto al total general)
f_count_corrected = len(files_with_errors | files_with_warnings)
o_count_corrected = occ_errors_fixed + occ_warnings_fixed
f_pct = percentage(f_count_corrected, total_files_all)
o_pct = percentage(o_count_corrected, total_occ_all)
f_bar = bar_width(f_count_corrected, total_files_all, max_width=PCT_CELL_WIDTH - 50)
o_bar = bar_width(o_count_corrected, total_occ_all, max_width=PCT_CELL_WIDTH - 50)
append(f"<tr style='background:#e3f2fd'><td class='total' style='color:#1976d2'>TOTAL CORREGIDOS</td>"
f"<td class='num'>{f_count_corrected}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner' style='background:#42a5f5; width:{f_bar}px'></div></div></td>"
f"<td class='num'>{o_count_corrected}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner' style='background:#42a5f5; width:{o_bar}px'></div></div></td></tr>")
# Total saltados (% respecto al total general)
f_count_skipped = len(files_with_errors_skipped | files_with_warnings_skipped)
o_count_skipped = occ_errors_skipped + occ_warnings_skipped
f_pct = percentage(f_count_skipped, total_files_all)
o_pct = percentage(o_count_skipped, total_occ_all)
f_bar = bar_width(f_count_skipped, total_files_all, max_width=PCT_CELL_WIDTH - 50)
o_bar = bar_width(o_count_skipped, total_occ_all, max_width=PCT_CELL_WIDTH - 50)
append(f"<tr style='background:#e3f2fd'><td class='total' style='color:#1976d2'>TOTAL SALTADOS</td>"
f"<td class='num' style='font-weight:bold'>{f_count_skipped}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner' style='background:#bdbdbd; width:{f_bar}px'></div></div></td>"
f"<td class='num'>{o_count_skipped}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner' style='background:#42a5f5; width:{o_bar}px'></div></div></td></tr>")
# Fila TOTAL - 100%
f_pct = "100.0%"
o_pct = "100.0%"
f_bar = PCT_CELL_WIDTH - 50
o_bar = PCT_CELL_WIDTH - 50
append(f"<tr style='background:#e3f2fd'><td class='total' style='color:#1976d2; font-weight:bold'>TOTAL</td>"
f"<td class='num' style='font-weight:bold'>{total_files_all}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner' style='background:#42a5f5; width:{f_bar}px'></div></div></td>"
f"<td class='num' style='font-weight:bold'>{total_occ_all}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none; font-weight:bold'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner' style='background:#42a5f5; width:{f_bar}px'></div></div></td></tr>")
append("</table>")
# Nota sobre correcciones indirectas
append("<div style='margin: 15px 0; padding: 12px; background: #e3f2fd; border-left: 4px solid #2196F3; border-radius: 4px;'>")
append("<strong>ℹ️ Nota:</strong> Algunos errores pueden corregirse indirectamente como efecto secundario de otras transformaciones. ")
append("Por ejemplo, al transformar <code>simple_strtoul(str,NULL,0)</code> a <code>kstrtoul(str, NULL, 0)</code>, ")
append("también se corrigen automáticamente los errores de espaciado alrededor de las comas. ")
append("El contador de 'errores corregidos' refleja las correcciones directas aplicadas.")
append("</div>")
# --- Preparar datos por motivo ---
error_reason_files = defaultdict(list)
warning_reason_files = defaultdict(list)
for f, issues in report_data.items():
for e in issues.get("error", []):
if e.get("fixed"):
error_reason_files[e.get("message", "UNKNOWN")].append(f)
for w in issues.get("warning", []):
if w.get("fixed"):
warning_reason_files[w.get("message", "UNKNOWN")].append(f)
# --- Función para escribir tabla de motivos ---
def write_reason_table(reason_files_dict, typ):
cls = "errors" if typ=="error" else "warnings"
section_title = "Errores" if typ=="error" else "Warnings"
# total de casos
total_cases = sum(len(files) for files in reason_files_dict.values())
# total de ficheros únicos que contienen al menos un motivo
total_files = len(set(f for files in reason_files_dict.values() for f in files))
append(f"<h3 class='{cls}'>{section_title}</h3>")
append(f"<table><tr><th>Motivo</th><th>Ficheros</th><th>% Ficheros</th><th>Casos</th><th>% de {typ}s</th></tr>")
for reason, files_list in sorted(reason_files_dict.items(), key=lambda x: -len(x[1])):
count_cases = len(files_list)
count_files = len(set(files_list))
pct_files = percentage(count_files, total_files)
pct_cases = percentage(count_cases, total_cases)
bar_files_len = bar_width(count_files, total_files, max_width=PCT_CELL_WIDTH-50)
bar_cases_len = bar_width(count_cases, total_cases, max_width=PCT_CELL_WIDTH-50)
reason_text = reason
if reason_text.startswith(f"{typ.upper()}: "):
reason_text = reason_text[len(f"{typ.upper()}: "):]
fid = reason.replace("/", "_").replace(" ", "_")
append(f"<tr><td>{html_module.escape(f'{typ.upper()}: {reason_text}')}</td>"
f"<td class='num'>{count_files}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{pct_files}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-{cls}' style='width:{bar_files_len}px'></div></div></td>"
f"<td class='num'><a href='#{fid}'>{count_cases}</a></td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{pct_cases}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-{cls}' style='width:{bar_cases_len}px'></div></div></td></tr>")
append("</table>")
write_reason_table(error_reason_files, "error")
write_reason_table(warning_reason_files, "warning")
# --- Detalle por motivo ---
append("<h2>Detalle por motivo</h2>")
for reason, files_list in {**error_reason_files, **warning_reason_files}.items():
rid = reason.replace("/", "_").replace(" ", "_")
append(f"<h4 id='{rid}' class='errors'>{html_module.escape(reason)} — {len(files_list)} casos</h4><ul>")
file_counts = defaultdict(int)
for fp in files_list:
file_counts[fp] += 1
for fp, cnt in file_counts.items():
append(f"<li><a href='#{fp.replace('/', '_')}'>{display_fp(fp)} ({cnt})</a></li>")
append("</ul>")
# --- Detalle por fichero separado (mejorado: genera diffs desde backups .bak) ---
# helper: escape and format diffs with coloring
def _escape_html(s):
return html_module.escape(s)
def _format_diff_html(diff_text):
if not diff_text or not diff_text.strip():
return '<pre class="diff-pre" style="color:#999;">No changes</pre>'
out = ['<pre class="diff-pre">']
for line in diff_text.split('\n'):
if line.startswith('+++') or line.startswith('---'):
out.append(f'<span style="color:#999; font-weight:bold;">{_escape_html(line)}</span>')
elif line.startswith('@@'):
out.append(f'<span style="color:#2196F3; font-weight:bold;">{_escape_html(line)}</span>')
elif line.startswith('+') and not line.startswith('+++'):
out.append(f'<span style="color:#4CAF50; background:#f1f8f4;">{_escape_html(line)}</span>')
elif line.startswith('-') and not line.startswith('---'):
out.append(f'<span style="color:#f44336; background:#ffe6e6;">{_escape_html(line)}</span>')
else:
out.append(_escape_html(line))
out.append('</pre>')
return '\n'.join(out)
def _get_diff(bak_path, current_path):
try:
res = subprocess.run(['diff', '-u', bak_path, current_path], capture_output=True, text=True)
return res.stdout
except Exception:
return ''
# Aggregate fix stats (for 'Arreglos por Tipo' or summaries)
fix_stats = defaultdict(int)
for f, issues in report_data.items():
for typ in ("error", "warning"):
for i in issues.get(typ, []):
if i.get('fixed'):
rule = i.get('message') or i.get('rule') or 'unknown'
fix_stats[rule] += 1
# Render per-file details using the new style
append(f"<h2>Detalle por fichero</h2>")
for f, issues in sorted(report_data.items(), key=lambda x: x[0]):
# collect fixed entries from both error and warning
entries = [i for typ in ("error", "warning") for i in issues.get(typ, []) if i.get('fixed')]
if not entries:
continue
fid = f.replace('/', '_')
display_name = display_fp(f)
# compute aggregate added/removed lines from available diffs or backups
total_added = 0
total_removed = 0
# try to find a .bak file for the path
bak_path = f + '.bak'
diff_text = None
if os.path.exists(bak_path):
diff_text = _get_diff(bak_path, f)
total_added = len([l for l in diff_text.split('\n') if l.startswith('+') and not l.startswith('+++')])
total_removed = len([l for l in diff_text.split('\n') if l.startswith('-') and not l.startswith('---')])
append(f"<details class='file-detail' id='{fid}'><summary>{_escape_html(display_name)}"
f"<div class='stats'><div class='stat-item'><span class='added'>+{total_added}</span> <span class='removed'>-{total_removed}</span></div>"
f"<span class='fixed-badge'>{sum(1 for _ in entries)} fixes</span></div></summary>")
# show combined diff if available
if diff_text:
append("<div class='detail-content'>")
append(_format_diff_html(diff_text))
append("</div>")
else:
# fallback: show individual small diffs per entry if present in json
append("<div class='detail-content'>")
for e in entries:
dtxt = e.get('diff')
if dtxt:
append(f"<details style='margin-top:6px;'><summary>Diff línea {e.get('line')}</summary>")
append(_format_diff_html(dtxt))
append("</details>")
append("</div>")
append("</details>")
append("</body></html>")
with open(html_file, "w", encoding="utf-8") as f:
f.write("\n".join(html_out))
def summarize_results(report_data, json_file, html_file, kernel_dir="."):
"""
Muestra en consola un resumen de los resultados de fixes aplicados.
"""
# --- Depuración mínima ---
total_issues = sum(len(v.get("error", [])) + len(v.get("warning", [])) for v in report_data.values())
# Contadores
modified_files = 0
errors_fixed = 0
errors_skipped = 0
warnings_fixed = 0
warnings_skipped = 0
for f, issues in report_data.items():
file_modified = any(i.get("fixed") for typ in ["error", "warning"] for i in issues.get(typ, []))
if file_modified:
modified_files += 1
for typ in ["error", "warning"]:
for i in issues.get(typ, []):
if i.get("fixed"):
if typ == "error":
errors_fixed += 1
else:
warnings_fixed += 1
else:
if typ == "error":
errors_skipped += 1
else:
warnings_skipped += 1
total_errors = errors_fixed + errors_skipped
total_warnings = warnings_fixed + warnings_skipped
total_total = total_errors + total_warnings
total_corrected = errors_fixed + warnings_fixed
total_skipped = errors_skipped + warnings_skipped
print("\n[AUTOFIX] Resumen de correcciones")
print(f"[AUTOFIX] Ficheros modificados: {modified_files}")
for f, issues in report_data.items():
if any(i.get("fixed") for typ in ["error", "warning"] for i in issues.get(typ, [])):
f = display_fp(f)
print(f"[AUTOFIX] - {f}")
print(f"[AUTOFIX] Errores procesados: {total_errors}")
print(f"[AUTOFIX] - Corregidos: {errors_fixed} ({(errors_fixed/total_errors*100 if total_errors else 0):.1f}%)")
print(f"[AUTOFIX] - Saltados : {errors_skipped} ({(errors_skipped/total_errors*100 if total_errors else 0):.1f}%)")
print(f"[AUTOFIX] Warnings procesados: {total_warnings}")
print(f"[AUTOFIX] - Corregidos: {warnings_fixed} ({(warnings_fixed/total_warnings*100 if total_warnings else 0):.1f}%)")
print(f"[AUTOFIX] - Saltados : {warnings_skipped} ({(warnings_skipped/total_warnings*100 if total_warnings else 0):.1f}%)")
print(f"[AUTOFIX] Total procesados: {total_total}")
print(f"[AUTOFIX] - Corregidos: {total_corrected} ({(total_corrected/total_warnings*100 if total_corrected else 0):.1f}%)")
print(f"[AUTOFIX] - Saltados : {total_skipped} ({(total_skipped/total_warnings*100 if total_skipped else 0):.1f}%)")
print(f"[AUTOFIX] ✔ Análisis terminado {json_file}")
print(f"[AUTOFIX] ✔ Informe HTML generado : {html_file}")
print(f"[AUTOFIX] ✔ JSON generado: {json_file}")
# ============================
# Funciones del Analyzer
# ============================
def generate_analyzer_html(analysis_data, html_file):
"""
Genera el reporte HTML del analyzer.
Args:
analysis_data: Diccionario con summary, global_counts, error_reasons, warning_reasons, etc.
html_file: Ruta del archivo HTML de salida
"""
summary = analysis_data["summary"]
global_counts = analysis_data["global_counts"]
error_reasons = analysis_data["error_reasons"]
warning_reasons = analysis_data["warning_reasons"]
error_reason_files = analysis_data["error_reason_files"]
warning_reason_files = analysis_data["warning_reason_files"]
file_outputs = analysis_data.get("file_outputs", {})
kernel_dir = analysis_data.get("kernel_dir", "")
html_out = []
append = html_out.append
timestamp = datetime.datetime.now().strftime("%H:%M:%S %d/%m/%Y")
# Helper para rutas relativas
def get_relative_path(fp):
if kernel_dir:
try:
return os.path.relpath(fp, kernel_dir)
except:
return fp
return fp
# Header y CSS
append("<!doctype html><html><head><meta charset='utf-8'>")
append("<style>")
append(COMMON_CSS)
append("</style></head><body>")
append(f"<h1>Informe Checkpatch Analyzer <span style='font-weight:normal'>{timestamp}</span></h1>")
# ============================
# RESUMEN GLOBAL
# ============================
total_files_count = sum(
len(summary[func]["errors"]) +
len(summary[func]["warnings"]) +
len(summary[func]["correct"])
for func in summary
)
files_errors = sum(len(summary[func]["errors"]) for func in summary)
files_warnings = sum(len(summary[func]["warnings"]) for func in summary)
files_correct = sum(len(summary[func]["correct"]) for func in summary)
occ_errors = sum(error_reasons.values())
occ_warnings = sum(warning_reasons.values())
occ_correct = global_counts["correct"]
total_occ_count = occ_errors + occ_warnings + occ_correct
PCT_CELL_WIDTH = 220
append("<h2>Resumen global</h2>")
append("<table>")
append(f"<tr><th>Estado</th><th>Ficheros</th>"
f"<th style='width:{PCT_CELL_WIDTH}px;'>% Ficheros</th>"
f"<th>Casos</th>"
f"<th style='width:{PCT_CELL_WIDTH}px;'>% Casos</th></tr>")
for key, cls, f_count, o_count in [
("errors", "errors", files_errors, occ_errors),
("warnings", "warnings", files_warnings, occ_warnings),
("correct", "correct", files_correct, occ_correct)
]:
f_pct = percentage(f_count, total_files_count)
o_pct = percentage(o_count, total_occ_count)
f_pct_val = percentage_value(f_count, total_files_count)
o_pct_val = percentage_value(o_count, total_occ_count)
append(f"<tr><td class='{cls}'>{key.upper()}</td>"
f"<td class='num'>{f_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{f_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-{cls}' style='width:{f_pct_val}%'></div></div>"
f"</td>"
f"<td class='num'>{o_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{o_pct}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-{cls}' style='width:{o_pct_val}%'></div></div>"
f"</td></tr>")
append(f"<tr><td class='total'>TOTAL</td>"
f"<td class='num'>{total_files_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>100%</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-total' style='width:100%'></div></div>"
f"</td>"
f"<td class='num'>{total_occ_count}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>100%</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-total' style='width:100%'></div></div>"
f"</td></tr>")
append("</table>")
# ============================
# RESUMEN POR MOTIVO - ERRORES
# ============================
if error_reasons:
append("<h3 class='errors'>Errores</h3>")
append("<table>")
append(f"<tr><th>Motivo</th><th>Ficheros</th>"
f"<th style='width:{PCT_CELL_WIDTH}px;'>% Ficheros</th>"
f"<th>Casos</th><th style='width:{PCT_CELL_WIDTH}px;'>% de errors</th></tr>")
# Calcular totales para porcentajes
all_error_files = set()
for fp_list in error_reason_files.values():
for fp, _ in fp_list:
all_error_files.add(fp)
total_error_files = len(all_error_files)
total_error_cases = sum(error_reasons.values())
for reason, count in sorted(error_reasons.items(), key=lambda x: -x[1]):
files_for_reason = set(fp for fp, _ in error_reason_files.get(reason, []))
num_files = len(files_for_reason)
pct_files = percentage(num_files, total_error_files)
pct_cases = percentage(count, total_error_cases)
pct_files_val = percentage_value(num_files, total_error_files)
pct_cases_val = percentage_value(count, total_error_cases)
# Helper para generar ID único
import hashlib
def safe_id(text):
h = hashlib.sha1(text.encode("utf-8")).hexdigest()[:12]
return f"id_{h}"
reason_id = safe_id("ERROR:" + reason)
append(f"<tr><td>ERROR: {html_module.escape(reason)}</td>"
f"<td class='num'>{num_files}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{pct_files}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{pct_files_val}%'></div></div>"
f"</td>"
f"<td class='num'><a href='detail-reason.html#{reason_id}'>{count}</a></td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{pct_cases}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-errors' style='width:{pct_cases_val}%'></div></div>"
f"</td></tr>")
append("</table>")
# ============================
# RESUMEN POR MOTIVO - WARNINGS
# ============================
if warning_reasons:
append("<h3 class='warnings'>Warnings</h3>")
append("<table>")
append(f"<tr><th>Motivo</th><th>Ficheros</th>"
f"<th style='width:{PCT_CELL_WIDTH}px;'>% Ficheros</th>"
f"<th>Casos</th><th style='width:{PCT_CELL_WIDTH}px;'>% de warnings</th></tr>")
# Calcular totales para porcentajes
all_warning_files = set()
for fp_list in warning_reason_files.values():
for fp, _ in fp_list:
all_warning_files.add(fp)
total_warning_files = len(all_warning_files)
total_warning_cases = sum(warning_reasons.values())
for reason, count in sorted(warning_reasons.items(), key=lambda x: -x[1]):
files_for_reason = set(fp for fp, _ in warning_reason_files.get(reason, []))
num_files = len(files_for_reason)
pct_files = percentage(num_files, total_warning_files)
pct_cases = percentage(count, total_warning_cases)
pct_files_val = percentage_value(num_files, total_warning_files)
pct_cases_val = percentage_value(count, total_warning_cases)
# Helper para generar ID único
import hashlib
def safe_id(text):
h = hashlib.sha1(text.encode("utf-8")).hexdigest()[:12]
return f"id_{h}"
reason_id = safe_id("WARNING:" + reason)
append(f"<tr><td>WARNING: {html_module.escape(reason)}</td>"
f"<td class='num'>{num_files}</td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{pct_files}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{pct_files_val}%'></div></div>"
f"</td>"
f"<td class='num'><a href='detail-reason.html#{reason_id}'>{count}</a></td>"
f"<td class='num' style='width:{PCT_CELL_WIDTH}px; display:flex; align-items:center; gap:6px;'>"
f"<span style='flex:none'>{pct_cases}</span>"
f"<div class='bar' style='flex:1;'><div class='bar-inner bar-warnings' style='width:{pct_cases_val}%'></div></div>"
f"</td></tr>")
append("</table>")
append("</body></html>")
# Escribir archivo
with open(html_file, "w", encoding="utf-8") as f:
f.write("\n".join(html_out))
def generate_detail_reason_html(analysis_data, html_file):
"""Genera detail-reason.html con el análisis detallado por motivo."""
import hashlib
def safe_id(text):
h = hashlib.sha1(text.encode("utf-8")).hexdigest()[:12]
return f"id_{h}"
error_reasons = analysis_data["error_reasons"]
warning_reasons = analysis_data["warning_reasons"]
error_reason_files = analysis_data["error_reason_files"]
warning_reason_files = analysis_data["warning_reason_files"]
kernel_dir = analysis_data.get("kernel_dir", "")
def get_relative_path(fp):
if kernel_dir:
try:
return os.path.relpath(fp, kernel_dir)
except:
return fp
return fp
html_out = []
append = html_out.append
# Header minimalista
timestamp = datetime.datetime.now().strftime("%H:%M:%S %d/%m/%Y")
append("<!doctype html><html><head><meta charset='utf-8'>")
append("<style>")
append(COMMON_CSS)
append("</style></head><body>")
append(f"<h1>Informe Checkpatch - Detalle por motivo <span style='font-weight:normal'>{timestamp}</span></h1>")
# ERRORES - Detallado
if error_reasons:
append("<h2 class='errors'>Detalle por motivo - Errores</h2>")
for reason in sorted(error_reasons.keys()):
count = error_reasons[reason]
reason_id = safe_id("ERROR:" + reason)
files_for_reason = sorted(set(fp for fp, _ in error_reason_files.get(reason, [])))
append(f"<h4 id='{reason_id}' class='errors'>ERROR: {html_module.escape(reason)}</h4>")
append(f"Ficheros afectados: {len(files_for_reason)} | Total casos: {count}")
append("<ul>")
for fp in files_for_reason:
lines = sorted(set(line for f, line in error_reason_files.get(reason, []) if f == fp))
rel_path = get_relative_path(fp)
file_id = safe_id("FILE:" + fp)
append(f"<li><a href='detail-file.html#{file_id}'>{rel_path}</a> - líneas {', '.join(map(str, lines))}</li>")
append("</ul>")
# WARNINGS - Detallado
if warning_reasons:
append("<h2 class='warnings'>Detalle por motivo - Warnings</h2>")
for reason in sorted(warning_reasons.keys()):
count = warning_reasons[reason]
reason_id = safe_id("WARNING:" + reason)
files_for_reason = sorted(set(fp for fp, _ in warning_reason_files.get(reason, [])))
append(f"<h4 id='{reason_id}' class='warnings'>WARNING: {html_module.escape(reason)}</h4>")
append(f"Ficheros afectados: {len(files_for_reason)} | Total casos: {count}")
append("<ul>")
for fp in files_for_reason:
lines = sorted(set(line for f, line in warning_reason_files.get(reason, []) if f == fp))
rel_path = get_relative_path(fp)
file_id = safe_id("FILE:" + fp)
append(f"<li><a href='detail-file.html#{file_id}'>{rel_path}</a> - líneas {', '.join(map(str, lines))}</li>")
append("</ul>")
append("</body></html>")
with open(html_file, "w", encoding="utf-8") as f:
f.write("\n".join(html_out))
def generate_detail_file_html(analysis_data, html_file):
"""Genera detail-file.html con el análisis detallado por fichero."""
import hashlib
def safe_id(text):
h = hashlib.sha1(text.encode("utf-8")).hexdigest()[:12]
return f"id_{h}"
def colorize_output(text):
"""Coloriza el output del checkpatch: ERROR en rojo, WARNING en naranja, + en verde, # en gris."""
lines = text.split('\n')
colored_lines = []
for line in lines:
escaped_line = html_module.escape(line)
if line.startswith('ERROR:'):
colored_lines.append(f"<span style='color: #d32f2f; font-weight: bold;'>{escaped_line}</span>")
elif line.startswith('WARNING:'):
colored_lines.append(f"<span style='color: #f57c00; font-weight: bold;'>{escaped_line}</span>")
elif line.startswith('+'):
colored_lines.append(f"<span style='color: #2e7d32;'>{escaped_line}</span>")
elif line.startswith('#'):
colored_lines.append(f"<span style='color: #757575;'>{escaped_line}</span>")
else:
colored_lines.append(escaped_line)
return '\n'.join(colored_lines)
file_outputs = analysis_data.get("file_outputs", {})
kernel_dir = analysis_data.get("kernel_dir", "")
error_reason_files = analysis_data["error_reason_files"]
warning_reason_files = analysis_data["warning_reason_files"]
def get_relative_path(fp):
if kernel_dir:
try:
return os.path.relpath(fp, kernel_dir)
except:
return fp
return fp
html_out = []
append = html_out.append
timestamp = datetime.datetime.now().strftime("%H:%M:%S %d/%m/%Y")
# Helper para rutas relativas
def get_relative_path_helper(fp):
if kernel_dir:
try:
return os.path.relpath(fp, kernel_dir)
except:
return fp
return fp
# Header y CSS
append("<!doctype html><html><head><meta charset='utf-8'>")
append("<style>")
append(COMMON_CSS)
append("</style></head><body>")
append(f"<h1>Informe Checkpatch - Detalle por fichero <span style='font-weight:normal'>{timestamp}</span></h1>")
# JavaScript para abrir el desplegable al llegar por ancla
append("<script>")
append("document.addEventListener('DOMContentLoaded', function() {")
append(" const hash = window.location.hash.substring(1);")
append(" if (hash) {")
append(" const element = document.getElementById(hash);")
append(" if (element && element.tagName === 'SUMMARY') {")
append(" element.parentElement.open = true;")
append(" element.scrollIntoView({ behavior: 'smooth', block: 'start' });")
append(" }")
append(" }")
append("});")
append("</script>")
# ============================
# DETALLE POR FICHERO
# ============================
# Agrupar issues por fichero
file_issues = {} # file_path -> [(reason, line, is_error), ...]
for reason, issues in error_reason_files.items():
for fp, line in issues:
if fp not in file_issues:
file_issues[fp] = []
file_issues[fp].append((reason, line, True))
for reason, issues in warning_reason_files.items():
for fp, line in issues:
if fp not in file_issues:
file_issues[fp] = []
file_issues[fp].append((reason, line, False))
append("<h2>Detalle por fichero</h2>")
for fp in sorted(file_issues.keys()):
file_id = safe_id("FILE:" + fp)
rel_path = get_relative_path_helper(fp)
issues = file_issues[fp]
errors = [i for i in issues if i[2]]
warnings = [i for i in issues if not i[2]]
append(f"<details class='file-detail'>")
append(f"<summary id='{file_id}'>")
append(f"<strong>{rel_path}</strong>")
append(f"<span class='stats'>")
if errors:
append(f"<span class='stat-item'><span class='errors'>{len(errors)} errores</span></span>")
if warnings:
append(f"<span class='stat-item'><span class='warnings'>{len(warnings)} warnings</span></span>")
append(f"<span class='stat-item'>Total: {len(issues)}</span>")
append(f"</span>")
append(f"</summary>")
append(f"<div class='detail-content'>")
# Output del checkpatch con colores
if fp in file_outputs:
output = file_outputs[fp]
colored_output = colorize_output(output)
append(f"<pre class='diff-pre'>{colored_output}</pre>")
else:
append(f"<p><em>Sin salida disponible</em></p>")
append(f"</div>")
append(f"</details>")
append("</body></html>")
with open(html_file, "w", encoding="utf-8") as f:
f.write("\n".join(html_out))
def generate_dashboard_html(html_file):
"""Genera dashboard.html con navegación entre reportes."""
html_out = []
append = html_out.append
append("""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Checkpatch Dashboard</title>
<style>
:root {
--bg: #f6f7fb;
--panel: #ffffff;
--text: #1f2742;
--muted: #6c7791;
--accent: #2d7df6;
--accent-strong: #1c66d8;
--border: #dce3ef;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: "Inter", "Segoe UI", system-ui, sans-serif;
background: var(--bg);
color: var(--text);
}
header {
position: sticky;
top: 0;
z-index: 10;
backdrop-filter: blur(8px);
background: rgba(246,247,251,0.9);
border-bottom: 1px solid var(--border);
padding: 12px 18px 8px;
}
.top-row {
display: flex;
align-items: center;
gap: 16px;
}
h1 {
margin: 0;
font-size: 18px;
letter-spacing: 0.4px;
color: var(--text);
flex: 1;
}
nav {
display: inline-flex;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 10px;
padding: 4px;
gap: 6px;
box-shadow: 0 6px 18px rgba(0,0,0,0.06);
}
.tab {
border: none;
background: transparent;
color: var(--muted);
padding: 10px 14px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
}
.tab:hover { color: var(--text); }
.tab.active {
background: linear-gradient(135deg, var(--accent), var(--accent-strong));
color: #ffffff;
box-shadow: 0 8px 18px rgba(44,124,246,0.28);
}
.breadcrumb {
margin: 10px 0 4px;
font-size: 13px;
color: var(--muted);
display: flex;
gap: 6px;
align-items: center;
flex-wrap: wrap;
}
.breadcrumb a {
color: var(--accent);
text-decoration: none;
font-weight: 600;
}
.breadcrumb a:hover { text-decoration: underline; }
.crumb-sep { color: var(--muted); }
main {
min-height: calc(100vh - 110px);
padding: 14px 18px 18px;
}
#view {
width: 100%;
height: calc(100vh - 120px);
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
box-shadow: 0 10px 26px rgba(0,0,0,0.12);
}
</style>
</head>
<body>
<header>
<div class="top-row">
<h1>Checkpatch Dashboard</h1>
<nav>
<button class="tab active" data-target="analyzer">Analyzer</button>
<button class="tab" data-target="autofix">Autofix</button>
<button class="tab" data-target="compile">Compile</button>
</nav>
</div>
<div class="breadcrumb" id="breadcrumb">Analyzer</div>
</header>
<main>
<iframe id="view" src="analyzer.html" title="Checkpatch view"></iframe>
</main>
<script>
const routes = {
analyzer: { url: 'analyzer.html', label: 'Analyzer', breadcrumb: [{ label: 'Analyzer', target: 'analyzer' }] },
autofix: { url: 'autofix.html', label: 'Autofix', breadcrumb: [{ label: 'Autofix', target: 'autofix' }] },
compile: { url: 'compile.html', label: 'Compile', breadcrumb: [{ label: 'Compile', target: 'compile' }] },
'detail-reason': { url: 'detail-reason.html', label: 'Detalle por motivo', breadcrumb: [{ label: 'Analyzer', target: 'analyzer' }, { label: 'Detalle por motivo', target: 'detail-reason' }] },
'detail-file': { url: 'detail-file.html', label: 'Detalle por fichero', breadcrumb: [{ label: 'Analyzer', target: 'analyzer' }, { label: 'Detalle por motivo', target: 'detail-reason' }, { label: 'Detalle por fichero', target: 'detail-file' }] },
'autofix-detail-reason': { url: 'autofix-detail-reason.html', label: 'Detalle por tipo de fix', breadcrumb: [{ label: 'Autofix', target: 'autofix' }, { label: 'Detalle por tipo de fix', target: 'autofix-detail-reason' }] },
'autofix-detail-file': { url: 'autofix-detail-file.html', label: 'Detalle por fichero', breadcrumb: [{ label: 'Autofix', target: 'autofix' }, { label: 'Detalle por tipo de fix', target: 'autofix-detail-reason' }, { label: 'Detalle por fichero', target: 'autofix-detail-file' }] }
};
const view = document.getElementById('view');
const breadcrumb = document.getElementById('breadcrumb');
const tabButtons = Array.from(document.querySelectorAll('.tab'));
let currentContext = 'analyzer'; // Tracker del contexto actual
function labelFromUrl(url) {
const file = url.split('/').pop().replace('.html', '');
if (routes[file]?.label) return routes[file].label;
return file.replace(/[-_]/g, ' ');
}
function setBreadcrumb(path) {
breadcrumb.innerHTML = path.map((item, idx) => {
const isLast = idx === path.length - 1;
if (isLast) return `<span>${item.label}</span>`;
return `<a href="#" data-target="${item.target}">${item.label}</a><span class="crumb-sep">›</span>`;
}).join(' ');
breadcrumb.querySelectorAll('a').forEach(a => {
a.addEventListener('click', (e) => {
e.preventDefault();
const target = e.currentTarget.dataset.target;
const route = routes[target];
if (route?.breadcrumb) {
navigate(target, route.breadcrumb);
} else {
navigate(target, [{ label: routes[target]?.label || labelFromUrl(target), target }]);
}
});
});
}