-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirParser.py
More file actions
200 lines (165 loc) · 9.33 KB
/
dirParser.py
File metadata and controls
200 lines (165 loc) · 9.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
import os
import sys
import threading
import tkinter as tk
from tkinter import filedialog, scrolledtext
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
class AdvDirParserApp:
def __init__(self, root):
self.root = root
self.root.title("DirParser Pro")
self.root.geometry("1100x700")
# Data storage
self.selected_folder_path = None
self.file_content_map = {} # Stores {relative_path: formatted_content}
self.checkbox_vars = {} # Stores {relative_path: tk.BooleanVar}
# --- Style Configuration ---
style = ttk.Style(theme='darkly')
self.font_main = ("Segoe UI", 11)
self.font_code = ("Consolas", 10) # A good monospaced font for code
# --- Main Layout Frames ---
self.control_frame = ttk.Frame(root, padding=(20, 10))
self.control_frame.pack(fill=X, side=TOP)
self.control_frame.grid_columnconfigure(1, weight=1)
# PanedWindow allows resizing the sidebar
self.main_paned_window = ttk.PanedWindow(root, orient=HORIZONTAL)
self.main_paned_window.pack(fill=BOTH, expand=True, padx=10, pady=10)
# --- Widgets ---
self.setup_controls()
self.setup_sidebar()
self.setup_output_area()
def setup_controls(self):
"""Sets up the top control bar with buttons and labels."""
# (Same as before)
self.select_btn = ttk.Button(self.control_frame, text="Select Folder", command=self.select_folder, style='primary.TButton')
self.select_btn.grid(row=0, column=0, padx=(10, 10))
self.folder_label = ttk.Label(self.control_frame, text="No folder selected...", font=self.font_main, style='secondary.TLabel')
self.folder_label.grid(row=0, column=1, sticky="ew")
self.start_btn = ttk.Button(self.control_frame, text="Start Parsing", command=self.start_parsing_thread, state=DISABLED, style='success.TButton')
self.start_btn.grid(row=0, column=2, padx=10)
self.copy_btn = ttk.Button(self.control_frame, text="Copy Output", command=self.copy_to_clipboard, state=DISABLED, style='info.TButton')
self.copy_btn.grid(row=0, column=3, padx=(0, 10))
def setup_sidebar(self):
"""Sets up the scrollable frame for the file checklist."""
sidebar_container = ttk.Frame(self.main_paned_window, padding=5)
# This Label acts as a title for the sidebar
title_label = ttk.Label(sidebar_container, text="Included Files", font=self.font_main)
title_label.pack(anchor="w", pady=(0, 5))
# The standard way to make a scrollable frame in tkinter
self.sidebar_canvas = tk.Canvas(sidebar_container, highlightthickness=0, bg=self.root["bg"])
self.sidebar_scrollbar = ttk.Scrollbar(sidebar_container, orient="vertical", command=self.sidebar_canvas.yview)
self.scrollable_frame = ttk.Frame(self.sidebar_canvas)
self.scrollable_frame.bind("<Configure>", lambda e: self.sidebar_canvas.configure(scrollregion=self.sidebar_canvas.bbox("all")))
self.sidebar_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.sidebar_canvas.configure(yscrollcommand=self.sidebar_scrollbar.set)
self.sidebar_canvas.pack(side="left", fill="both", expand=True)
self.sidebar_scrollbar.pack(side="right", fill="y")
self.main_paned_window.add(sidebar_container, weight=1) # Add sidebar to the resizable pane
def setup_output_area(self):
"""Sets up the main text display area."""
output_container = ttk.Frame(self.main_paned_window)
self.output_text = scrolledtext.ScrolledText(
output_container, wrap=tk.WORD, font=self.font_code, relief="flat",
borderwidth=0, highlightthickness=1, highlightcolor="#555"
)
self.output_text.pack(fill=BOTH, expand=True)
self.output_text.insert(tk.END, "Select a folder and click 'Start Parsing'...")
self.output_text.config(state=DISABLED)
self.main_paned_window.add(output_container, weight=4) # Add output area, give it more space
def select_folder(self):
"""Opens folder dialog and resets the state."""
folder_path = filedialog.askdirectory(title="Select a Project Folder")
if folder_path:
self.selected_folder_path = folder_path
display_path = folder_path
if len(display_path) > 70: display_path = "..." + display_path[-67:]
self.folder_label.config(text=display_path)
self.start_btn.config(state=NORMAL)
self.copy_btn.config(state=DISABLED)
# Clear previous results
self.clear_results()
def clear_results(self):
"""Clears all previous parsing data from the UI."""
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
self.output_text.config(state=NORMAL)
self.output_text.delete(1.0, tk.END)
self.output_text.insert(tk.END, "Ready to parse new folder.")
self.output_text.config(state=DISABLED)
self.file_content_map.clear()
self.checkbox_vars.clear()
def start_parsing_thread(self):
"""Starts the parsing in a background thread to keep the GUI responsive."""
if self.selected_folder_path:
self.start_btn.config(state=DISABLED)
self.select_btn.config(state=DISABLED)
self.clear_results()
self.output_text.config(state=NORMAL)
self.output_text.delete(1.0, tk.END)
self.output_text.insert(tk.END, "Scanning and parsing files, please wait...")
self.output_text.config(state=DISABLED)
thread = threading.Thread(target=self.parse_directory, daemon=True)
thread.start()
def parse_directory(self):
"""Core logic: walks directory, reads files, and stores their content."""
for dirpath, _, filenames in os.walk(self.selected_folder_path):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
if self.is_text_file(full_path):
relative_path = os.path.relpath(full_path, self.selected_folder_path).replace("\\", "/") # Normalize slashes
try:
with open(full_path, 'r', encoding='utf-8', errors='ignore') as file:
content = file.read()
# Store the formatted content for later use
self.file_content_map[relative_path] = f"\n\n---\n\n{relative_path}\n\n{content}"
except Exception as e:
print(f"Could not read file {full_path}: {e}")
# Schedule the GUI update to run on the main thread
self.root.after(0, self.populate_ui_with_results)
def populate_ui_with_results(self):
"""Creates the checkboxes in the sidebar and triggers the first output generation."""
# Create a checkbox for each file found
for path in sorted(self.file_content_map.keys()):
var = tk.BooleanVar(value=True)
self.checkbox_vars[path] = var
cb = ttk.Checkbutton(self.scrollable_frame, text=path, variable=var, command=self.regenerate_output, style='primary.TCheckbutton')
cb.pack(anchor="w", padx=5, pady=2)
self.regenerate_output() # Initial generation of the output
self.select_btn.config(state=NORMAL)
def regenerate_output(self):
"""Builds the final output string based on which checkboxes are currently ticked."""
main_dir_name = os.path.basename(self.selected_folder_path)
output_parts = [f"main directory:\n{main_dir_name}"]
# Iterate through the sorted list of files to maintain order
for path in sorted(self.file_content_map.keys()):
if self.checkbox_vars[path].get(): # Check if the box is ticked
output_parts.append(self.file_content_map[path])
final_output = "".join(output_parts)
self.output_text.config(state=NORMAL)
self.output_text.delete(1.0, tk.END)
self.output_text.insert(tk.END, final_output)
self.output_text.config(state=DISABLED)
self.copy_btn.config(state=NORMAL if final_output else DISABLED)
def copy_to_clipboard(self):
# (Same as before)
self.root.clipboard_clear()
self.root.clipboard_append(self.output_text.get(1.0, tk.END))
original_text = self.copy_btn['text']
self.copy_btn.config(text="Copied!", style='success.TButton')
self.root.after(1500, lambda: self.copy_btn.config(text=original_text, style='info.TButton'))
@staticmethod
def is_text_file(filepath):
# (Same as before)
text_extensions = [
'.txt', '.md', '.html', '.css', '.js', '.json', '.xml', '.yaml', '.yml',
'.py', '.java', '.c', '.cpp', '.h', '.hpp', '.cs', '.sh', '.rb', '.php',
'.go', '.rs', '.swift', '.kt', '.kts', '.sql', '.ini', '.cfg', '.conf',
'.gitignore', '.gitattributes', '.env', 'Dockerfile', '.dockerignore',
]
# Check against a lowercased path to be case-insensitive
return any(filepath.lower().endswith(ext) for ext in text_extensions)
if __name__ == "__main__":
root = ttk.Window(themename="darkly")
app = AdvDirParserApp(root)
root.mainloop()