Skip to content

Commit 33ea8bd

Browse files
author
Kilynho
committed
Mejoras de logging y depuración en run, main.py y compile.py
1 parent 73f8cc7 commit 33ea8bd

File tree

3 files changed

+44
-1798
lines changed

3 files changed

+44
-1798
lines changed

compile.py

Lines changed: 22 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -57,21 +57,22 @@ def ensure_kernel_configured(kernel_root: Path) -> bool:
5757
True si el kernel está configurado correctamente
5858
"""
5959
config_file = kernel_root / ".config"
60-
60+
logger.debug(f"[ensure_kernel_configured] kernel_root={kernel_root}")
6161
# Si ya existe .config, asumir que está configurado
6262
if config_file.exists():
63+
logger.debug("[ensure_kernel_configured] .config exists, kernel is configured.")
6364
return True
64-
6565
logger.info("[COMPILE] Kernel not configured. Running 'make defconfig'...")
6666
try:
67+
logger.debug("[ensure_kernel_configured] Running 'make defconfig'")
6768
result = subprocess.run(
6869
['make', 'defconfig'],
6970
cwd=str(kernel_root),
7071
capture_output=True,
7172
text=True,
7273
timeout=60
7374
)
74-
75+
logger.debug(f"[ensure_kernel_configured] make defconfig returncode={result.returncode}")
7576
if result.returncode == 0 and config_file.exists():
7677
logger.info("[COMPILE] ✓ Kernel configured successfully")
7778
return True
@@ -146,41 +147,34 @@ def compile_single_file(file_path: Path, kernel_root: Path) -> CompilationResult
146147
CompilationResult con el resultado de la compilación
147148
"""
148149
try:
150+
logger.debug(f"[compile_single_file] file_path={file_path}, kernel_root={kernel_root}")
149151
# Convertir la ruta del archivo .c a la ruta del .o correspondiente
150152
rel_path = file_path.relative_to(kernel_root)
151153
obj_path = rel_path.with_suffix('.o')
152-
153154
start_time = time.time()
154-
155+
logger.debug(f"[compile_single_file] Compiling {obj_path}")
155156
# Usar make con el target específico del archivo .o
156-
# Esto compila solo ese archivo sin compilar todo el kernel
157157
result = subprocess.run(
158158
['make', str(obj_path)],
159159
cwd=str(kernel_root),
160160
capture_output=True,
161161
text=True,
162162
timeout=300 # 5 minutos timeout
163163
)
164-
165164
duration = time.time() - start_time
166-
165+
logger.debug(f"[compile_single_file] Finished in {duration:.2f}s, returncode={result.returncode}")
167166
success = result.returncode == 0
168167
error_msg = ""
169168
error_type = ""
170-
171169
if not success:
172-
# Extraer mensaje de error más relevante
173170
error_lines = result.stderr.split('\n')
174-
# Buscar líneas con "error:"
175171
error_msgs = [line for line in error_lines if 'error:' in line.lower()]
176172
if error_msgs:
177-
error_msg = '\n'.join(error_msgs[:5]) # Primeros 5 errores
173+
error_msg = '\n'.join(error_msgs[:5])
178174
else:
179-
error_msg = result.stderr[:500] # Primeros 500 chars si no hay errores explícitos
180-
181-
# Clasificar el tipo de error
175+
error_msg = result.stderr[:500]
182176
error_type = classify_compilation_error(error_msg, result.stderr)
183-
177+
logger.debug(f"[compile_single_file] Compilation failed: error_type={error_type}, error_msg={error_msg.splitlines()[0] if error_msg else ''}")
184178
return CompilationResult(
185179
file_path=str(file_path),
186180
success=success,
@@ -190,15 +184,16 @@ def compile_single_file(file_path: Path, kernel_root: Path) -> CompilationResult
190184
error_message=error_msg,
191185
error_type=error_type
192186
)
193-
194187
except subprocess.TimeoutExpired:
188+
logger.debug(f"[compile_single_file] TimeoutExpired for {file_path}")
195189
return CompilationResult(
196190
file_path=str(file_path),
197191
success=False,
198192
duration=300.0,
199193
error_message="Timeout: Compilation took more than 5 minutes"
200194
)
201195
except Exception as e:
196+
logger.error(f"[compile_single_file] Exception: {str(e)}")
202197
return CompilationResult(
203198
file_path=str(file_path),
204199
success=False,
@@ -215,25 +210,20 @@ def cleanup_compiled_files(kernel_root: Path, compiled_files: List[Path]):
215210
kernel_root: Directorio raíz del kernel
216211
compiled_files: Lista de archivos .c que fueron compilados
217212
"""
213+
logger.debug(f"[cleanup_compiled_files] kernel_root={kernel_root}, compiled_files={compiled_files}")
218214
for c_file in compiled_files:
219215
try:
220-
# Encontrar el archivo .o correspondiente
221216
rel_path = c_file.relative_to(kernel_root)
222217
obj_path = kernel_root / rel_path.with_suffix('.o')
223-
224218
if obj_path.exists():
225219
obj_path.unlink()
226220
logger.debug(f"[CLEANUP] Removed: {obj_path.relative_to(kernel_root)}")
227-
228-
# También limpiar posibles archivos auxiliares (.cmd, .d, etc.)
229221
cmd_file = obj_path.parent / f".{obj_path.name}.cmd"
230222
if cmd_file.exists():
231223
cmd_file.unlink()
232-
233224
d_file = obj_path.with_suffix('.o.d')
234225
if d_file.exists():
235226
d_file.unlink()
236-
237227
except Exception as e:
238228
logger.warning(f"[CLEANUP WARNING] Could not clean {c_file}: {e}")
239229

@@ -251,41 +241,32 @@ def compile_modified_files(files: List[Path], kernel_root: Path,
251241
Returns:
252242
Lista de CompilationResult con los resultados
253243
"""
244+
logger.debug(f"[compile_modified_files] files={files}, kernel_root={kernel_root}, cleanup={cleanup}")
254245
results = []
255-
256246
# Verificar/configurar el kernel antes de compilar
257247
if not ensure_kernel_configured(kernel_root):
258-
print("[COMPILE] ✗ Cannot compile without kernel configuration")
248+
logger.error("[COMPILE] ✗ Cannot compile without kernel configuration")
259249
return results
260-
261-
print(f"[COMPILE] Compilando {len(files)} archivos...")
262-
250+
logger.debug(f"[compile_modified_files] Compilando {len(files)} archivos...")
263251
for i, file_path in enumerate(files, 1):
264-
# Solo compilar archivos .c
265252
if file_path.suffix != '.c':
266-
print(f"[COMPILE] [{i}/{len(files)}] Skipped (not .c): {file_path.name}")
253+
logger.debug(f"[compile_modified_files] Skipped (not .c): {file_path.name}")
267254
continue
268-
269-
print(f"[COMPILE] [{i}/{len(files)}] Compiling: {file_path.relative_to(kernel_root)}")
270-
255+
logger.debug(f"[compile_modified_files] Compiling: {file_path.relative_to(kernel_root)} [{i}/{len(files)}]")
271256
result = compile_single_file(file_path, kernel_root)
272257
results.append(result)
273-
274258
if result.success:
275-
print(f"[COMPILE] ✓ Success ({result.duration:.2f}s)")
259+
logger.debug(f"[compile_modified_files] Success: {file_path} ({result.duration:.2f}s)")
276260
else:
277-
print(f"[COMPILE] ✗ Failed ({result.duration:.2f}s)")
261+
logger.debug(f"[compile_modified_files] Failed: {file_path} ({result.duration:.2f}s)")
278262
if result.error_message:
279-
# Mostrar solo primera línea del error
280263
first_error = result.error_message.split('\n')[0]
281-
print(f"[COMPILE] Error: {first_error}")
282-
264+
logger.debug(f"[compile_modified_files] Error: {first_error}")
283265
if cleanup:
284266
compiled_c_files = [Path(r.file_path) for r in results if r.success]
285267
if compiled_c_files:
286-
print(f"\n[CLEANUP] Limpiando {len(compiled_c_files)} archivos compilados...")
268+
logger.debug(f"[compile_modified_files] Limpiando {len(compiled_c_files)} archivos compilados...")
287269
cleanup_compiled_files(kernel_root, compiled_c_files)
288-
289270
return results
290271

291272

main.py

Lines changed: 22 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -52,64 +52,54 @@ def analyze_mode(args):
5252
"""Modo análisis: analiza archivos y genera reporte HTML."""
5353

5454
# Buscar archivos en todos los directorios especificados
55+
logger.debug(f"[ANALYZER] args.source_dirs={args.source_dirs}, args.extensions={args.extensions}")
5556
all_files = []
5657
for source_dir in args.source_dirs:
58+
logger.debug(f"[ANALYZER] Buscando archivos en: {source_dir}")
5759
files = find_source_files(source_dir, extensions=args.extensions)
60+
logger.debug(f"[ANALYZER] Encontrados {len(files)} archivos en {source_dir}")
5861
all_files.extend(files)
59-
6062
if not all_files:
6163
logger.error(f"[ERROR] No se encontraron archivos con extensiones {args.extensions}")
6264
return 1
63-
6465
checkpatch_script = args.checkpatch
6566
kernel_root = args.kernel_root
66-
67-
# Resetear estructuras globales
6867
reset_analysis()
69-
70-
# Estructura para JSON compatible con autofix
7168
json_data = []
72-
73-
# Barra de progreso
7469
total = len(all_files)
7570
completed = 0
7671
lock = threading.Lock()
77-
7872
def progress_bar(current, total):
7973
percent = current / total * 100
8074
bar_len = 40
8175
filled = int(bar_len * current / total)
8276
bar = '#' * filled + ' ' * (bar_len - filled)
8377
return f"[{bar}] {percent:.1f}% ({current}/{total})"
84-
8578
logger.info(f"[ANALYZER] Analizando {total} archivos con {args.workers} workers...")
8679
logger.debug(f"[ANALYZER] Archivos a analizar: {[str(f) for f in all_files[:5]]}{'...' if len(all_files) > 5 else ''}")
8780

81+
logger.debug(f"[ANALYZER] Lanzando ThreadPoolExecutor con {args.workers} workers")
8882
with ThreadPoolExecutor(max_workers=args.workers) as executor:
8983
futures = {executor.submit(analyze_file, f, checkpatch_script, kernel_root): f for f in all_files}
90-
9184
for future in as_completed(futures):
9285
file_path = futures[future]
86+
logger.debug(f"[ANALYZER] Iniciando análisis de: {file_path}")
9387
try:
9488
errors, warnings, is_correct = future.result()
95-
96-
# Agregar a JSON si tiene issues
89+
logger.debug(f"[ANALYZER] Finalizado análisis de: {file_path} - {len(errors)} errores, {len(warnings)} warnings")
9790
if errors or warnings:
9891
json_data.append({
9992
"file": str(file_path),
10093
"error": errors,
10194
"warning": warnings
10295
})
103-
104-
# Progreso
10596
with lock:
10697
completed += 1
10798
if completed % 10 == 0 or completed == total:
10899
print(f"\r[ANALYZER] Progreso: {progress_bar(completed, total)}", end="")
109-
logger.debug(f"[ANALYZER] Analizado {file_path}: {len(errors)} errores, {len(warnings)} warnings")
110-
111100
except Exception as e:
112101
logger.error(f"\n[ERROR] {file_path}: {e}")
102+
logger.debug(f"[ANALYZER] Error al analizar {file_path}: {e}")
113103

114104
print() # Nueva línea después de la barra
115105

@@ -175,10 +165,10 @@ def fix_mode(args):
175165

176166
for entry in files_data:
177167
file_path = Path(entry["file"]).resolve()
178-
168+
logger.debug(f"[AUTOFIX] Procesando archivo: {file_path}")
179169
if file_filter and file_filter != file_path:
170+
logger.debug(f"[AUTOFIX] Archivo filtrado: {file_path} (filtro: {file_filter})")
180171
continue
181-
182172
# Reunir issues según tipo
183173
issues_to_fix = []
184174
if args.type in ("warning", "all"):
@@ -187,31 +177,29 @@ def fix_mode(args):
187177
if args.type in ("error", "all"):
188178
for e in entry.get("error", []):
189179
issues_to_fix.append({"type": "error", **e})
190-
180+
logger.debug(f"[AUTOFIX] Issues a corregir: {len(issues_to_fix)}")
191181
if not issues_to_fix:
182+
logger.debug(f"[AUTOFIX] Ningún issue para corregir en: {file_path}")
192183
continue
193-
194184
issues_to_fix.sort(key=lambda x: -x["line"]) # de abajo hacia arriba
195-
185+
logger.debug(f"[AUTOFIX] Issues ordenados para aplicar fixes")
196186
# Aplicar fixes
187+
logger.debug(f"[AUTOFIX] Llamando a apply_fixes para {file_path}")
197188
fix_results = apply_fixes(file_path, issues_to_fix)
198-
189+
logger.debug(f"[AUTOFIX] apply_fixes completado para {file_path}")
199190
file_modified = False
200191
for orig_issue, res in zip(issues_to_fix, fix_results):
201192
typ = orig_issue["type"]
202193
line = orig_issue["line"]
203194
message = orig_issue["message"]
204195
fixed = res.get("fixed", False)
205-
206196
report_data[str(file_path)][typ].append({
207197
"line": line,
208198
"message": message,
209199
"fixed": fixed
210200
})
211-
212201
if fixed:
213202
file_modified = True
214-
215203
if file_modified:
216204
modified_files.add(str(file_path))
217205
logger.info(f"[AUTOFIX] - {file_path.relative_to(file_path.parent.parent.parent)}")
@@ -244,19 +232,20 @@ def fix_mode(args):
244232
# Generar HTML
245233
html_path = Path(args.html)
246234
html_path.parent.mkdir(parents=True, exist_ok=True)
247-
248-
# Generar 3 archivos de autofix
235+
logger.debug(f"[AUTOFIX] Generando HTML principal: {html_path}")
249236
generate_autofix_html(report_data, html_path)
237+
logger.debug(f"[AUTOFIX] Generando HTML detalle motivo: {html_path.parent / 'autofix-detail-reason.html'}")
250238
generate_autofix_detail_reason_html(report_data, html_path.parent / "autofix-detail-reason.html")
239+
logger.debug(f"[AUTOFIX] Generando HTML detalle archivo: {html_path.parent / 'autofix-detail-file.html'}")
251240
generate_autofix_detail_file_html(report_data, html_path.parent / "autofix-detail-file.html")
252-
253241
# Generar dashboard
254242
dashboard_path = html_path.parent / "dashboard.html"
243+
logger.debug(f"[AUTOFIX] Generando dashboard: {dashboard_path}")
255244
generate_dashboard_html(dashboard_path)
256-
257245
# Guardar JSON de resultados
258246
json_out_path = Path(args.json_out)
259247
json_out_path.parent.mkdir(parents=True, exist_ok=True)
248+
logger.debug(f"[AUTOFIX] Guardando JSON de resultados: {json_out_path}")
260249
with open(json_out_path, "w", encoding="utf-8") as f:
261250
json.dump(report_data, f, indent=2, default=str)
262251

@@ -455,19 +444,16 @@ def main():
455444
return analyze_mode(args)
456445

457446
elif args.fix:
458-
if not args.json_input:
459-
parser.error("--fix requiere --json-input")
460447
# Ajustar defaults para fix
448+
args.json_input = args.json_input or "json/checkpatch.json"
461449
args.html = args.html or "html/autofix.html"
462450
args.json_out = args.json_out or "json/fixed.json"
463451
return fix_mode(args)
464452

465453
elif args.compile:
466-
if not args.json_input:
467-
parser.error("--compile requiere --json-input")
468-
if not args.kernel_root:
469-
parser.error("--compile requiere --kernel-root")
470454
# Ajustar defaults para compile
455+
args.json_input = args.json_input or "json/fixed.json"
456+
args.kernel_root = kernel_root
471457
args.html = args.html or "html/compile.html"
472458
args.json_out = args.json_out or "json/compile.json"
473459
return compile_mode(args)

0 commit comments

Comments
 (0)