-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
771 lines (627 loc) · 28.7 KB
/
main.py
File metadata and controls
771 lines (627 loc) · 28.7 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
#!/usr/bin/env python3
"""
Codebase Parser with GUI - Fixed Version
Advanced code documentation generator with file explorer interface
Supports multiple programming languages with checkboxes for selective parsing
"""
import os
import sys
import threading
from pathlib import Path
from typing import Dict, List, Set, Optional
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import platform
class CodebaseParser:
def __init__(self):
self.code_extensions = {
'.py', '.js', '.ts', '.tsx', '.jsx', '.java', '.cpp', '.cc', '.cxx',
'.c', '.h', '.hpp', '.cs', '.php', '.rb', '.go', '.rs', '.kt',
'.swift', '.m', '.mm', '.scala', '.clj', '.hs', '.ml', '.fs',
'.dart', '.lua', '.r', '.pl', '.sh', '.bash', '.zsh', '.fish',
'.sql', '.json', '.xml', '.yaml', '.yml', '.toml', '.ini', '.cfg',
'.vue', '.svelte', '.elm', '.coffee', '.scss', '.sass', '.less'
}
self.ignore_dirs = {
'node_modules', '__pycache__', '.git', '.svn', '.hg', 'build',
'dist', 'target', 'bin', 'obj', '.gradle', '.idea', '.vscode',
'vendor', 'coverage', '.nyc_output', 'logs', 'tmp', 'temp',
'.next', '.nuxt', 'out', 'venv', 'env', '.env', '$RECYCLE.BIN',
'System Volume Information', 'Windows', 'Program Files',
'Program Files (x86)', 'ProgramData'
}
def should_ignore_path(self, path: Path) -> bool:
"""Check if path should be ignored"""
try:
for parent in path.parents:
if parent.name in self.ignore_dirs:
return True
return path.is_dir() and path.name in self.ignore_dirs
except:
return True
def is_code_file(self, file_path: Path) -> bool:
return file_path.suffix.lower() in self.code_extensions
def get_language_from_extension(self, extension: str) -> str:
lang_map = {
'.py': 'Python', '.js': 'JavaScript', '.ts': 'TypeScript',
'.tsx': 'TypeScript React', '.jsx': 'JavaScript React',
'.java': 'Java', '.cpp': 'C++', '.cc': 'C++', '.cxx': 'C++',
'.c': 'C', '.h': 'C/C++ Header', '.hpp': 'C++ Header',
'.cs': 'C#', '.php': 'PHP', '.rb': 'Ruby', '.go': 'Go',
'.rs': 'Rust', '.kt': 'Kotlin', '.swift': 'Swift', '.vue': 'Vue',
'.svelte': 'Svelte', '.elm': 'Elm', '.sql': 'SQL'
}
return lang_map.get(extension.lower(), extension[1:].upper() if extension else 'Unknown')
def read_file_content(self, file_path: Path) -> Optional[str]:
try:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
except UnicodeDecodeError:
try:
with open(file_path, 'r', encoding='latin-1') as f:
return f.read()
except:
return f"Error: Unable to read file"
except Exception as e:
return f"Error: {str(e)}"
def generate_separator(self, text: str, char: str = '-', length: int = 43) -> str:
return char * length + text + char * length
def generate_output(self, selected_paths: List[Path], output_file: str) -> tuple:
try:
files_by_dir = {}
total_files = 0
# Organize files by directory
for path in selected_paths:
try:
if path.is_file() and self.is_code_file(path):
parent = str(path.parent)
if parent not in files_by_dir:
files_by_dir[parent] = []
files_by_dir[parent].append(path)
total_files += 1
elif path.is_dir():
for item in path.rglob('*'):
if item.is_file() and self.is_code_file(item) and not self.should_ignore_path(item):
parent = str(item.parent)
if parent not in files_by_dir:
files_by_dir[parent] = []
if item not in files_by_dir[parent]:
files_by_dir[parent].append(item)
total_files += 1
except Exception as e:
continue
if total_files == 0:
return (False, "No code files found in selected paths")
# Generate output
with open(output_file, 'w', encoding='utf-8') as f:
# Write header
f.write("=" * 100 + "\n")
f.write("CODEBASE DOCUMENTATION\n")
f.write("=" * 100 + "\n")
f.write(f"Total Files: {total_files}\n")
f.write(f"Total Directories: {len(files_by_dir)}\n")
f.write(f"Output Generated: {Path(output_file).absolute()}\n")
f.write("=" * 100 + "\n\n")
# Write structure
f.write("Code Structure:\n")
for directory in sorted(files_by_dir.keys()):
f.write(f"\n{directory}\n")
for file_path in sorted(files_by_dir[directory], key=lambda x: x.name):
f.write(f" {file_path.name}\n")
f.write("\n" + "=" * 100 + "\n\n")
# Write file contents
for directory in sorted(files_by_dir.keys()):
files = sorted(files_by_dir[directory], key=lambda x: x.name)
for file_path in files:
file_name = file_path.stem
extension = file_path.suffix
language = self.get_language_from_extension(extension)
# Section header
section_header = f"{Path(directory).name}/{file_name}"
f.write(self.generate_separator(section_header) + "\n")
f.write(f"File: {file_path.name}\n")
f.write(f"Path: {file_path}\n")
f.write(f"Language: {language}\n")
f.write("-" * 100 + "\n")
# File content
content = self.read_file_content(file_path)
f.write(content if content else "// Unable to read file\n")
f.write("\n" + "=" * 100 + "\n\n")
return (True, f"Successfully generated {output_file}\nProcessed {total_files} files")
except Exception as e:
return (False, f"Error generating output: {str(e)}")
class FileTreeView(ttk.Frame):
def __init__(self, parent, parser):
super().__init__(parent)
self.parser = parser
self.checked_items = {} # item_id -> (path, checked_state)
self.expanded_items = set()
# Create UI
self.create_widgets()
def create_widgets(self):
# Toolbar
toolbar = ttk.Frame(self)
toolbar.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Buttons
ttk.Button(toolbar, text="Browse Folder", command=self.browse_folder).pack(side=tk.LEFT, padx=2)
ttk.Button(toolbar, text="Refresh", command=self.refresh_tree).pack(side=tk.LEFT, padx=2)
ttk.Button(toolbar, text="Clear All", command=self.clear_all).pack(side=tk.LEFT, padx=2)
# Search frame
search_frame = ttk.Frame(toolbar)
search_frame.pack(side=tk.RIGHT, padx=5)
ttk.Label(search_frame, text="Filter:").pack(side=tk.LEFT)
self.search_var = tk.StringVar()
search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=20)
search_entry.pack(side=tk.LEFT, padx=5)
search_entry.bind('<Return>', self.on_search)
ttk.Button(search_frame, text="Search", command=self.on_search).pack(side=tk.LEFT)
# Create frame for tree and scrollbar
tree_frame = ttk.Frame(self)
tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Scrollbars
vsb = ttk.Scrollbar(tree_frame, orient="vertical")
hsb = ttk.Scrollbar(tree_frame, orient="horizontal")
# Treeview
self.tree = ttk.Treeview(
tree_frame,
yscrollcommand=vsb.set,
xscrollcommand=hsb.set,
selectmode='browse'
)
vsb.config(command=self.tree.yview)
hsb.config(command=self.tree.xview)
# Layout
self.tree.grid(row=0, column=0, sticky='nsew')
vsb.grid(row=0, column=1, sticky='ns')
hsb.grid(row=1, column=0, sticky='ew')
tree_frame.grid_rowconfigure(0, weight=1)
tree_frame.grid_columnconfigure(0, weight=1)
# Configure columns
self.tree.heading('#0', text='File System (Click checkbox to select, double-click to expand)', anchor=tk.W)
self.tree.column('#0', width=500, minwidth=200)
# Bind events
self.tree.bind('<Button-1>', self.on_click)
self.tree.bind('<<TreeviewOpen>>', self.on_expand)
# Status bar
self.status_var = tk.StringVar(value="Ready - Browse for a folder to start")
status_bar = ttk.Label(self, textvariable=self.status_var, relief=tk.SUNKEN)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# Initialize with quick access
self.populate_quick_access()
def get_icon(self, path: Path) -> str:
"""Get icon character for file/folder"""
if path.is_dir():
return "📁"
elif self.parser.is_code_file(path):
return "📄"
else:
return "📋"
def populate_quick_access(self):
"""Populate with quick access locations"""
self.tree.delete(*self.tree.get_children())
# Add home directory
home = Path.home()
home_node = self.insert_node('', home, f"🏠 Home ({home})")
# Add Desktop if exists
desktop = home / "Desktop"
if desktop.exists():
self.insert_node('', desktop, "🖥️ Desktop")
# Add Documents if exists
documents = home / "Documents"
if documents.exists():
self.insert_node('', documents, "📚 Documents")
# Add common project locations
if platform.system() == 'Windows':
# Add drives
import string
for letter in string.ascii_uppercase:
drive = Path(f"{letter}:\\")
if drive.exists():
try:
drive.stat() # Check if accessible
self.insert_node('', drive, f"💾 {letter}:\\")
except:
pass
def insert_node(self, parent, path: Path, display_name: str = None):
"""Insert a node into the tree"""
if display_name is None:
icon = self.get_icon(path)
display_name = f"☐ {icon} {path.name if path.name else str(path)}"
else:
display_name = f"☐ {display_name}"
item_id = self.tree.insert(parent, 'end', text=display_name, open=False)
self.checked_items[item_id] = (str(path), False)
# Add dummy child for directories to make them expandable
if path.is_dir():
self.tree.insert(item_id, 'end', text='')
return item_id
def on_expand(self, event):
"""Handle node expansion"""
item = self.tree.focus()
if not item or item in self.expanded_items:
return
# Mark as expanded
self.expanded_items.add(item)
# Remove dummy child
children = self.tree.get_children(item)
if children and not self.checked_items.get(children[0]):
self.tree.delete(children[0])
# Populate real children
if item in self.checked_items:
path_str = self.checked_items[item][0]
self.populate_children(item, Path(path_str))
def populate_children(self, parent_item, path: Path):
"""Populate children of a directory"""
if not path.exists() or not path.is_dir():
return
try:
items = []
for item in path.iterdir():
# Skip hidden files (except common dev folders)
if item.name.startswith('.') and item.name not in ['.git', '.vscode', '.idea']:
continue
# Skip ignored directories
if self.parser.should_ignore_path(item):
continue
items.append(item)
# Sort: directories first, then by name
items.sort(key=lambda x: (not x.is_dir(), x.name.lower()))
# Limit to prevent overwhelming the UI
if len(items) > 500:
self.tree.insert(parent_item, 'end',
text=f'⚠️ Too many items ({len(items)}) - showing first 500')
items = items[:500]
for item in items:
self.insert_node(parent_item, item)
except PermissionError:
self.tree.insert(parent_item, 'end', text='⚠️ Permission Denied')
except Exception as e:
self.tree.insert(parent_item, 'end', text=f'⚠️ Error: {str(e)}')
def on_click(self, event):
"""Handle clicks on tree items"""
region = self.tree.identify_region(event.x, event.y)
item = self.tree.identify_row(event.y)
if not item or item not in self.checked_items:
return
# Get click region
column = self.tree.identify_column(event.x)
if region == "tree" and column == "#0":
# Check if click is on checkbox area (first 30 pixels)
if event.x < 30:
self.toggle_checkbox(item)
return "break"
def toggle_checkbox(self, item):
"""Toggle checkbox state"""
if item not in self.checked_items:
return
path_str, current_state = self.checked_items[item]
new_state = not current_state
# Update state
self.checked_items[item] = (path_str, new_state)
# Update visual
text = self.tree.item(item, 'text')
if new_state:
new_text = text.replace('☐', '☑', 1)
else:
new_text = text.replace('☑', '☐', 1)
self.tree.item(item, text=new_text)
# Update children if expanded
self.update_children_recursive(item, new_state)
# Update status
self.update_status()
def update_children_recursive(self, parent, state):
"""Recursively update children checkbox state"""
for child in self.tree.get_children(parent):
if child in self.checked_items:
path_str, _ = self.checked_items[child]
self.checked_items[child] = (path_str, state)
# Update visual
text = self.tree.item(child, 'text')
if state:
new_text = text.replace('☐', '☑', 1)
else:
new_text = text.replace('☑', '☐', 1)
self.tree.item(child, text=new_text)
# Recurse
self.update_children_recursive(child, state)
def browse_folder(self):
"""Browse for a folder to add"""
folder = filedialog.askdirectory(title="Select Folder to Parse")
if folder:
path = Path(folder)
# Add to tree
node = self.insert_node('', path, f"📂 {path.name} ({path})")
# Auto-expand
self.tree.item(node, open=True)
self.on_expand(None)
self.tree.focus(node)
self.tree.selection_set(node)
self.update_status()
def refresh_tree(self):
"""Refresh the tree"""
self.checked_items.clear()
self.expanded_items.clear()
self.populate_quick_access()
self.update_status()
def clear_all(self):
"""Clear all selections"""
for item in self.checked_items:
path_str, checked = self.checked_items[item]
if checked:
self.checked_items[item] = (path_str, False)
text = self.tree.item(item, 'text')
new_text = text.replace('☑', '☐', 1)
self.tree.item(item, text=new_text)
self.update_status()
def on_search(self, event=None):
"""Search for items in tree"""
search_text = self.search_var.get().lower().strip()
if not search_text:
messagebox.showinfo("Search", "Please enter a search term")
return
# Find matching items
matches = []
for item in self.checked_items:
path_str = self.checked_items[item][0]
if search_text in Path(path_str).name.lower():
matches.append(item)
if matches:
# Focus on first match
self.tree.selection_set(matches[0])
self.tree.focus(matches[0])
self.tree.see(matches[0])
messagebox.showinfo("Search", f"Found {len(matches)} matches")
else:
messagebox.showinfo("Search", "No matches found")
def update_status(self):
"""Update status bar"""
count = sum(1 for _, checked in self.checked_items.values() if checked)
self.status_var.set(f"Selected: {count} items")
def get_checked_paths(self) -> List[Path]:
"""Get list of checked paths"""
paths = []
for item_id, (path_str, checked) in self.checked_items.items():
if checked:
paths.append(Path(path_str))
return paths
class CodebaseParserGUI:
def __init__(self, root):
self.root = root
self.root.title("Codebase Parser - Professional Code Documentation Tool")
self.root.geometry("1200x800")
# Set minimum size
self.root.minsize(900, 600)
# Initialize parser
self.parser = CodebaseParser()
# Create UI
self.create_menu()
self.create_main_layout()
# Configure styles
self.configure_styles()
def configure_styles(self):
"""Configure ttk styles"""
style = ttk.Style()
try:
style.theme_use('clam')
except:
pass
def create_menu(self):
"""Create menu bar"""
menubar = tk.Menu(self.root)
self.root.config(menu=menubar)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Browse Folder", command=lambda: self.file_tree.browse_folder())
file_menu.add_command(label="Choose Output Location", command=self.choose_output_location)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
# View menu
view_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="View", menu=view_menu)
view_menu.add_command(label="Refresh", command=lambda: self.file_tree.refresh_tree())
view_menu.add_command(label="Clear Selections", command=lambda: self.file_tree.clear_all())
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="How to Use", command=self.show_help)
help_menu.add_command(label="About", command=self.show_about)
def create_main_layout(self):
"""Create main layout"""
# Main container
main_container = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
main_container.pack(fill=tk.BOTH, expand=True)
# Left panel - File tree
left_panel = ttk.Frame(main_container)
main_container.add(left_panel, weight=3)
self.file_tree = FileTreeView(left_panel, self.parser)
self.file_tree.pack(fill=tk.BOTH, expand=True)
# Right panel - Options and output
right_panel = ttk.Frame(main_container)
main_container.add(right_panel, weight=1)
# Options frame
options_frame = ttk.LabelFrame(right_panel, text="Options", padding=10)
options_frame.pack(fill=tk.X, padx=10, pady=10)
# Output location
ttk.Label(options_frame, text="Output File:").pack(anchor=tk.W, pady=5)
output_frame = ttk.Frame(options_frame)
output_frame.pack(fill=tk.X, pady=5)
self.output_var = tk.StringVar(value=str(Path.cwd() / "code.txt"))
output_entry = ttk.Entry(output_frame, textvariable=self.output_var)
output_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))
ttk.Button(output_frame, text="Browse",
command=self.choose_output_location).pack(side=tk.RIGHT)
# File extensions
ttk.Label(options_frame, text="Custom Extensions:").pack(anchor=tk.W, pady=(10, 5))
self.extensions_var = tk.StringVar()
ttk.Entry(options_frame, textvariable=self.extensions_var).pack(fill=tk.X, pady=5)
ttk.Label(options_frame, text="(e.g., .txt,.md,.conf)",
font=('TkDefaultFont', 8)).pack(anchor=tk.W)
# Generate button
self.generate_btn = ttk.Button(
options_frame,
text="📝 Generate Documentation",
command=self.generate_output
)
self.generate_btn.pack(fill=tk.X, pady=20)
# Quick stats
stats_frame = ttk.LabelFrame(options_frame, text="Quick Stats", padding=5)
stats_frame.pack(fill=tk.X, pady=10)
self.stats_var = tk.StringVar(value="No selections yet")
ttk.Label(stats_frame, textvariable=self.stats_var, wraplength=200).pack()
# Progress frame
progress_frame = ttk.LabelFrame(right_panel, text="Progress", padding=10)
progress_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.progress_var = tk.StringVar(value="Ready to generate documentation")
ttk.Label(progress_frame, textvariable=self.progress_var,
wraplength=250).pack(anchor=tk.W, pady=5)
self.progressbar = ttk.Progressbar(progress_frame, mode='indeterminate')
self.progressbar.pack(fill=tk.X, pady=10)
# Log text
log_label = ttk.Label(progress_frame, text="Log:")
log_label.pack(anchor=tk.W, pady=(10, 5))
self.log_text = scrolledtext.ScrolledText(
progress_frame,
height=15,
wrap=tk.WORD,
font=('Courier', 9)
)
self.log_text.pack(fill=tk.BOTH, expand=True)
# Update stats periodically
self.update_stats()
def update_stats(self):
"""Update statistics"""
checked = self.file_tree.get_checked_paths()
if checked:
self.stats_var.set(f"Selected: {len(checked)} paths")
else:
self.stats_var.set("No selections yet")
# Schedule next update
self.root.after(1000, self.update_stats)
def choose_output_location(self):
"""Choose output file location"""
filename = filedialog.asksaveasfilename(
title="Choose Output Location",
defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
initialfile="code.txt"
)
if filename:
self.output_var.set(filename)
self.log(f"Output location: {filename}")
def log(self, message):
"""Add message to log"""
self.log_text.insert(tk.END, f"{message}\n")
self.log_text.see(tk.END)
self.root.update_idletasks()
def generate_output(self):
"""Generate documentation output"""
checked_paths = self.file_tree.get_checked_paths()
if not checked_paths:
messagebox.showwarning("No Selection",
"Please select at least one file or folder.\n\n"
"Click the checkbox (☐) next to folders to select them.")
return
output_file = self.output_var.get()
if not output_file:
messagebox.showwarning("No Output File", "Please specify an output file")
return
# Add custom extensions
custom_exts = self.extensions_var.get()
if custom_exts:
for ext in custom_exts.split(','):
ext = ext.strip()
if ext and not ext.startswith('.'):
ext = '.' + ext
if ext:
self.parser.code_extensions.add(ext.lower())
# Disable generate button
self.generate_btn.config(state='disabled')
self.progressbar.start()
self.log("\n" + "="*50)
self.log("Starting documentation generation...")
self.log(f"Selected {len(checked_paths)} items")
self.log(f"Output file: {output_file}")
# Run in thread to keep UI responsive
def generate_thread():
success, message = self.parser.generate_output(checked_paths, output_file)
# Update UI in main thread
self.root.after(0, lambda: self.generation_complete(success, message))
thread = threading.Thread(target=generate_thread, daemon=True)
thread.start()
def generation_complete(self, success, message):
"""Called when generation is complete"""
self.progressbar.stop()
self.generate_btn.config(state='normal')
if success:
self.log("✓ " + message)
self.progress_var.set("Documentation generated successfully!")
# Ask to open file
if messagebox.askyesno("Success",
f"{message}\n\nWould you like to open the output file?"):
try:
if platform.system() == 'Windows':
os.startfile(self.output_var.get())
elif platform.system() == 'Darwin':
os.system(f'open "{self.output_var.get()}"')
else:
os.system(f'xdg-open "{self.output_var.get()}"')
except:
pass
else:
self.log("✗ " + message)
self.progress_var.set("Error occurred during generation")
messagebox.showerror("Error", message)
def show_about(self):
"""Show about dialog"""
about_text = """
Codebase Parser GUI v2.5
Professional code documentation tool with
file explorer interface.
Features:
• Multi-language support
• Selective file/folder parsing
• Full directory tree navigation
• Customizable output format
• Built-in code analysis
Created with Python & Tkinter
"""
messagebox.showinfo("About", about_text)
def show_help(self):
"""Show help dialog"""
help_text = """How to Use Codebase Parser
STEP 1: BROWSE & SELECT
• Click "Browse Folder" to add a project folder
• Navigate through the file tree
• Click checkboxes (☐) next to files/folders to select them
2. SELECT
• Click checkboxes next to items to include them
• Use "Select All" to select everything
• Selecting a folder selects all its contents
3. CONFIGURE
• Set output file location
• Add custom file extensions if needed
4. GENERATE
• Click "Generate Documentation" button
• Wait for completion
• Open the generated code.txt file
Tips:
• The tool automatically ignores node_modules, .git, etc.
• Only code files are processed
• Large projects may take some time to process
"""
help_window = tk.Toplevel(self.root)
help_window.title("How to Use")
help_window.geometry("500x500")
text = scrolledtext.ScrolledText(help_window, wrap=tk.WORD, font=('TkDefaultFont', 10))
text.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
text.insert('1.0', help_text)
text.config(state='disabled')
ttk.Button(help_window, text="Close",
command=help_window.destroy).pack(pady=10)
def main():
root = tk.Tk()
app = CodebaseParserGUI(root)
root.mainloop()
if __name__ == "__main__":
main()