-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodebase_analysis.py
More file actions
832 lines (702 loc) · 33 KB
/
Copy pathcodebase_analysis.py
File metadata and controls
832 lines (702 loc) · 33 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
import os
import json
import logging
import threading
import customtkinter as ctk
import chardet
from tkinter import filedialog, messagebox
from pathlib import Path
from typing import Dict, Callable, Optional
from concurrent.futures import ThreadPoolExecutor, as_completed
import fnmatch
# Intentar importar gitignore_parser
try:
from gitignore_parser import parse_gitignore
except ImportError:
parse_gitignore = None
# Configuración de logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler("codebase_analysis.log", encoding="utf-8"),
logging.StreamHandler(),
],
)
# Constantes de estilo
BUTTON_STYLE = {
"primary": {
"fg_color": "#1f6aa5",
"hover_color": "#144870",
"text_color": "white",
},
"secondary": {
"fg_color": "#6c757d",
"hover_color": "#5a6268",
"text_color": "white",
},
"danger": {
"fg_color": "#dc3545",
"hover_color": "#a71d2a",
"text_color": "white",
}
}
SPACING = {
"small": 5,
"medium": 10,
"large": 20,
"xlarge": 30
}
# Clase para tooltips mejorada
class ToolTip:
def __init__(self, widget, text, delay=500): # delay en milisegundos
self.widget = widget
self.text = text
self.delay = delay
self.tooltip = None
self.schedule_id = None
# Bindings mejorados
self.widget.bind("<Enter>", self.schedule_show)
self.widget.bind("<Leave>", self.on_leave)
self.widget.bind("<ButtonPress>", self.hide) # Ocultar al hacer clic
def schedule_show(self, event=None):
# Cancelar cualquier tooltip pendiente
self.cancel_schedule()
# Programar nuevo tooltip
self.schedule_id = self.widget.after(self.delay, self.show)
def cancel_schedule(self):
if self.schedule_id:
self.widget.after_cancel(self.schedule_id)
self.schedule_id = None
def on_leave(self, event=None):
# Cancelar tooltip pendiente y ocultar el actual
self.cancel_schedule()
self.hide()
def show(self, event=None):
# Asegurar que no haya otros tooltips
self.hide()
# Calcular posición
x = self.widget.winfo_rootx() + self.widget.winfo_width() + 5
y = self.widget.winfo_rooty() + self.widget.winfo_height()//2
# Crear tooltip
self.tooltip = ctk.CTkToplevel(self.widget)
self.tooltip.wm_overrideredirect(True)
# Evitar que el tooltip tome el foco
self.tooltip.wm_attributes("-topmost", True)
self.tooltip.withdraw() # Ocultar mientras se configura
# Crear contenido
label = ctk.CTkLabel(
self.tooltip,
text=self.text,
fg_color="#2d2d2d",
corner_radius=6,
padx=10,
pady=5
)
label.pack()
# Posicionar y mostrar
self.tooltip.update_idletasks()
tooltip_width = self.tooltip.winfo_width()
tooltip_height = self.tooltip.winfo_height()
# Ajustar posición si se sale de la pantalla
screen_width = self.widget.winfo_screenwidth()
screen_height = self.widget.winfo_screenheight()
if x + tooltip_width > screen_width:
x = self.widget.winfo_rootx() - tooltip_width - 5
if y + tooltip_height > screen_height:
y = screen_height - tooltip_height - 5
self.tooltip.geometry(f"+{x}+{y}")
self.tooltip.deiconify()
def hide(self, event=None):
if self.tooltip:
self.tooltip.destroy()
self.tooltip = None
###############################################################################
# CONFIGURATION MANAGEMENT #
###############################################################################
class ConfigManager:
def __init__(self, config_file: str = "codebase_analyzer_config.json"):
self.config_file = Path(config_file)
def load_config(self) -> Dict:
default_config = {
"root_path": "",
"use_gitignore": True,
"extra_ignore_files": [],
"output_folder": "{root_path}", # Usar misma carpeta por defecto
"additional_ignore_patterns": "",
}
if not self.config_file.is_file():
logging.info("Config file not found. Using defaults.")
return default_config
try:
with open(self.config_file, "r", encoding="utf-8") as f:
data = json.load(f)
return {**default_config, **data}
except Exception as e:
logging.warning(f"Error loading config: {e}. Using defaults.")
return default_config
def save_config(self, data: Dict):
try:
with open(self.config_file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
except Exception as e:
logging.error(f"Error saving config: {e}", exc_info=True)
###############################################################################
# HELPER FUNCTIONS #
###############################################################################
def preprocess_ignore_files(ignore_files):
"""Preprocesar los archivos de ignorado para validar su existencia."""
valid_ignore_files = []
for ignore_file in ignore_files:
if Path(ignore_file).is_file():
valid_ignore_files.append(ignore_file)
else:
logging.warning(f"Ignored file {ignore_file} not found or invalid.")
return valid_ignore_files
def build_ignore_function(root_path, use_gitignore, extra_ignore_files, additional_patterns):
"""Construir una función combinada para ignorar archivos y carpetas."""
ignore_functions = []
root_path = Path(root_path).resolve() # Convertir a ruta absoluta normalizada
logging.info(f"Construyendo función de ignorado para: {root_path}")
def normalize_path(path):
"""Normaliza una ruta para comparación"""
try:
# Si es una ruta absoluta, conviértela a relativa al root_path
abs_path = Path(path).resolve()
if str(abs_path).startswith(str(root_path)):
return str(abs_path.relative_to(root_path)).replace('\\', '/')
# Si es una ruta relativa, normalízala
return str(Path(path)).replace('\\', '/')
except Exception as e:
logging.warning(f"Error normalizando ruta {path}: {e}")
return str(path).replace('\\', '/')
# Agregar soporte para .gitignore si está habilitado
if use_gitignore and parse_gitignore is not None:
gitignore_path = root_path / ".gitignore"
if gitignore_path.is_file():
try:
with open(gitignore_path, 'r', encoding='utf-8') as f:
gitignore_content = f.read()
fn = parse_gitignore(gitignore_content)
logging.info(f"Usando .gitignore en: {gitignore_path}")
def gitignore_wrapper(path):
norm_path = normalize_path(path)
return fn(norm_path)
ignore_functions.append(gitignore_wrapper)
except Exception as e:
logging.error(f"Error al procesar .gitignore: {e}")
# Procesar patrones adicionales
if additional_patterns:
patterns = [p.strip() for p in additional_patterns.split(",") if p.strip()]
if patterns:
logging.info(f"Patrones adicionales: {patterns}")
def pattern_ignore(path):
norm_path = normalize_path(path)
for pattern in patterns:
try:
if pattern.startswith('!'): # Patrón negativo
if fnmatch.fnmatch(norm_path, pattern[1:]):
return False
elif fnmatch.fnmatch(norm_path, pattern):
return True
except Exception as e:
logging.warning(f"Error al procesar patrón '{pattern}': {e}")
return False
ignore_functions.append(pattern_ignore)
# Procesar archivos/carpetas ignorados manualmente
if extra_ignore_files:
normalized_ignores = [normalize_path(p) for p in extra_ignore_files]
logging.info(f"Patrones ignorados normalizados: {normalized_ignores}")
def manual_ignore(path):
norm_path = normalize_path(path)
for ignore_pattern in normalized_ignores:
try:
if ignore_pattern.endswith('/**'):
# Es un patrón de carpeta
folder = ignore_pattern[:-3]
if norm_path.startswith(folder):
logging.debug(f"Ignorando {norm_path} por coincidencia con patrón de carpeta {folder}")
return True
else:
# Es un archivo específico
if norm_path == ignore_pattern:
logging.debug(f"Ignorando {norm_path} por coincidencia exacta con {ignore_pattern}")
return True
except Exception as e:
logging.warning(f"Error al procesar patrón manual '{ignore_pattern}': {e}")
return False
ignore_functions.append(manual_ignore)
def combined_ignore(path):
try:
return any(fn(path) for fn in ignore_functions)
except Exception as e:
logging.error(f"Error en combined_ignore para path '{path}': {e}")
return False
return combined_ignore
def analyze_single_file(file_path, ignore_func, max_size):
"""Analizar un archivo individual para obtener información básica."""
rel_path = str(Path(file_path).relative_to(Path(file_path).anchor))
if ignore_func(rel_path):
logging.info(f"Ignorando archivo: {rel_path}")
return None
if os.path.getsize(file_path) > max_size:
logging.info(f"Ignorando archivo grande (> {max_size} bytes): {rel_path}")
return None
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read(1000) # Leer hasta 1000 caracteres
except Exception as e:
logging.warning(f"No se pudo leer el archivo {rel_path}: {e}")
content = "Error al leer el archivo."
return {
"path": rel_path,
"size": os.path.getsize(file_path),
"content": content,
}
def analyze_codebase(root_path, ignore_func, max_size, progress_callback):
"""Analizar una base de código completa en paralelo."""
result = {"files": [], "total_files": 0}
files_to_analyze = []
for root, _, files in os.walk(root_path):
for file in files:
files_to_analyze.append(os.path.join(root, file))
total_files = len(files_to_analyze)
logging.info(f"Total de archivos encontrados: {total_files}")
with ThreadPoolExecutor() as executor:
futures = {
executor.submit(analyze_single_file, file_path, ignore_func, max_size): file_path
for file_path in files_to_analyze
}
for i, future in enumerate(as_completed(futures), start=1):
file_info = future.result()
if file_info:
result["files"].append(file_info)
result["total_files"] += 1
if progress_callback:
progress_callback(i / total_files * 100)
return result
###############################################################################
# MAIN APPLICATION #
###############################################################################
print("Creating CodebaseAnalyzerApp instance") # Debug statement
class CodebaseAnalyzerApp(ctk.CTk):
def __init__(self):
print("Entering CodebaseAnalyzerApp.__init__") # Debug statement
super().__init__()
print("Initializing main window") # Debug statement
try:
self.title("Codebase Analyzer - Modern UI")
self.geometry("900x600")
print("Window initialized successfully") # Debug statement
except Exception as e:
print(f"Error initializing window: {e}") # Debug statement
# Configuración de CustomTkinter
ctk.set_appearance_mode("dark") # Opciones: "light", "dark", "system"
ctk.set_default_color_theme("blue") # Opciones: "green", "dark-blue", "blue"
# Configuración del programa
self.config_manager = ConfigManager()
self.config = self.config_manager.load_config()
# Inicializar variables de ruta
root_path = self.config.get("root_path", "")
self.root_path_var = ctk.StringVar(value=root_path)
# Sincronizar carpeta de salida con la raíz por defecto
output_folder = self.config.get("output_folder", "")
if not output_folder or output_folder == "{root_path}":
output_folder = root_path
if output_folder:
logging.info(f"Carpeta de salida inicializada con raíz: {output_folder}")
self.config["output_folder"] = output_folder
self.config_manager.save_config(self.config)
self.output_folder_var = ctk.StringVar(value=output_folder)
self.use_gitignore_var = ctk.BooleanVar(value=self.config.get("use_gitignore", True))
self.extra_ignore_files = self.config.get("extra_ignore_files", [])
self.additional_patterns_var = ctk.StringVar(value=self.config.get("additional_ignore_patterns", ""))
self.analysis_thread = None
self.analysis_running = False
self.analysis_cancelled = False
# Elementos de la UI
self._create_widgets()
def _create_widgets(self):
"""Crea y organiza los widgets principales usando grid layout."""
# Configuración de grid
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
# Frame principal con más padding
main_frame = ctk.CTkFrame(self, corner_radius=10)
main_frame.grid(row=0, column=0, sticky="nsew", padx=SPACING["large"], pady=SPACING["large"])
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_rowconfigure(4, weight=1) # La lista de ignorados crecerá
# Título con más espacio
title_label = ctk.CTkLabel(
main_frame,
text="Codebase Analyzer",
font=("Segoe UI", 28, "bold")
)
title_label.grid(row=0, column=0, pady=(SPACING["large"], SPACING["xlarge"]), sticky="ew")
# Configuración de proyecto
project_frame = self._create_input_frame(
main_frame,
row=1,
label="Carpeta raíz del proyecto:",
entry_var=self.root_path_var,
browse_callback=self._browse_root,
tooltip="Selecciona la carpeta principal de tu proyecto para analizar"
)
# Configuración de salida
output_frame = self._create_input_frame(
main_frame,
row=2,
label="Carpeta de salida:",
entry_var=self.output_folder_var,
browse_callback=self._browse_output,
tooltip="Elige dónde guardar los resultados del análisis"
)
# Opciones adicionales
options_frame = ctk.CTkFrame(main_frame)
options_frame.grid(row=3, column=0, sticky="ew", pady=(SPACING["large"], SPACING["medium"]))
options_frame.grid_columnconfigure(0, weight=1)
# Checkbox para gitignore con tooltip
gitignore_check = ctk.CTkCheckBox(
options_frame,
text="Usar .gitignore si existe en la raíz",
variable=self.use_gitignore_var
)
gitignore_check.grid(row=0, column=0, sticky="w", padx=SPACING["medium"], pady=SPACING["medium"])
ToolTip(gitignore_check, "Aplica automáticamente las reglas de tu archivo .gitignore")
# Entrada para patrones adicionales
patterns_frame = ctk.CTkFrame(options_frame, fg_color="transparent")
patterns_frame.grid(row=1, column=0, sticky="ew", pady=SPACING["medium"])
patterns_frame.grid_columnconfigure(1, weight=1)
patterns_label = ctk.CTkLabel(patterns_frame, text="Patrones adicionales:")
patterns_label.grid(row=0, column=0, sticky="w", padx=SPACING["medium"])
patterns_entry = ctk.CTkEntry(
patterns_frame,
textvariable=self.additional_patterns_var,
placeholder_text="Ejemplo: *.log, temp/*, build/"
)
patterns_entry.grid(row=0, column=1, sticky="ew", padx=SPACING["medium"])
ToolTip(patterns_entry, "Añade patrones adicionales separados por comas (*.log, temp/*, etc.)")
# Frame para selección dinámica de ignorados
ignore_frame = ctk.CTkFrame(main_frame)
ignore_frame.grid(row=4, column=0, sticky="nsew", pady=SPACING["medium"]) # Cambiado a nsew
ignore_frame.grid_columnconfigure(0, weight=1)
ignore_frame.grid_rowconfigure(0, weight=1) # La lista crecerá
# Lista de elementos ignorados
self.ignore_listbox = ctk.CTkTextbox(ignore_frame, height=120)
self.ignore_listbox.grid(row=0, column=0, sticky="nsew", padx=SPACING["medium"], pady=SPACING["medium"])
self.ignore_listbox.configure(state="disabled")
# Botones de control con estilos estandarizados
button_frame = ctk.CTkFrame(ignore_frame, fg_color="transparent")
button_frame.grid(row=1, column=0, sticky="ew", pady=(0, SPACING["medium"]))
# Botones de ignorar
add_files_button = ctk.CTkButton(
button_frame,
text="+ Archivos",
command=lambda: self._add_ignore_item(mode="files"),
width=100,
**BUTTON_STYLE["secondary"]
)
add_files_button.grid(row=0, column=0, padx=SPACING["small"])
ToolTip(add_files_button, "Añade múltiples archivos a la lista de ignorados")
add_folders_button = ctk.CTkButton(
button_frame,
text="+ Carpetas",
command=lambda: self._add_ignore_item(mode="folders"),
width=100,
**BUTTON_STYLE["secondary"]
)
add_folders_button.grid(row=0, column=1, padx=SPACING["small"])
ToolTip(add_folders_button, "Añade múltiples carpetas a la lista de ignorados")
remove_button = ctk.CTkButton(
button_frame,
text="Eliminar",
command=self._remove_ignore_item,
width=100,
**BUTTON_STYLE["danger"]
)
remove_button.grid(row=0, column=2, padx=SPACING["small"])
ToolTip(remove_button, "Elimina los elementos seleccionados de la lista")
clear_button = ctk.CTkButton(
button_frame,
text="Limpiar",
command=self._clear_ignore_list,
width=100,
**BUTTON_STYLE["danger"]
)
clear_button.grid(row=0, column=3, padx=SPACING["small"])
ToolTip(clear_button, "Elimina todos los elementos de la lista")
# Frame para la barra de progreso y botón de análisis
self.analysis_frame = ctk.CTkFrame(main_frame)
self.analysis_frame.grid(row=5, column=0, sticky="ew", pady=(0, SPACING["medium"])) # Reducido el padding vertical
self.analysis_frame.grid_columnconfigure(0, weight=1)
# Barra de progreso (inicialmente oculta)
self.progress_frame = ctk.CTkFrame(self.analysis_frame)
self.progress_frame.grid_columnconfigure(0, weight=1)
self.progress_bar = ctk.CTkProgressBar(self.progress_frame, height=15)
self.progress_bar.grid(row=0, column=0, sticky="ew", padx=SPACING["medium"], pady=SPACING["medium"])
self.progress_bar.set(0)
self.progress_label = ctk.CTkLabel(self.progress_frame, text="0%", font=("Segoe UI", 12, "bold"))
self.progress_label.grid(row=1, column=0)
# Inicialmente ocultamos el frame de progreso
self.progress_frame.grid_remove()
# Botón de inicio principal
self.analyze_button = ctk.CTkButton(
self.analysis_frame,
text="Iniciar Análisis",
command=self._start_analysis,
height=40,
font=("Segoe UI", 14, "bold"),
**BUTTON_STYLE["primary"]
)
self.analyze_button.grid(row=2, column=0, sticky="ew", padx=SPACING["xlarge"])
ToolTip(self.analyze_button, "Comienza el análisis del código con la configuración actual")
def _create_input_frame(self, parent, row, label, entry_var, browse_callback, tooltip):
"""Crea un frame estandarizado para entradas de texto con botón de búsqueda."""
frame = ctk.CTkFrame(parent)
frame.grid(row=row, column=0, sticky="ew", pady=SPACING["medium"])
frame.grid_columnconfigure(1, weight=1)
# Label
label = ctk.CTkLabel(frame, text=label)
label.grid(row=0, column=0, sticky="w", padx=SPACING["medium"], pady=SPACING["medium"])
# Entrada de texto
entry = ctk.CTkEntry(
frame,
textvariable=entry_var,
placeholder_text="Selecciona una carpeta..."
)
entry.grid(row=0, column=1, sticky="ew", padx=(0, SPACING["medium"]), pady=SPACING["medium"])
ToolTip(entry, tooltip)
# Botón de búsqueda
browse_button = ctk.CTkButton(
frame,
text="Examinar",
command=browse_callback,
width=100,
**BUTTON_STYLE["secondary"]
)
browse_button.grid(row=0, column=2, padx=(0, SPACING["medium"]), pady=SPACING["medium"])
ToolTip(browse_button, "Haz clic para buscar la carpeta")
return frame
def _browse_root(self):
folder = filedialog.askdirectory(title="Selecciona la carpeta raíz del proyecto")
if folder:
self.root_path_var.set(folder)
# Sincronizar carpeta de salida si no ha sido modificada manualmente
current_output = self.output_folder_var.get()
if not current_output or current_output == self.config.get("root_path", "") or current_output == "{root_path}":
self.output_folder_var.set(folder)
logging.info(f"Carpeta de salida sincronizada con raíz: {folder}")
# Actualizar configuración
self.config["root_path"] = folder
if self.output_folder_var.get() == folder:
self.config["output_folder"] = folder
self.config_manager.save_config(self.config)
def _browse_output(self):
folder = filedialog.askdirectory(title="Selecciona la carpeta de salida")
if folder:
self.output_folder_var.set(folder)
# Actualizar configuración
self.config["output_folder"] = folder
self.config_manager.save_config(self.config)
def _update_ignore_list(self):
"""Actualiza la visualización de la lista de ignorados"""
self.ignore_listbox.configure(state="normal")
self.ignore_listbox.delete("1.0", "end")
self.ignore_listbox.insert("end", "\n".join(self.extra_ignore_files))
self.ignore_listbox.configure(state="disabled")
self.config_manager.save_config({
**self.config,
"extra_ignore_files": self.extra_ignore_files
})
def _add_ignore_item(self, mode="files"):
"""
Añade archivos o carpetas a la lista de ignorados.
Args:
mode (str): "files" para seleccionar archivos, "folders" para carpetas
"""
try:
items_to_add = []
if mode == "files":
files = filedialog.askopenfilenames(
title="Selecciona archivos para ignorar",
filetypes=[("Todos los archivos", "*.*")]
)
items_to_add.extend(files)
else: # mode == "folders"
while True:
folder = filedialog.askdirectory(
title="Selecciona una carpeta para ignorar (Cancelar para terminar)"
)
if not folder:
break
items_to_add.append(folder + "/**") # Añadir /** para ignorar todo el contenido
# Convertir la lista actual a un conjunto para evitar duplicados
current_ignores = set(self.extra_ignore_files)
# Validar y añadir items
for item in items_to_add:
if os.path.exists(os.path.dirname(item.replace("/**", ""))):
current_ignores.add(item)
else:
logging.warning(f"La ruta {item} no existe y será ignorada")
# Actualizar la lista de ignorados
self.extra_ignore_files = sorted(list(current_ignores))
self._update_ignore_list()
# Guardar configuración
config = {
"root_path": self.root_path_var.get(),
"output_folder": self.output_folder_var.get(),
"use_gitignore": self.use_gitignore_var.get(),
"extra_ignore_files": self.extra_ignore_files,
"additional_ignore_patterns": self.additional_patterns_var.get(),
}
self.config_manager.save_config(config)
except Exception as e:
logging.error(f"Error al añadir items ignorados: {e}", exc_info=True)
messagebox.showerror("Error", f"Error al añadir items: {str(e)}")
def _remove_ignore_item(self):
"""Elimina el ítem seleccionado de la lista de ignorados"""
try:
# Obtener texto seleccionado
selected_text = self.ignore_listbox.get("sel.first", "sel.last")
if selected_text:
# Eliminar de la lista
self.extra_ignore_files = [item for item in self.extra_ignore_files
if item != selected_text]
# Actualizar UI y config
self._update_ignore_list()
logging.info(f"Ítem eliminado de ignorados: {selected_text}")
else:
messagebox.showwarning(
"Nada seleccionado",
"Por favor selecciona un ítem para eliminar"
)
except Exception as e:
logging.error(f"Error eliminando ítem de ignorados: {e}")
messagebox.showerror(
"Error",
f"No se pudo eliminar el ítem: {str(e)}"
)
def _clear_ignore_list(self):
"""Limpia toda la lista de archivos ignorados"""
try:
# Confirmar con el usuario
confirm = messagebox.askyesno(
"Limpiar lista",
"¿Estás seguro que quieres eliminar todos los ítems de la lista de ignorados?"
)
if confirm:
# Limpiar lista
self.extra_ignore_files = []
# Actualizar UI y config
self._update_ignore_list()
logging.info("Lista de ignorados limpiada")
except Exception as e:
logging.error(f"Error limpiando lista de ignorados: {e}")
messagebox.showerror(
"Error",
f"No se pudo limpiar la lista: {str(e)}"
)
def _start_analysis(self):
"""Inicia el análisis del código en un hilo separado"""
root_path = self.root_path_var.get()
if not root_path:
messagebox.showerror("Error", "Por favor seleccione una carpeta raíz")
return
if self.analysis_running:
self.analysis_cancelled = True
self.analyze_button.configure(text="Analizar")
self.progress_frame.grid_remove() # Ocultar barra de progreso
return
# Mostrar barra de progreso y mover botón
self.progress_frame.grid(row=0, column=0, sticky="ew")
self.analyze_button.grid(row=2, column=0) # Mover botón abajo
# Configurar botón para cancelar
self.analyze_button.configure(text="Cancelar")
self.analysis_running = True
self.analysis_cancelled = False
# Crear función de ignorado
ignore_func = build_ignore_function(
root_path,
self.use_gitignore_var.get(),
self.extra_ignore_files,
self.additional_patterns_var.get()
)
# Iniciar análisis en hilo separado
threading.Thread(
target=self._run_analysis,
args=(root_path, ignore_func),
daemon=True
).start()
def _run_analysis(self, root_path, ignore_func):
"""Ejecuta el análisis en un hilo separado"""
try:
result = {"files": [], "total_files": 0}
# Recolectar archivos a analizar, filtrando carpetas ignoradas primero
files_to_analyze = []
root_path_obj = Path(root_path)
for root, dirs, files in os.walk(root_path):
if self.analysis_cancelled:
logging.info("Análisis cancelado por el usuario")
break
# Filtrar directorios antes de procesarlos
rel_root = str(Path(root).relative_to(root_path_obj))
if rel_root != "." and ignore_func(rel_root):
dirs.clear() # No procesar subdirectorios de carpetas ignoradas
continue
# Filtrar y eliminar directorios ignorados antes de procesarlos
dirs[:] = [d for d in dirs if not ignore_func(str(Path(root) / d))]
# Añadir solo archivos no ignorados
for file in files:
file_path = os.path.join(root, file)
rel_path = str(Path(file_path).relative_to(root_path_obj))
if not ignore_func(rel_path):
files_to_analyze.append(file_path)
if not self.analysis_cancelled:
total_files = len(files_to_analyze)
logging.info(f"Total de archivos a analizar (después de filtrar): {total_files}")
with ThreadPoolExecutor() as executor:
futures = {
executor.submit(
analyze_single_file,
file_path,
lambda x: False, # Ya no necesitamos verificar ignore_func aquí
1024 * 1024 # 1MB max size
): file_path
for file_path in files_to_analyze
}
for i, future in enumerate(as_completed(futures), start=1):
if self.analysis_cancelled:
logging.info("Análisis cancelado durante el procesamiento")
break
file_info = future.result()
if file_info:
result["files"].append(file_info)
result["total_files"] += 1
self._update_progress(i / total_files * 100)
if not self.analysis_cancelled:
self.after(0, lambda: self._show_results(result))
else:
self.after(0, lambda: self._update_progress(0))
except Exception as e:
logging.error(f"Error durante el análisis: {e}", exc_info=True)
self.after(0, lambda: messagebox.showerror(
"Error",
f"Error durante el análisis: {str(e)}"
))
finally:
self.analysis_running = False
self.after(0, lambda: self.analyze_button.configure(text="Analizar"))
def _update_progress(self, progress):
"""Actualiza la barra de progreso"""
self.progress_bar.set(progress / 100)
self.progress_label.configure(text=f"{progress:.0f}%")
def _show_results(self, result):
"""Muestra los resultados del análisis"""
messagebox.showinfo(
"Análisis completado",
f"Archivos analizados: {result['total_files']}"
)
# Add main application entry point at the end of the file
if __name__ == "__main__":
app = CodebaseAnalyzerApp()
app.mainloop()