-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
353 lines (295 loc) · 11.6 KB
/
Copy pathgui.py
File metadata and controls
353 lines (295 loc) · 11.6 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
"""Smart Codebase Bundler — tkinter GUI."""
from __future__ import annotations
import os
import re
import sys
import threading
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, scrolledtext, ttk
from main import cleanup, request_cancel, run_pipeline # never call main() — SystemExit
# Strip CSI/OSC ANSI escapes (colorama Fore/Style, etc.).
_ANSI_RE = re.compile(
r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\))"
)
def strip_ansi(text: str) -> str:
return _ANSI_RE.sub("", text)
class TextRedirector:
"""Thread-safe stdout/stderr → Log Text (ANSI stripped)."""
def __init__(self, widget: tk.Text, root: tk.Tk) -> None:
self._widget = widget
self._root = root
def write(self, message: str) -> int:
if not message:
return 0
clean = strip_ansi(message)
if clean:
self._root.after(0, self._append, clean)
return len(message)
def _append(self, text: str) -> None:
self._widget.configure(state=tk.NORMAL)
self._widget.insert(tk.END, text)
self._widget.see(tk.END)
self._widget.configure(state=tk.DISABLED)
def flush(self) -> None:
pass
class BundlerGUI:
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("Smart Codebase Bundler")
self.root.minsize(640, 520)
self.root.geometry("820x600")
self._running = False
self._closing = False
self._worker: threading.Thread | None = None
self._action_buttons: list[ttk.Button] = []
self.source_var = tk.StringVar(value=str(Path.cwd()))
self.output_var = tk.StringVar(value=str(Path.cwd() / "bundles"))
self.virtual_ignore_var = tk.StringVar(value="")
self._build_ui()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
self._stdout_orig = sys.stdout
self._stderr_orig = sys.stderr
redirector = TextRedirector(self.log_text, self.root)
sys.stdout = redirector # type: ignore[assignment]
sys.stderr = redirector # type: ignore[assignment]
def _build_ui(self) -> None:
pad = {"padx": 10, "pady": 6}
top = ttk.LabelFrame(self.root, text="Folders", padding=10)
top.pack(fill=tk.X, **pad)
ttk.Label(top, text="Source folder:").grid(row=0, column=0, sticky=tk.W, pady=4)
ttk.Entry(top, textvariable=self.source_var).grid(
row=0, column=1, sticky=tk.EW, padx=(8, 8), pady=4
)
ttk.Button(top, text="Browse…", command=self._browse_source).grid(
row=0, column=2, pady=4
)
ttk.Label(top, text="Output folder:").grid(row=1, column=0, sticky=tk.W, pady=4)
ttk.Entry(top, textvariable=self.output_var).grid(
row=1, column=1, sticky=tk.EW, padx=(8, 8), pady=4
)
ttk.Button(top, text="Browse…", command=self._browse_output).grid(
row=1, column=2, pady=4
)
top.columnconfigure(1, weight=1)
ignore_frame = ttk.LabelFrame(
self.root,
text="Virtual Ignore (excluded from pack — not written to disk)",
padding=10,
)
ignore_frame.pack(fill=tk.X, **pad)
ttk.Label(ignore_frame, text="Paths:").grid(row=0, column=0, sticky=tk.NW, pady=4)
ttk.Entry(ignore_frame, textvariable=self.virtual_ignore_var).grid(
row=0, column=1, sticky=tk.EW, padx=(8, 8), pady=4
)
ignore_btns = ttk.Frame(ignore_frame)
ignore_btns.grid(row=0, column=2, sticky=tk.N, pady=4)
ttk.Button(ignore_btns, text="Add files", command=self._pick_ignore_files).pack(
fill=tk.X, pady=(0, 4)
)
ttk.Button(ignore_btns, text="Add folder", command=self._pick_ignore_dir).pack(
fill=tk.X, pady=(0, 4)
)
ttk.Button(ignore_btns, text="Clear", command=self._clear_ignore).pack(fill=tk.X)
ttk.Label(
ignore_frame,
text="Comma-separated absolute paths → SMART_BUNDLER_VIRTUAL_IGNORE",
).grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=(4, 0))
ignore_frame.columnconfigure(1, weight=1)
mid = ttk.LabelFrame(self.root, text="Actions (CLI equivalents)", padding=10)
mid.pack(fill=tk.X, **pad)
grid = ttk.Frame(mid)
grid.pack(fill=tk.X)
actions: list[tuple[str, str, bool, bool]] = [
(
"1 · Token cost",
"main.py -d\nNo write · ~tokens for changed modules",
False,
True,
),
(
"2 · Dry run",
"main.py -d -f\nNo write · preview all as REBUILD",
True,
True,
),
(
"3 · Force run",
"main.py -f\nWrite · ignore cache, rebuild all",
True,
False,
),
(
"4 · Bundle",
"main.py\nWrite · rebuild changed modules only",
False,
False,
),
]
for col, (title, hint, force, dry_run) in enumerate(actions):
cell = ttk.Frame(grid, padding=(4, 2))
cell.grid(row=0, column=col, sticky=tk.NSEW, padx=4)
btn = ttk.Button(
cell,
text=title,
command=lambda f=force, d=dry_run, t=title: self._start_pipeline(
force=f, dry_run=d, label=t
),
)
btn.pack(fill=tk.X, ipady=10)
ttk.Label(cell, text=hint, justify=tk.CENTER, wraplength=170).pack(
fill=tk.X, pady=(6, 0)
)
self._action_buttons.append(btn)
grid.columnconfigure(col, weight=1)
bottom = ttk.LabelFrame(self.root, text="Log", padding=10)
bottom.pack(fill=tk.BOTH, expand=True, **pad)
self.log_text = scrolledtext.ScrolledText(
bottom,
wrap=tk.WORD,
state=tk.DISABLED,
height=16,
font=("Consolas", 10),
)
self.log_text.pack(fill=tk.BOTH, expand=True)
def _browse_source(self) -> None:
path = filedialog.askdirectory(
title="Select source folder",
initialdir=self.source_var.get() or str(Path.cwd()),
)
if path:
self.source_var.set(path)
def _browse_output(self) -> None:
path = filedialog.askdirectory(
title="Select output folder",
initialdir=self.output_var.get() or str(Path.cwd()),
)
if path:
self.output_var.set(path)
def _ignore_paths(self) -> list[str]:
raw = self.virtual_ignore_var.get()
return [p.strip() for p in raw.split(",") if p.strip()]
def _set_ignore_paths(self, paths: list[str]) -> None:
seen: set[str] = set()
ordered: list[str] = []
for p in paths:
key = os.path.normcase(os.path.normpath(p))
if key in seen:
continue
seen.add(key)
ordered.append(p)
self.virtual_ignore_var.set(",".join(ordered))
def _append_ignore_paths(self, new_paths: list[str]) -> None:
if not new_paths:
return
self._set_ignore_paths(self._ignore_paths() + list(new_paths))
def _pick_ignore_files(self) -> None:
initial = self.source_var.get() or str(Path.cwd())
chosen = filedialog.askopenfilenames(
title="Files to exclude from packing",
initialdir=initial,
)
if chosen:
self._append_ignore_paths([str(Path(p).resolve()) for p in chosen])
def _pick_ignore_dir(self) -> None:
initial = self.source_var.get() or str(Path.cwd())
chosen = filedialog.askdirectory(
title="Folder to exclude from packing",
initialdir=initial,
)
if chosen:
self._append_ignore_paths([str(Path(chosen).resolve())])
def _clear_ignore(self) -> None:
self.virtual_ignore_var.set("")
def _set_busy(self, busy: bool) -> None:
"""Disable action buttons while a run is in progress (FR-1.2 / _active_writer)."""
self._running = busy
state = tk.DISABLED if busy else tk.NORMAL
for btn in self._action_buttons:
btn.configure(state=state)
def _log(self, message: str) -> None:
self.log_text.configure(state=tk.NORMAL)
self.log_text.insert(tk.END, message + "\n")
self.log_text.see(tk.END)
self.log_text.configure(state=tk.DISABLED)
def _start_pipeline(self, *, force: bool, dry_run: bool, label: str) -> None:
if self._running:
return
source = self.source_var.get().strip()
output = self.output_var.get().strip()
if not source or not Path(source).is_dir():
messagebox.showerror("Error", "Please select a valid source folder.")
return
if not output:
messagebox.showerror("Error", "Output folder path cannot be empty.")
return
os.environ["SMART_BUNDLER_ROOT"] = str(Path(source).resolve())
os.environ["SMART_BUNDLER_OUTPUT"] = str(Path(output).resolve())
ignore_paths = self._ignore_paths()
if ignore_paths:
os.environ["SMART_BUNDLER_VIRTUAL_IGNORE"] = ",".join(ignore_paths)
else:
os.environ.pop("SMART_BUNDLER_VIRTUAL_IGNORE", None)
self._set_busy(True)
self._log(f"--- {label} started ---")
self._log(f"ROOT={os.environ['SMART_BUNDLER_ROOT']}")
self._log(f"OUTPUT={os.environ['SMART_BUNDLER_OUTPUT']}")
self._log(f"force={force} dry_run={dry_run}")
self._log(f"virtual_ignore={len(ignore_paths)} path(s)")
for p in ignore_paths:
self._log(f" - {p}")
def worker() -> None:
code = 1
try:
code = run_pipeline(force=force, dry_run=dry_run)
except Exception as exc: # noqa: BLE001
sys.stderr.write(f"Error: {exc}\n")
code = 1
finally:
self.root.after(0, self._on_pipeline_done, code)
self._worker = threading.Thread(target=worker, daemon=True)
self._worker.start()
def _on_pipeline_done(self, code: int) -> None:
if self._closing:
self._finish_close()
return
self._log(f"--- Finished (exit code: {code}) ---")
self._set_busy(False)
def _on_close(self) -> None:
"""Do not delete TEMP while the worker still writes (FR-1.2 race fix)."""
if self._closing:
return
self._closing = True
if self._running and self._worker is not None and self._worker.is_alive():
try:
request_cancel()
except Exception: # noqa: BLE001
pass
self._set_busy(True)
self._log("Closing: waiting for worker / cleanup…")
self.root.after(200, self._poll_close)
return
self._finish_close()
def _poll_close(self) -> None:
if self._worker is not None and self._worker.is_alive():
self.root.after(200, self._poll_close)
return
self._finish_close()
def _finish_close(self) -> None:
sys.stdout = self._stdout_orig
sys.stderr = self._stderr_orig
try:
cleanup()
except Exception: # noqa: BLE001
pass
self.root.destroy()
def main() -> None:
root = tk.Tk()
try:
root.call("tk", "scaling", 1.25)
except tk.TclError:
pass
BundlerGUI(root)
root.mainloop()
if __name__ == "__main__":
main()