-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproject_stats_counter.py
More file actions
435 lines (383 loc) · 10.3 KB
/
Copy pathproject_stats_counter.py
File metadata and controls
435 lines (383 loc) · 10.3 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
import os
import re
import sys
import argparse
from collections import defaultdict
from datetime import datetime
# File extensions to analyze
TEXT_EXTENSIONS = {
"Code": [
".py",
".js",
".java",
".c",
".cpp",
".h",
".hpp",
".cs",
".php",
".rb",
".go",
".rs",
".swift",
".kt",
".kts",
".scala",
".ts",
".tsx",
".jsx",
".html",
".htm",
".css",
".scss",
".sass",
".less",
".sql",
".sh",
".bash",
".bat",
".ps1",
".cmd",
".lua",
".r",
".pl",
".pm",
".tcl",
".awk",
".sed",
".dart",
".groovy",
".vb",
".vbs",
".asm",
".f",
".f90",
".f95",
".m",
".ml",
".mli",
".swift",
".vue",
".elm",
".clj",
".cljs",
".cljc",
".ex",
".exs",
".erl",
".hrl",
".lisp",
".lsp",
".hs",
".purs",
".ada",
".d",
".nim",
".zig",
".jl",
".cr",
".json5",
".hx",
".wren",
".p4",
".rkt",
".idris",
".e",
".pike",
".lean",
".v",
".agda",
".cob",
".cpy",
".abap",
".rpg",
".4gl",
".chpl",
".rex",
".omgrofl",
],
"Markup": [
".md",
".rst",
".txt",
".tex",
".latex",
".bib",
".json",
".yaml",
".yml",
".toml",
".ini",
".cfg",
".conf",
".properties",
".csv",
".tsv",
".xml",
".xsl",
".xsd",
".xslt",
".xhtml",
".svg",
".rss",
".atom",
],
"Documentation": [
".doc",
".docx",
".pdf",
".rtf",
".odt",
".fodt",
".sxw",
".wpd",
".texi",
".me",
".ms",
],
"Scripts": [
".ps1",
".cmd",
".bat",
".vbs",
".applescript",
".ahk",
".ksh",
".zsh",
".fish",
".csh",
".tcsh",
".mak",
".mk",
".ninja",
".ebuild",
".eclass",
".pkgbuild",
],
"Config": [
".env",
".venv",
".editorconfig",
".gitattributes",
".gitignore",
".gitmodules",
".dockerfile",
".npmrc",
".yarnrc",
".babelrc",
".eslint",
".prettierrc",
".stylelintrc",
".condarc",
".flake8",
".pylintrc",
".mypy.ini",
".pydocstyle",
".phpcs",
".phpmd",
],
}
# Directories to exclude from analysis
EXCLUDE_DIRS = [
".git",
"node_modules",
"build",
"dist",
"__pycache__",
".idea",
".vscode",
"vendor",
"bin",
"obj",
]
# Binary file signatures to detect quickly
BINARY_SIGNATURES = [
b"\x89PNG",
b"GIF8",
b"BM",
b"\xFF\xD8\xFF",
b"PK\x03\x04",
b"%PDF",
b"\x7FELF",
b"MZ",
b"\xCF\xFA\xED\xFE",
b"\xCA\xFE\xBA\xBE",
]
def is_binary(file_path, sample_size=8192):
"""
Check if a file is binary by reading its first few bytes.
"""
try:
with open(file_path, "rb") as f:
header = f.read(sample_size)
# Check for known binary signatures
for signature in BINARY_SIGNATURES:
if header.startswith(signature):
return True
# Check for null bytes which commonly indicate binary files
if b"\x00" in header:
return True
# If more than 30% of the bytes are non-text, it's likely binary
text_characters = bytes(range(32, 127)) + b"\r\n\t\b"
binary_chars = sum(1 for byte in header if byte not in text_characters)
return binary_chars / len(header) > 0.3 if header else False
except (IOError, OSError):
return True # If we can't read the file, consider it binary to be safe
def get_file_extension_category(file_path):
"""
Determine the category of a file based on its extension.
"""
_, ext = os.path.splitext(file_path.lower())
for category, extensions in TEXT_EXTENSIONS.items():
if ext in extensions:
return category
# For unknown extensions, try to determine if it's text or binary
if not is_binary(file_path):
return "Other Text"
return None # Not a text file we're interested in
def count_lines_and_chars(file_path):
"""
Count the number of lines and characters in a file.
Returns a tuple of (lines, characters)
"""
try:
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
lines = content.count("\n") + (
1 if content and not content.endswith("\n") else 0
)
chars = len(content)
return lines, chars
except Exception as e:
print(f"Error reading {file_path}: {e}")
return 0, 0
def format_number(num):
"""Format a number with thousands separators."""
return f"{num:,}"
def analyze_directory(target_dir):
"""
Analyze files in the specified directory and return statistics.
"""
dir_stats = defaultdict(lambda: {"files": 0, "lines": 0, "chars": 0})
dir_total_files = 0
dir_total_lines = 0
dir_total_chars = 0
print(f"\nScanning files in {target_dir}...\n")
for root, dirs, files in os.walk(target_dir):
# Skip excluded directories
dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]
for file in files:
file_path = os.path.join(root, file)
# Skip this script itself
if os.path.abspath(file_path) == os.path.abspath(__file__):
continue
category = get_file_extension_category(file_path)
if not category:
continue # Skip binary or undesired files
lines, chars = count_lines_and_chars(file_path)
dir_stats[category]["files"] += 1
dir_stats[category]["lines"] += lines
dir_stats[category]["chars"] += chars
dir_total_files += 1
dir_total_lines += lines
dir_total_chars += chars
return dir_stats, dir_total_files, dir_total_lines, dir_total_chars
def format_statistics(stat_dict, files_count, lines_count, chars_count):
"""
Format the statistics as a string.
"""
output = ["=" * 80, f"PROJECT STATISTICS SUMMARY", "=" * 80]
# Print by category
categories = sorted(stat_dict.keys())
for category in categories:
cat_stats = stat_dict[category]
output.append(f"\n{category} Files:")
output.append(f" Files: {format_number(cat_stats['files'])}")
output.append(f" Lines: {format_number(cat_stats['lines'])}")
output.append(f" Characters: {format_number(cat_stats['chars'])}")
# Print totals
output.append("\n" + "=" * 80)
output.append(
f"TOTAL: {format_number(files_count)} files, {format_number(lines_count)} lines, {format_number(chars_count)} characters"
)
output.append("=" * 80)
return "\n".join(output)
def save_statistics_to_file(stats_output):
"""
Save the statistics to a text file and return the file path.
"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"project_stats_{timestamp}.txt"
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
with open(file_path, "w", encoding="utf-8") as f:
f.write(stats_output)
return file_path
def display_and_menu(stat_dict, files_count, lines_count, chars_count, args_obj):
"""
Display statistics and show interactive menu.
"""
stats_output = format_statistics(stat_dict, files_count, lines_count, chars_count)
print(stats_output)
while True:
print("\nOptions:")
print("1. Save statistics to a text file")
print("2. Quit")
if not args_obj.dir: # Only offer to run again if not in command-line mode
print("3. Run again")
choice = input("\nEnter your choice (1-3): ").strip()
if choice == "1":
# Save the file immediately when option is chosen
file_path = save_statistics_to_file(stats_output)
print(f"\nStatistics saved to: {file_path}")
# Now ask what to do next
print("\nOptions:")
print("1. Quit")
print("2. Run again")
next_choice = input("\nEnter your choice (1-2): ").strip()
if next_choice == "1" or next_choice.lower() == "q":
print("Exiting program.")
sys.exit(0)
elif next_choice == "2":
return True # Run again
elif choice == "2" or choice.lower() == "q":
print("Exiting program.")
sys.exit(0)
elif choice == "3" and not args_obj.dir:
return True # Run again
else:
print("Invalid choice. Please try again.")
def parse_arguments():
"""
Parse command line arguments.
"""
parser = argparse.ArgumentParser(
description="Project Statistics Counter - Analyze and count files, lines, and characters in a project."
)
parser.add_argument(
"-dir",
"--directory",
dest="dir",
help="Directory to analyze (default: current directory)",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
while True:
target_directory = args.dir if args.dir else "."
(
directory_stats,
directory_total_files,
directory_total_lines,
directory_total_chars,
) = analyze_directory(target_directory)
if not display_and_menu(
directory_stats,
directory_total_files,
directory_total_lines,
directory_total_chars,
args,
):
break
# If running again and in command-line mode, exit after one run
if args.dir:
break