-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
344 lines (321 loc) · 14.2 KB
/
Copy pathapp.py
File metadata and controls
344 lines (321 loc) · 14.2 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
from textual.app import App, ComposeResult
import asyncio
from textual.widgets import Static, Header, Footer, Input, Button, DirectoryTree, Label
from textual.widget import Widget
from textual.containers import VerticalScroll
from pathlib import Path
from typing import List, Optional
class FileLineCounterApp(App):
"""A simple terminal app to count lines in any type of file."""
# Minimal, colorblind-friendly CSS with enhanced results styling
CSS = """
Header, Footer {
border: none;
}
Label, Static {
padding: 0 1;
margin: 0 0 1 0;
}
#dir_tree {
border: round #888;
margin: 1 0 1 0;
}
#select_dir_btn, #next_ignored_btn, #start_btn, #restart_btn {
border: round;
margin: 1 0 1 0;
}
Input {
border: round;
margin: 0 0 1 0;
}
.error-label {
color: #f00;
margin: 1 0 1 0;
}
.summary-label {
color: #00f;
}
.divider {
color: #888;
margin: 1 0 1 0;
}
/* Enhanced results styling */
.result-file {
padding: 0 1;
margin: 0;
background: #0f172a 10%;
}
.result-error {
color: #ef4444;
padding: 0 1;
margin: 0;
background: #450a0a 30%;
}
.summary-title {
color: #1df205;
text-style: bold;
padding: 0 1;
margin: 1 0 0 0;
background: #1e293b 20%;
}
.summary-stats {
color: #06b6d4;
padding: 0 2;
margin: 0;
}
.summary-breakdown {
padding: 0 3;
margin: 0;
}
.summary-total {
color: #f59e0b;
text-style: bold;
padding: 0 1;
margin: 0;
background: #292524 20%;
}
.section-divider {
color: #64748b;
margin: 0;
padding: 0 1;
}
.summary-divider {
color: #475569;
text-style: bold;
padding: 0 1;
margin: 0;
}
"""
IGNORED_DIRS = {
'.venv', 'venv', '.env', 'env', # Virtual environments
'node_modules', '.npm', # Node.js
'.git', '.svn', '.hg', # Version control
'__pycache__', '.pytest_cache', # Python cache
'build', 'dist', 'target', # Build directories
'.idea', '.vscode', # IDE directories
'vendor', '.vendor', # Dependencies
'coverage', '.coverage', # Coverage reports
'logs', '.logs', # Log directories
'.next', '.nuxt', # Framework cache
'temp', 'tmp', '.tmp', # Temporary directories
'bin', 'obj', # Compiled binaries
}
BINDINGS = [
("q", "quit", "Quit"),
("r", "restart", "Restart"),
]
def __init__(self):
super().__init__()
self.directory: Optional[Path] = None
self.extensions: Optional[List[str]] = None
self.extra_ignored_dirs: List[str] = []
self.results = []
self._state = "select_dir" # or "select_ext" or "select_extra_ignored" or "show_results"
def should_ignore_path(self, path: Path) -> bool:
"""Check if a path should be ignored based on its parts and extra ignored dirs."""
ignored = set(self.IGNORED_DIRS)
if hasattr(self, 'extra_ignored_dirs') and self.extra_ignored_dirs:
ignored = ignored.union({d.strip() for d in self.extra_ignored_dirs if d.strip()})
for part in path.parts:
if part in ignored:
return True
return False
async def count_lines_in_files(self):
"""Yield results for each file as they are processed, then yield the summary. Enhanced formatting for better visual separation."""
total_lines = 0
file_count = 0
ignored_files = 0
all_files = []
ext_stats = {ext: {'lines': 0, 'files': 0} for ext in self.extensions}
for ext in self.extensions:
pattern = f'*.{ext}'
files = list(self.directory.rglob(pattern))
all_files.extend(files)
ignored_files = len(all_files) - len([f for f in all_files if not self.should_ignore_path(f)])
all_files = [f for f in all_files if not self.should_ignore_path(f)]
all_files.sort()
for file_path in all_files:
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = sum(1 for _ in f)
try:
relative_path = file_path.relative_to(self.directory)
except ValueError:
relative_path = file_path
total_lines += lines
file_count += 1
ext = file_path.suffix.lstrip('.')
if ext in ext_stats:
ext_stats[ext]['lines'] += lines
ext_stats[ext]['files'] += 1
# Enhanced file result formatting with different colors for path and line count
yield ("file", f"{relative_path} [#94a3b8]•[/] [#fbbf24]{lines:,} lines[/]")
except Exception as e:
yield ("error", f"❌ {file_path.name} • Error: {str(e)[:40]}...")
total_files = file_count + ignored_files
percent_ignored = (ignored_files / total_files * 100) if total_files else 0
# Enhanced summary formatting with reduced emojis and better structure
summary_lines = []
summary_lines.append(("section-divider", ""))
summary_lines.append(("summary-divider", "━" * 50))
summary_lines.append(("summary-title", "📊 PROJECT SUMMARY"))
summary_lines.append(("summary-divider", "━" * 50))
summary_lines.append(("summary-stats", f"[b]Directory:[/b] {self.directory}"))
summary_lines.append(("summary-stats", f"[b]Extensions:[/b] {', '.join(f'.{ext}' for ext in self.extensions)}"))
if len(self.extensions) > 1:
summary_lines.append(("section-divider", ""))
summary_lines.append(("summary-stats", f"[b]Per-Extension Breakdown:[/b]"))
for ext in self.extensions:
summary_lines.append(("summary-breakdown", f".{ext}: [b]{ext_stats[ext]['files']}[/b] files • [b]{ext_stats[ext]['lines']:,}[/b] lines"))
summary_lines.append(("section-divider", ""))
summary_lines.append(("summary-divider", "─" * 30))
summary_lines.append(("summary-stats", f"[b]Total files:[/b] {total_files:,}"))
summary_lines.append(("summary-stats", f"[b]Files counted:[/b] {file_count:,}"))
if ignored_files > 0:
summary_lines.append(("summary-stats", f"[b]Files ignored:[/b] {ignored_files:,} ({percent_ignored:.1f}%)"))
else:
summary_lines.append(("summary-stats", f"[b]Files ignored:[/b] 0"))
summary_lines.append(("summary-divider", "─" * 30))
summary_lines.append(("summary-total", f"[b]📏 TOTAL LINES: {total_lines:,}[/b]"))
summary_lines.append(("summary-divider", "━" * 50))
for kind, line in summary_lines:
yield (kind, line)
async def _stream_results(self):
async def add_widget(widget: Widget):
await self.results_container.mount(widget)
# Always scroll to bottom after adding
self.results_container.scroll_end(animate=False)
async for kind, result in self.count_lines_in_files():
if kind == "file":
await add_widget(Static(result, classes="result-file"))
elif kind == "error":
await add_widget(Static(result, classes="result-error"))
elif kind == "section-divider":
await add_widget(Static(result, classes="section-divider"))
elif kind == "summary-title":
await add_widget(Static(result, classes="summary-title"))
elif kind == "summary-stats":
await add_widget(Static(result, classes="summary-stats"))
elif kind == "summary-breakdown":
await add_widget(Static(result, classes="summary-breakdown"))
elif kind == "summary-total":
await add_widget(Static(result, classes="summary-total"))
elif kind == "summary-divider":
await add_widget(Static(result, classes="summary-divider"))
def compose(self) -> ComposeResult:
"""Compose the app layout with a minimal, colorblind-friendly UI and loader."""
yield Header(name="File Line Counter", icon="", show_clock=False)
if self._state == "select_dir":
yield Label("Choose a directory to scan:", classes="divider")
yield DirectoryTree(str(Path("/")), id="dir_tree")
yield Label("Or enter a directory path:")
yield Input(placeholder="/full/path/to/your/project", id="dir_path_input")
yield Button("Select Directory", id="select_dir_btn")
elif self._state == "select_ext":
yield Label(f"Directory: {self.directory}", classes="divider")
yield Label("File extensions (comma or space separated):")
yield Input(placeholder="e.g. py js ts", id="ext_input")
yield Button("Next", id="next_ignored_btn")
elif self._state == "select_extra_ignored":
yield Label(f"Directory: {self.directory}")
yield Label(f"Extensions: {', '.join(self.extensions) if self.extensions else ''}", classes="divider")
yield Label("Extra directories to ignore (optional):")
yield Input(placeholder="e.g. build dist myfolder", id="extra_ignored_input")
yield Label("Directories to be ignored by default include:")
yield Static(", ".join(sorted(self.IGNORED_DIRS)), classes="divider")
yield Button("Start", id="start_btn")
elif self._state == "loading":
from textual.widgets import LoadingIndicator
yield Label("Analyzing files... Please wait.", classes="divider")
yield LoadingIndicator()
elif self._state == "show_results":
# Container to hold results dynamically
self.results_container = VerticalScroll()
yield self.results_container
yield Button("Restart", id="restart_btn")
yield Label("Press 'q' to quit or use the button above to scan another directory.", classes="divider")
# Run streaming of results as a background worker for true real-time updates
self.run_worker(self._stream_results, exclusive=True)
async def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "restart_btn":
await self.action_restart()
return
if event.button.id == "select_dir_btn":
dir_path_input = self.query_one("#dir_path_input", Input)
dir_path_text = dir_path_input.value.strip() if dir_path_input else ""
if dir_path_text:
path = Path(dir_path_text).expanduser().resolve()
if path.is_dir():
self.directory = path
self._state = "select_ext"
await self.recompose()
else:
self.notify(f"❌ '{dir_path_text}' is not a valid directory.", severity="error")
return
dir_tree = self.query_one("#dir_tree", DirectoryTree)
node = dir_tree.cursor_node
# Get the path from the selected node
if node is not None:
if hasattr(node.data, 'path'):
path = node.data.path
else:
path = Path(str(node.data))
else:
path = Path(dir_tree.path)
if path.is_dir():
self.directory = path
self._state = "select_ext"
await self.recompose()
else:
self.notify("❌ Please highlight a directory, not a file.", severity="error")
return
if event.button.id == "next_ignored_btn":
ext_input = self.query_one("#ext_input", Input)
ext_text = ext_input.value.strip()
if not ext_text:
self.notify("❌ Please enter at least one extension.", severity="error")
return
self.extensions = [e.strip().lstrip('.') for e in ext_text.replace(',', ' ').split() if e.strip()]
self._state = "select_extra_ignored"
await self.recompose()
return
if event.button.id == "start_btn":
try:
extra_ignored_input = self.query_one("#extra_ignored_input", Input)
extra_ignored_text = extra_ignored_input.value.strip()
self.extra_ignored_dirs = [d.strip() for d in extra_ignored_text.replace(',', ' ').split() if d.strip()]
except Exception:
self.extra_ignored_dirs = []
self._state = "loading"
await self.recompose()
# Let the UI update to show the loader before blocking
await asyncio.sleep(0.1)
self._state = "show_results"
await self.recompose()
async def on_input_submitted(self, event: Input.Submitted) -> None:
if event.input.id == "dir_path_input":
await self.on_button_pressed(Button.Pressed(self.query_one("#select_dir_btn", Button)))
elif event.input.id == "ext_input":
await self.on_button_pressed(Button.Pressed(self.query_one("#next_ignored_btn", Button)))
elif event.input.id == "extra_ignored_input":
await self.on_button_pressed(Button.Pressed(self.query_one("#start_btn", Button)))
async def action_restart(self) -> None:
"""Restart the app by resetting to directory selection."""
self.directory = None
self.extensions = None
self.extra_ignored_dirs = []
self.results = []
self._state = "select_dir"
await self.recompose()
if __name__ == "__main__":
try:
app = FileLineCounterApp()
app.title = "File Line Counter"
app.sub_title = "Interactive Directory Picker"
app.run()
except KeyboardInterrupt:
print("\n👋 Goodbye!")
except Exception as e:
print(f"❌ An error occurred: {e}")
import sys
sys.exit(1)