-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·477 lines (384 loc) · 18.3 KB
/
main.py
File metadata and controls
executable file
·477 lines (384 loc) · 18.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
#!/usr/bin/env python3
"""
main.py - Punto de entrada unificado
Modos de operación:
--analyze: Analiza archivos con checkpatch.pl y genera reporte HTML
--fix: Aplica correcciones automáticas a warnings/errores
Compatible con el flujo anterior de checkpatch_analyzer.py y checkpatch_autofix.py
"""
import argparse
import json
import sys
import logging
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
# Sistema de logging
import logger
# Módulos unificados
from engine import (
apply_fixes,
analyze_file,
get_analysis_summary,
reset_analysis
)
from report import (
generate_html_report,
summarize_results,
generate_analyzer_html,
generate_detail_reason_html,
generate_detail_file_html,
generate_dashboard_html,
generate_autofix_html,
generate_autofix_detail_reason_html,
generate_autofix_detail_file_html,
generate_compile_html
)
from utils import find_source_files
from compile import (
compile_modified_files,
restore_backups,
print_summary,
save_json_report
)
def analyze_mode(args):
"""Modo análisis: analiza archivos y genera reporte HTML."""
# Buscar archivos en todos los directorios especificados
all_files = []
for source_dir in args.source_dirs:
files = find_source_files(source_dir, extensions=args.extensions)
all_files.extend(files)
if not all_files:
logger.error(f"[ERROR] No se encontraron archivos con extensiones {args.extensions}")
return 1
checkpatch_script = args.checkpatch
kernel_root = args.kernel_root
# Resetear estructuras globales
reset_analysis()
# Estructura para JSON compatible con autofix
json_data = []
# Barra de progreso
total = len(all_files)
completed = 0
lock = threading.Lock()
def progress_bar(current, total):
percent = current / total * 100
bar_len = 40
filled = int(bar_len * current / total)
bar = '#' * filled + ' ' * (bar_len - filled)
return f"[{bar}] {percent:.1f}% ({current}/{total})"
logger.info(f"[ANALYZER] Analizando {total} archivos con {args.workers} workers...")
logger.debug(f"[ANALYZER] Archivos a analizar: {[str(f) for f in all_files[:5]]}{'...' if len(all_files) > 5 else ''}")
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = {executor.submit(analyze_file, f, checkpatch_script, kernel_root): f for f in all_files}
for future in as_completed(futures):
file_path = futures[future]
try:
errors, warnings, is_correct = future.result()
# Agregar a JSON si tiene issues
if errors or warnings:
json_data.append({
"file": str(file_path),
"error": errors,
"warning": warnings
})
# Progreso
with lock:
completed += 1
if completed % 10 == 0 or completed == total:
print(f"\r[ANALYZER] Progreso: {progress_bar(completed, total)}", end="")
logger.debug(f"[ANALYZER] Analizado {file_path}: {len(errors)} errores, {len(warnings)} warnings")
except Exception as e:
logger.error(f"\n[ERROR] {file_path}: {e}")
print() # Nueva línea después de la barra
# Obtener resumen
analysis_data = get_analysis_summary()
# Generar HTML
html_path = Path(args.html)
html_path.parent.mkdir(parents=True, exist_ok=True)
generate_analyzer_html(analysis_data, html_path)
# Generar HTMLs de detalle
detail_reason_path = html_path.parent / "detail-reason.html"
detail_file_path = html_path.parent / "detail-file.html"
generate_detail_reason_html(analysis_data, detail_reason_path)
generate_detail_file_html(analysis_data, detail_file_path)
# Generar dashboard
dashboard_path = html_path.parent / "dashboard.html"
generate_dashboard_html(dashboard_path)
# Generar JSON
json_path = Path(args.json_out)
json_path.parent.mkdir(parents=True, exist_ok=True)
with open(json_path, "w", encoding="utf-8") as f:
json.dump(json_data, f, indent=2)
# Resumen en consola
gc = analysis_data["global_counts"]
error_count = sum(analysis_data["error_reasons"].values())
warning_count = sum(analysis_data["warning_reasons"].values())
logger.info(f"[ANALYZER] Errores encontrados: {error_count}")
logger.info(f"[ANALYZER] Warnings encontrados: {warning_count}")
logger.info(f"[ANALYZER] Total encontrados: {error_count + warning_count}")
logger.info(f"[ANALYZER] ✔ Análisis terminado.")
logger.info(f"[ANALYZER] ✔ Informe HTML generado: {html_path}")
logger.info(f"[ANALYZER] ✔ JSON generado: {json_path}")
return 0
def fix_mode(args):
"""Modo autofix: aplica correcciones automáticas."""
json_file = Path(args.json_input)
if not json_file.exists():
logger.error(f"[ERROR] No existe el archivo: {json_file}")
return 1
with open(json_file, "r") as f:
files_data = json.load(f)
# Estructura para report_data
from collections import defaultdict
report_data = defaultdict(lambda: {"warning": [], "error": []})
modified_files = set()
file_filter = Path(args.file).resolve() if args.file else None
logger.info("[AUTOFIX] Procesando archivos...")
logger.debug(f"[AUTOFIX] JSON de entrada: {json_file}, filtro de archivo: {file_filter}")
for entry in files_data:
file_path = Path(entry["file"]).resolve()
if file_filter and file_filter != file_path:
continue
# Reunir issues según tipo
issues_to_fix = []
if args.type in ("warning", "all"):
for w in entry.get("warning", []):
issues_to_fix.append({"type": "warning", **w})
if args.type in ("error", "all"):
for e in entry.get("error", []):
issues_to_fix.append({"type": "error", **e})
if not issues_to_fix:
continue
issues_to_fix.sort(key=lambda x: -x["line"]) # de abajo hacia arriba
# Aplicar fixes
fix_results = apply_fixes(file_path, issues_to_fix)
file_modified = False
for orig_issue, res in zip(issues_to_fix, fix_results):
typ = orig_issue["type"]
line = orig_issue["line"]
message = orig_issue["message"]
fixed = res.get("fixed", False)
report_data[str(file_path)][typ].append({
"line": line,
"message": message,
"fixed": fixed
})
if fixed:
file_modified = True
if file_modified:
modified_files.add(str(file_path))
logger.info(f"[AUTOFIX] - {file_path.relative_to(file_path.parent.parent.parent)}")
logger.debug(f"[AUTOFIX] Modificado archivo: {file_path}")
# Calcular estadísticas para resumen
errors_fixed = sum(1 for issues in report_data.values() for i in issues.get("error", []) if i.get("fixed"))
warnings_fixed = sum(1 for issues in report_data.values() for i in issues.get("warning", []) if i.get("fixed"))
errors_skipped = sum(1 for issues in report_data.values() for i in issues.get("error", []) if not i.get("fixed"))
warnings_skipped = sum(1 for issues in report_data.values() for i in issues.get("warning", []) if not i.get("fixed"))
# Resumen en consola
if errors_fixed + errors_skipped > 0:
logger.info(f"[AUTOFIX] Errores procesados: {errors_fixed + errors_skipped}")
logger.info(f"[AUTOFIX] - Corregidos: {errors_fixed} ({100*errors_fixed/(errors_fixed+errors_skipped):.1f}%)")
logger.info(f"[AUTOFIX] - Saltados : {errors_skipped} ({100*errors_skipped/(errors_fixed+errors_skipped):.1f}%)")
if warnings_fixed + warnings_skipped > 0:
logger.info(f"[AUTOFIX] Warnings procesados: {warnings_fixed + warnings_skipped}")
logger.info(f"[AUTOFIX] - Corregidos: {warnings_fixed} ({100*warnings_fixed/(warnings_fixed+warnings_skipped):.1f}%)")
logger.info(f"[AUTOFIX] - Saltados : {warnings_skipped} ({100*warnings_skipped/(warnings_fixed+warnings_skipped):.1f}%)")
total = errors_fixed + warnings_fixed + errors_skipped + warnings_skipped
total_fixed = errors_fixed + warnings_fixed
if total > 0:
logger.info(f"[AUTOFIX] Total procesados: {total}")
logger.info(f"[AUTOFIX] - Corregidos: {total_fixed} ({100*total_fixed/total:.1f}%)")
logger.info(f"[AUTOFIX] - Saltados : {total - total_fixed} ({100*(total-total_fixed)/total:.1f}%)")
# Generar HTML
html_path = Path(args.html)
html_path.parent.mkdir(parents=True, exist_ok=True)
# Generar 3 archivos de autofix
generate_autofix_html(report_data, html_path)
generate_autofix_detail_reason_html(report_data, html_path.parent / "autofix-detail-reason.html")
generate_autofix_detail_file_html(report_data, html_path.parent / "autofix-detail-file.html")
# Generar dashboard
dashboard_path = html_path.parent / "dashboard.html"
generate_dashboard_html(dashboard_path)
# Guardar JSON de resultados
json_out_path = Path(args.json_out)
json_out_path.parent.mkdir(parents=True, exist_ok=True)
with open(json_out_path, "w", encoding="utf-8") as f:
json.dump(report_data, f, indent=2, default=str)
logger.info(f"[AUTOFIX] ✔ Análisis terminado {json_out_path}")
logger.info(f"[AUTOFIX] ✔ Informe HTML generado : {html_path}")
logger.info(f"[AUTOFIX] ✔ JSON generado: {json_out_path}")
return 0
def compile_mode(args):
"""Modo compilación: compila archivos modificados y verifica que compilen."""
json_file = Path(args.json_input)
if not json_file.exists():
logger.error(f"[ERROR] No existe el archivo: {json_file}")
return 1
# Leer archivos modificados del JSON de autofix
with open(json_file, "r") as f:
report_data = json.load(f)
# Extraer lista de archivos que fueron modificados
modified_files = []
if isinstance(report_data, dict):
# JSON de autofix (formato: {file: {error: [], warning: []}})
for file_path, issues in report_data.items():
if file_path == "summary":
continue
# Verificar si hay algún fix aplicado
has_fixes = any(
i.get("fixed", False)
for issue_list in [issues.get("error", []), issues.get("warning", [])]
for i in issue_list
)
if has_fixes:
modified_files.append(Path(file_path))
elif isinstance(report_data, list):
# JSON de checkpatch (formato: [{file: ..., error: [], warning: []}])
modified_files = [Path(entry["file"]) for entry in report_data]
if not modified_files:
logger.info("[COMPILE] No se encontraron archivos modificados para compilar")
return 0
logger.debug(f"[COMPILE] Archivos a compilar: {[str(f) for f in modified_files]}")
# Restaurar backups si se solicita
if args.restore_before:
logger.info(f"[COMPILE] Restaurando {len(modified_files)} archivos desde backup...")
restore_backups(modified_files)
# Compilar archivos
kernel_root = Path(args.kernel_root).resolve()
if not kernel_root.exists():
logger.error(f"[ERROR] Kernel root no encontrado: {kernel_root}")
return 1
logger.info(f"[COMPILE] Kernel root: {kernel_root}")
results = compile_modified_files(
modified_files,
kernel_root,
cleanup=not args.no_cleanup
)
# Restaurar backups después si se solicita
if args.restore_after:
logger.info(f"\n[COMPILE] Restaurando {len(modified_files)} archivos desde backup...")
restore_backups(modified_files)
# Generar reportes
html_path = Path(args.html)
html_path.parent.mkdir(parents=True, exist_ok=True)
generate_compile_html(results, html_path, kernel_root)
# Generar JSON
json_path = Path(args.json_out)
save_json_report(results, json_path)
# Resumen en consola
print_summary(results)
logger.info(f"\n[COMPILE] ✓ Informe HTML generado: {html_path}")
logger.info(f"[COMPILE] ✓ JSON generado: {json_path}")
# Retornar 0 si todos compilaron exitosamente, 1 si hubo fallos
failed_count = sum(1 for r in results if not r.success)
return 1 if failed_count > 0 else 0
def main():
parser = argparse.ArgumentParser(
description="Checkpatch analyzer y autofix unificado",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Ejemplos:
# Analizar archivos (estilo original)
%(prog)s --analyze /path/to/kernel/linux --paths init
# Aplicar fixes
%(prog)s --fix --json-input json/checkpatch.json
# Compilar archivos modificados
%(prog)s --compile --json-input json/fixed.json --kernel-root /path/to/kernel/linux
"""
)
# Modo de operación
mode_group = parser.add_mutually_exclusive_group(required=True)
mode_group.add_argument("--analyze", metavar="KERNEL_ROOT",
help="Modo análisis: ruta al root del kernel Linux")
mode_group.add_argument("--fix", action="store_true", help="Modo autofix")
mode_group.add_argument("--compile", action="store_true", help="Modo compilación: prueba compilar archivos modificados")
# Argumentos para análisis
analyze_group = parser.add_argument_group("Opciones de análisis")
analyze_group.add_argument("--paths", nargs="+",
help="Subdirectorios a analizar (ej: init, kernel). Si se omite, analiza todo")
analyze_group.add_argument("--extensions", nargs="+", default=[".c", ".h"],
help="Extensiones de archivo (default: .c .h)")
analyze_group.add_argument("--workers", type=int, default=4,
help="Número de workers paralelos (default: 4)")
# Argumentos para autofix
fix_group = parser.add_argument_group("Opciones de autofix")
fix_group.add_argument("--json-input", help="JSON de entrada de checkpatch o autofix")
fix_group.add_argument("--type", choices=["warning", "error", "all"], default="all",
help="Filtrar por tipo (default: all)")
fix_group.add_argument("--file", help="Procesar solo este fichero específico")
# Argumentos para compilación
compile_group = parser.add_argument_group("Opciones de compilación")
compile_group.add_argument("--kernel-root", help="Directorio raíz del kernel Linux")
compile_group.add_argument("--restore-before", action="store_true",
help="Restaurar backups antes de compilar")
compile_group.add_argument("--restore-after", action="store_true",
help="Restaurar backups después de compilar")
compile_group.add_argument("--no-cleanup", action="store_true",
help="No limpiar archivos .o después de compilar")
# Argumentos comunes
parser.add_argument("--html", help="Archivo HTML de salida (default: html/analyzer.html o html/autofix.html)")
parser.add_argument("--json-out", help="Archivo JSON de salida (default: json/checkpatch.json o json/fixed.json)")
# Argumentos de logging
logging_group = parser.add_argument_group("Opciones de logging")
logging_group.add_argument("--log-level",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
default="INFO",
help="Nivel de logging (default: INFO)")
logging_group.add_argument("--log-file",
help="Archivo de log opcional (ej: logs/checkpatch.log)")
logging_group.add_argument("--no-color", action="store_true",
help="Desactivar colores en la salida de consola")
args = parser.parse_args()
# Configurar logging
log_level = logger.get_level_from_string(args.log_level)
logger.setup_logging(
level=log_level,
log_file=args.log_file,
use_colors=not args.no_color
)
logger.debug(f"[MAIN] Argumentos: {vars(args)}")
logger.debug(f"[MAIN] Nivel de logging: {args.log_level}")
# Validar argumentos según modo
if args.analyze:
# Configurar rutas automáticamente desde kernel root
kernel_root = Path(args.analyze).resolve()
if not kernel_root.exists():
parser.error(f"Kernel root no encontrado: {kernel_root}")
# Checkpatch.pl debe estar en scripts/
checkpatch = kernel_root / "scripts" / "checkpatch.pl"
if not checkpatch.exists():
parser.error(f"checkpatch.pl no encontrado en {checkpatch}")
# Determinar directorios a analizar
if args.paths:
source_dirs = [kernel_root / p for p in args.paths]
for sd in source_dirs:
if not sd.exists():
parser.error(f"Subdirectorio no encontrado: {sd}")
else:
source_dirs = [kernel_root]
# Defaults para analyze
args.source_dirs = source_dirs
args.kernel_root = kernel_root
args.checkpatch = checkpatch
args.html = args.html or "html/analyzer.html"
args.json_out = args.json_out or "json/checkpatch.json"
return analyze_mode(args)
elif args.fix:
if not args.json_input:
parser.error("--fix requiere --json-input")
# Ajustar defaults para fix
args.html = args.html or "html/autofix.html"
args.json_out = args.json_out or "json/fixed.json"
return fix_mode(args)
elif args.compile:
if not args.json_input:
parser.error("--compile requiere --json-input")
if not args.kernel_root:
parser.error("--compile requiere --kernel-root")
# Ajustar defaults para compile
args.html = args.html or "html/compile.html"
args.json_out = args.json_out or "json/compile.json"
return compile_mode(args)
if __name__ == "__main__":
sys.exit(main())