-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepo_stats.py
More file actions
1151 lines (985 loc) · 40.9 KB
/
repo_stats.py
File metadata and controls
1151 lines (985 loc) · 40.9 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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
repo-stats – Advanced Repository Analysis CLI
Analyzes local or remote Git repositories and generates detailed statistics.
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
# ─────────────────────────────────────────────
# Language Detection
# ─────────────────────────────────────────────
LANGUAGE_MAP = {
".py": "Python",
".js": "JavaScript",
".mjs": "JavaScript",
".cjs": "JavaScript",
".ts": "TypeScript",
".tsx": "TypeScript",
".jsx": "JavaScript",
".cs": "C#",
".java": "Java",
".cpp": "C++",
".cc": "C++",
".cxx": "C++",
".c": "C",
".h": "C/C++ Header",
".hpp": "C/C++ Header",
".go": "Go",
".rs": "Rust",
".rb": "Ruby",
".php": "PHP",
".swift": "Swift",
".kt": "Kotlin",
".kts": "Kotlin",
".scala": "Scala",
".r": "R",
".R": "R",
".m": "Objective-C",
".mm": "Objective-C",
".lua": "Lua",
".pl": "Perl",
".pm": "Perl",
".sh": "Shell",
".bash": "Shell",
".zsh": "Shell",
".fish": "Shell",
".ps1": "PowerShell",
".psm1": "PowerShell",
".html": "HTML",
".htm": "HTML",
".css": "CSS",
".scss": "SCSS",
".sass": "SCSS",
".less": "Less",
".xml": "XML",
".json": "JSON",
".yaml": "YAML",
".yml": "YAML",
".toml": "TOML",
".ini": "INI",
".cfg": "INI",
".conf": "INI",
".md": "Markdown",
".rst": "reStructuredText",
".tex": "LaTeX",
".sql": "SQL",
".vue": "Vue",
".svelte": "Svelte",
".dart": "Dart",
".ex": "Elixir",
".exs": "Elixir",
".erl": "Erlang",
".hrl": "Erlang",
".hs": "Haskell",
".lhs": "Haskell",
".clj": "Clojure",
".cljs": "Clojure",
".fs": "F#",
".fsx": "F#",
".fsi": "F#",
".groovy": "Groovy",
".gradle": "Groovy",
".tf": "Terraform",
".dockerfile": "Dockerfile",
".makefile": "Makefile",
".mk": "Makefile",
}
# Files without extensions that are recognized
SPECIAL_FILES = {
"Dockerfile": "Dockerfile",
"Makefile": "Makefile",
"GNUmakefile": "Makefile",
"Gemfile": "Ruby",
"Rakefile": "Ruby",
"Vagrantfile": "Ruby",
"Procfile": "Shell",
"Brewfile": "Ruby",
}
COMMENT_PATTERNS = {
"Python": (r"^\s*#", r'^\s*("""|\'\'\')'),
"JavaScript": (r"^\s*//", r"^\s*/\*"),
"TypeScript": (r"^\s*//", r"^\s*/\*"),
"C#": (r"^\s*//", r"^\s*/\*"),
"Java": (r"^\s*//", r"^\s*/\*"),
"C++": (r"^\s*//", r"^\s*/\*"),
"C": (r"^\s*//", r"^\s*/\*"),
"Go": (r"^\s*//", r"^\s*/\*"),
"Rust": (r"^\s*//", r"^\s*/\*"),
"Swift": (r"^\s*//", r"^\s*/\*"),
"Kotlin": (r"^\s*//", r"^\s*/\*"),
"Scala": (r"^\s*//", r"^\s*/\*"),
"PHP": (r"^\s*//", r"^\s*/\*"),
"Ruby": (r"^\s*#", None),
"Shell": (r"^\s*#", None),
"PowerShell": (r"^\s*#", r"^\s*<#"),
"HTML": (None, r"^\s*<!--"),
"CSS": (None, r"^\s*/\*"),
"SCSS": (r"^\s*//", r"^\s*/\*"),
"SQL": (r"^\s*--", r"^\s*/\*"),
"Lua": (r"^\s*--", None),
"Haskell": (r"^\s*--", None),
"Elixir": (r"^\s*#", None),
"Erlang": (r"^\s*%", None),
"R": (r"^\s*#", None),
}
TODO_PATTERNS = re.compile(
r"\b(TODO|FIXME|HACK|NOTE|BUG|XXX|OPTIMIZE|REVIEW|DEPRECATED)\b",
re.IGNORECASE,
)
IGNORE_DIRS = {
"node_modules", ".git", ".svn", ".hg",
"bin", "obj", "build", "dist", "out",
"__pycache__", ".mypy_cache", ".pytest_cache",
".tox", "venv", ".venv", "env", ".env",
".idea", ".vscode", ".vs",
"target", "vendor", "packages",
".terraform", ".next", ".nuxt",
"coverage", ".nyc_output", "htmlcov",
"eggs", ".eggs", "wheels", "*.egg-info",
}
IGNORE_EXTENSIONS = {
".pyc", ".pyo", ".pyd", ".class", ".o", ".so", ".a", ".lib",
".dll", ".exe", ".jar", ".war", ".ear",
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".svg", ".webp",
".tiff", ".psd", ".ai",
".mp3", ".mp4", ".wav", ".avi", ".mov", ".mkv",
".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar",
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
".lock", ".sum",
".min.js", ".min.css",
}
DEPENDENCY_FILES = {
"package.json": "Node.js",
"requirements.txt": "Python (pip)",
"Pipfile": "Python (Pipenv)",
"pyproject.toml": "Python (pyproject)",
"go.mod": "Go",
"Cargo.toml": "Rust",
"pom.xml": "Java (Maven)",
"build.gradle": "Java (Gradle)",
"*.csproj": "NuGet (.NET)",
"composer.json": "PHP (Composer)",
"Gemfile": "Ruby (Gems)",
"pubspec.yaml": "Dart/Flutter",
"Package.swift": "Swift",
"mix.exs": "Elixir",
"rebar.config": "Erlang",
"stack.yaml": "Haskell",
"cabal.project": "Haskell",
"conanfile.txt": "C++ (Conan)",
"vcpkg.json": "C++ (vcpkg)",
}
# ─────────────────────────────────────────────
# Data Structures
# ─────────────────────────────────────────────
@dataclass
class FileStats:
path: str
language: str
size_bytes: int
total_lines: int
code_lines: int
comment_lines: int
blank_lines: int
todos: dict = field(default_factory=dict)
@dataclass
class RepoStats:
repo_path: str
repo_name: str
# File stats
total_files: int = 0
total_lines: int = 0
code_lines: int = 0
comment_lines: int = 0
blank_lines: int = 0
total_size_bytes: int = 0
average_file_size: float = 0.0
# Language stats
languages: dict = field(default_factory=dict) # name -> {files, lines}
# File details
file_stats: list = field(default_factory=list)
largest_files: list = field(default_factory=list)
# Directory stats
directory_stats: dict = field(default_factory=dict)
# Git stats
git_available: bool = False
is_shallow_clone: bool = False
total_commits: int = 0
contributors: list = field(default_factory=list)
first_commit_date: Optional[str] = None
last_commit_date: Optional[str] = None
repo_age_days: int = 0
current_branch: Optional[str] = None
# TODOs
todos: dict = field(default_factory=dict)
todo_details: list = field(default_factory=list)
# Dependencies
dependencies: dict = field(default_factory=dict)
# Health metrics
avg_file_lines: float = 0.0
comment_ratio: float = 0.0
code_density: float = 0.0
# ─────────────────────────────────────────────
# Utility Functions
# ─────────────────────────────────────────────
def detect_language(path: Path) -> str:
"""Detect programming language from file extension or filename."""
name = path.name
if name in SPECIAL_FILES:
return SPECIAL_FILES[name]
ext = path.suffix.lower()
# Handle compound extensions like .min.js
if len(path.suffixes) >= 2:
compound = "".join(path.suffixes[-2:]).lower()
if compound in IGNORE_EXTENSIONS:
return None
if ext in IGNORE_EXTENSIONS:
return None
return LANGUAGE_MAP.get(ext, "Other")
def should_ignore_dir(name: str) -> bool:
return name in IGNORE_DIRS or name.startswith(".")
def is_binary(path: Path) -> bool:
"""Quick binary file check."""
try:
with open(path, "rb") as f:
chunk = f.read(8192)
return b"\x00" in chunk
except Exception:
return True
def analyze_file(path: Path, repo_root: Path) -> Optional[FileStats]:
"""Analyze a single file and return its stats."""
try:
if path.stat().st_size == 0:
language = detect_language(path)
if not language:
return None
return FileStats(
path=str(path.relative_to(repo_root)),
language=language,
size_bytes=0,
total_lines=0,
code_lines=0,
comment_lines=0,
blank_lines=0,
)
language = detect_language(path)
if not language:
return None
if is_binary(path):
return None
try:
content = path.read_text(encoding="utf-8", errors="replace")
except Exception:
return None
lines = content.splitlines()
total_lines = len(lines)
blank_lines = sum(1 for l in lines if not l.strip())
comment_lines = 0
todos = defaultdict(int)
todo_details = []
comment_single, comment_multi = COMMENT_PATTERNS.get(language, (None, None))
comment_re_single = re.compile(comment_single) if comment_single else None
comment_re_multi = re.compile(comment_multi) if comment_multi else None
in_multiline = False
multiline_end_pattern = None
for lineno, line in enumerate(lines, 1):
stripped = line.strip()
# Multi-line comment tracking (simplified)
if in_multiline:
comment_lines += 1
if multiline_end_pattern and re.search(multiline_end_pattern, line):
in_multiline = False
continue
if stripped:
is_comment = False
if comment_re_single and comment_re_single.match(line):
is_comment = True
elif comment_re_multi and comment_re_multi.match(line):
is_comment = True
if language == "Python" and ('"""' in line or "'''" in line):
count = line.count('"""') + line.count("'''")
if count < 2:
in_multiline = True
multiline_end_pattern = r'"""|\'\'\''
elif "/*" in line and "*/" not in line:
in_multiline = True
multiline_end_pattern = r"\*/"
elif "<!--" in line and "-->" not in line:
in_multiline = True
multiline_end_pattern = r"-->"
if is_comment:
comment_lines += 1
# TODO scanning
m = TODO_PATTERNS.search(line)
if m:
marker = m.group(1).upper()
todos[marker] = todos.get(marker, 0) + 1
code_lines = total_lines - blank_lines - comment_lines
return FileStats(
path=str(path.relative_to(repo_root)),
language=language,
size_bytes=path.stat().st_size,
total_lines=total_lines,
code_lines=max(0, code_lines),
comment_lines=comment_lines,
blank_lines=blank_lines,
todos=dict(todos),
)
except Exception:
return None
# ─────────────────────────────────────────────
# Repository Cloning
# ─────────────────────────────────────────────
def extract_repo_name_from_url(url: str) -> str:
"""Extract a human-friendly repo name from a remote URL."""
clean = url.rstrip("/")
if clean.endswith(".git"):
clean = clean[:-4]
# Handle git@github.com:user/repo style
clean = re.sub(r"^git@[^:]+:", "", clean)
parts = [p for p in clean.replace("\\", "/").split("/") if p]
if len(parts) >= 2:
return f"{parts[-2]}/{parts[-1]}"
elif parts:
return parts[-1]
return "remote-repo"
def resolve_repo(target: str, full_clone: bool = False) -> tuple[str, bool, str]:
"""
Resolve repository target to a local path.
Returns (path, is_temp, repo_name).
"""
# Local path
if os.path.exists(target):
return os.path.abspath(target), False, Path(os.path.abspath(target)).name
# GitHub shorthand user/repo
if re.match(r"^[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$", target):
target = f"https://github.com/{target}"
# Remote URL
if target.startswith(("http://", "https://", "git://", "git@", "ssh://")):
repo_name = extract_repo_name_from_url(target)
tmp_dir = tempfile.mkdtemp(prefix="repo-stats-")
clone_args = ["git", "clone", "--quiet"]
if not full_clone:
clone_args += ["--depth", "1"]
clone_args += [target, tmp_dir]
clone_type = "full clone" if full_clone else "shallow clone"
print(f" Cloning {target} ({clone_type})...")
try:
result = subprocess.run(
clone_args,
capture_output=True, text=True, timeout=300
)
if result.returncode != 0:
shutil.rmtree(tmp_dir, ignore_errors=True)
print(f" Error cloning: {result.stderr.strip()}", file=sys.stderr)
sys.exit(1)
return tmp_dir, True, repo_name
except subprocess.TimeoutExpired:
shutil.rmtree(tmp_dir, ignore_errors=True)
print(" Clone timed out.", file=sys.stderr)
sys.exit(1)
except FileNotFoundError:
shutil.rmtree(tmp_dir, ignore_errors=True)
print(" git not found. Please install git.", file=sys.stderr)
sys.exit(1)
print(f" Cannot find or clone: {target}", file=sys.stderr)
sys.exit(1)
# ─────────────────────────────────────────────
# File Scanning
# ─────────────────────────────────────────────
def collect_files(repo_root: Path) -> list[Path]:
"""Walk repo directory and collect eligible files."""
files = []
for dirpath, dirnames, filenames in os.walk(repo_root):
# Prune ignored directories in-place
dirnames[:] = [
d for d in dirnames
if not should_ignore_dir(d)
]
for fname in filenames:
fpath = Path(dirpath) / fname
files.append(fpath)
return files
def scan_files(repo_root: Path) -> list[FileStats]:
"""Scan all files in parallel and return stats."""
files = collect_files(repo_root)
results = []
with ThreadPoolExecutor(max_workers=min(16, os.cpu_count() or 4)) as executor:
futures = {executor.submit(analyze_file, f, repo_root): f for f in files}
for future in as_completed(futures):
result = future.result()
if result is not None:
results.append(result)
return results
# ─────────────────────────────────────────────
# Git Analysis
# ─────────────────────────────────────────────
def run_git(repo_root: str, *args, timeout=30) -> Optional[str]:
"""Run a git command and return stdout, or None on failure."""
try:
result = subprocess.run(
["git", "-C", repo_root, *args],
capture_output=True, text=True, timeout=timeout
)
if result.returncode == 0:
return result.stdout.strip()
return None
except Exception:
return None
def analyze_git(repo_root: str, stats: RepoStats):
"""Populate git-related fields in RepoStats."""
# Check if this is a git repo
top = run_git(repo_root, "rev-parse", "--show-toplevel")
if top is None:
return
stats.git_available = True
# Current branch
stats.current_branch = run_git(repo_root, "rev-parse", "--abbrev-ref", "HEAD")
# Total commits — detect shallow clone and note limitation
is_shallow = os.path.exists(os.path.join(repo_root, ".git", "shallow"))
commit_count = run_git(repo_root, "rev-list", "--count", "HEAD")
if commit_count and commit_count.isdigit():
stats.total_commits = int(commit_count)
stats.is_shallow_clone = is_shallow
# Contributors with commit counts
shortlog = run_git(repo_root, "shortlog", "-sne", "--no-merges", "HEAD")
if shortlog:
contributors = []
for line in shortlog.strip().splitlines():
line = line.strip()
if not line:
continue
parts = line.split("\t", 1)
if len(parts) == 2:
count_str, name_email = parts
count_str = count_str.strip()
# Extract name from "Name <email>"
name = re.sub(r"\s*<[^>]+>", "", name_email).strip()
if count_str.isdigit():
contributors.append({
"name": name,
"commits": int(count_str),
"pct": 0.0,
})
# Calculate percentages
total = sum(c["commits"] for c in contributors)
if total > 0:
for c in contributors:
c["pct"] = round(c["commits"] / total * 100, 1)
stats.contributors = contributors
# First and last commit dates
last_date = run_git(repo_root, "log", "-1", "--format=%ci", "HEAD")
if last_date:
stats.last_commit_date = last_date.split(" ")[0]
first_date = run_git(repo_root, "log", "--reverse", "--format=%ci", "HEAD")
if first_date:
stats.first_commit_date = first_date.splitlines()[0].split(" ")[0]
# Repo age
if stats.first_commit_date and stats.last_commit_date:
from datetime import date
try:
d1 = date.fromisoformat(stats.first_commit_date)
d2 = date.fromisoformat(stats.last_commit_date)
stats.repo_age_days = (d2 - d1).days
except Exception:
pass
# ─────────────────────────────────────────────
# Dependency Detection
# ─────────────────────────────────────────────
def count_deps_in_file(path: Path, dep_type: str) -> int:
"""Count number of dependencies in a known dependency file."""
try:
content = path.read_text(encoding="utf-8", errors="replace")
except Exception:
return 1 # file exists, unknown count
name = path.name.lower()
if name == "package.json":
try:
data = json.loads(content)
deps = 0
for key in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"):
deps += len(data.get(key, {}))
return deps
except Exception:
return 0
if name == "requirements.txt":
lines = [l.strip() for l in content.splitlines() if l.strip() and not l.startswith("#")]
return len(lines)
if name == "cargo.toml":
matches = re.findall(r"^\[dependencies", content, re.MULTILINE | re.IGNORECASE)
deps = re.findall(r"^[a-z_-]+ ?=", content, re.MULTILINE)
return len(deps)
if name == "go.mod":
requires = re.findall(r"^\s+\S+ v", content, re.MULTILINE)
return len(requires)
if name.endswith(".csproj"):
matches = re.findall(r"<PackageReference", content)
return len(matches)
if name == "pom.xml":
matches = re.findall(r"<dependency>", content)
return len(matches)
if name == "composer.json":
try:
data = json.loads(content)
deps = len(data.get("require", {})) + len(data.get("require-dev", {}))
return deps
except Exception:
return 0
if name == "gemfile":
gems = re.findall(r"^gem ['\"]", content, re.MULTILINE)
return len(gems)
if name == "pyproject.toml":
matches = re.findall(r"^\s+['\"][a-zA-Z]", content, re.MULTILINE)
return max(len(matches) - 2, 0)
return 1
def detect_dependencies(repo_root: Path) -> dict:
"""Find dependency files and count packages."""
deps = {}
for fpath in repo_root.rglob("*"):
# Skip ignored dirs
parts = fpath.parts
if any(should_ignore_dir(p) for p in parts):
continue
name = fpath.name
fname_lower = name.lower()
# Direct match
if name in DEPENDENCY_FILES:
dtype = DEPENDENCY_FILES[name]
count = count_deps_in_file(fpath, dtype)
if dtype in deps:
deps[dtype] += count
else:
deps[dtype] = count
continue
# .csproj pattern
if fpath.suffix == ".csproj":
dtype = "NuGet (.NET)"
count = count_deps_in_file(fpath, dtype)
deps[dtype] = deps.get(dtype, 0) + count
return deps
# ─────────────────────────────────────────────
# Statistics Aggregation
# ─────────────────────────────────────────────
def aggregate_stats(repo_path: str, file_stats: list[FileStats], repo_name: str = None) -> RepoStats:
"""Combine all file stats into a RepoStats object."""
repo_root = Path(repo_path)
if repo_name is None:
repo_name = repo_root.name
stats = RepoStats(repo_path=repo_path, repo_name=repo_name)
stats.total_files = len(file_stats)
lang_data = defaultdict(lambda: {"files": 0, "lines": 0})
dir_data = defaultdict(int)
all_todos = defaultdict(int)
for fs in file_stats:
stats.total_lines += fs.total_lines
stats.code_lines += fs.code_lines
stats.comment_lines += fs.comment_lines
stats.blank_lines += fs.blank_lines
stats.total_size_bytes += fs.size_bytes
lang_data[fs.language]["files"] += 1
lang_data[fs.language]["lines"] += fs.total_lines
# Directory stats: first component of path
parts = Path(fs.path).parts
if len(parts) > 1:
top_dir = parts[0] + "/"
else:
top_dir = "./"
dir_data[top_dir] += fs.total_lines
for marker, count in fs.todos.items():
all_todos[marker] += count
# Sort languages by line count
stats.languages = dict(
sorted(lang_data.items(), key=lambda x: x[1]["lines"], reverse=True)
)
# Largest files by line count (top 10)
stats.largest_files = sorted(
file_stats, key=lambda f: f.total_lines, reverse=True
)[:10]
# Directory stats sorted
stats.directory_stats = dict(
sorted(dir_data.items(), key=lambda x: x[1], reverse=True)
)
stats.todos = dict(all_todos)
# Health metrics
if stats.total_files > 0:
stats.avg_file_lines = round(stats.total_lines / stats.total_files, 1)
if stats.total_lines > 0:
stats.comment_ratio = round(stats.comment_lines / stats.total_lines * 100, 1)
stats.code_density = round(stats.code_lines / stats.total_lines * 100, 1)
if stats.total_files > 0:
stats.average_file_size = round(stats.total_size_bytes / stats.total_files / 1024, 2)
return stats
# ─────────────────────────────────────────────
# Output Formatting
# ─────────────────────────────────────────────
BOLD = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
RED = "\033[31m"
RESET = "\033[0m"
WHITE = "\033[97m"
def c(text, color, bold=False):
"""Colorize text if stdout is a TTY."""
if not sys.stdout.isatty():
return str(text)
prefix = (BOLD if bold else "") + color
return f"{prefix}{text}{RESET}"
def fmt_number(n: int) -> str:
return f"{n:,}"
def bar(pct: float, width: int = 20) -> str:
filled = round(pct / 100 * width)
return "█" * filled + "░" * (width - filled)
def fmt_size(n_bytes: int) -> str:
if n_bytes < 1024:
return f"{n_bytes} B"
elif n_bytes < 1024 ** 2:
return f"{n_bytes / 1024:.1f} KB"
elif n_bytes < 1024 ** 3:
return f"{n_bytes / 1024 ** 2:.1f} MB"
else:
return f"{n_bytes / 1024 ** 3:.1f} GB"
def fmt_days(days: int) -> str:
if days < 30:
return f"{days} days"
elif days < 365:
return f"{days // 30} months"
else:
years = days // 365
months = (days % 365) // 30
if months:
return f"{years} year{'s' if years > 1 else ''}, {months} month{'s' if months > 1 else ''}"
return f"{years} year{'s' if years > 1 else ''}"
def print_section(title: str):
print()
print(c(f" {title}", CYAN, bold=True))
print(c(" " + "─" * (len(title) + 2), DIM))
def print_human(stats: RepoStats, show_all: bool, flags: dict):
show_files = show_all or flags.get("files")
show_langs = show_all or flags.get("languages")
show_git = show_all or flags.get("git")
show_contributors = show_all or flags.get("contributors")
show_dirs = show_all or flags.get("directories")
show_todos = show_all or flags.get("todos")
show_deps = show_all or flags.get("dependencies")
show_health = show_all or flags.get("health")
# ── Header ──────────────────────────────────────
print()
print(c(" ╔═══════════════════════════════════════╗", CYAN))
print(c(" ║", CYAN) + c(f" repo-stats · {stats.repo_name:<21}", WHITE, bold=True) + c("║", CYAN))
print(c(" ╚═══════════════════════════════════════╝", CYAN))
print(f" {c('Path:', DIM)} {stats.repo_path}")
if stats.git_available and stats.current_branch:
print(f" {c('Branch:', DIM)} {stats.current_branch}")
# ── File Overview ────────────────────────────────
if show_files or show_all:
print_section("File Statistics")
print(f" {'Files:':<18} {c(fmt_number(stats.total_files), GREEN, bold=True)}")
print(f" {'Total Size:':<18} {c(fmt_size(stats.total_size_bytes), GREEN)}")
print(f" {'Avg File Size:':<18} {c(str(stats.average_file_size) + ' KB', GREEN)}")
print()
print(f" {'Lines of Code:':<18} {c(fmt_number(stats.total_lines), WHITE, bold=True)}")
print(f" {' Code:':<18} {fmt_number(stats.code_lines)}")
print(f" {' Comments:':<18} {fmt_number(stats.comment_lines)}")
print(f" {' Blank:':<18} {fmt_number(stats.blank_lines)}")
if stats.largest_files:
print()
print(f" {c('Largest files:', DIM)}")
for i, fs in enumerate(stats.largest_files[:5], 1):
name = fs.path
print(f" {c(str(i) + '.', DIM)} {name:<45} {c(fmt_number(fs.total_lines) + ' lines', YELLOW)}")
# ── Languages ────────────────────────────────────
if show_langs:
print_section("Languages")
total_lines = stats.total_lines or 1
for lang, data in list(stats.languages.items())[:10]:
pct = data["lines"] / total_lines * 100
b = bar(pct, 18)
print(f" {lang:<20} {c(b, BLUE)} {c(f'{pct:.1f}%', WHITE)} "
f"{c(fmt_number(data['files']) + ' files', DIM)}, "
f"{c(fmt_number(data['lines']) + ' lines', DIM)}")
# ── Git Stats ────────────────────────────────────
if show_git and stats.git_available:
print_section("Git Statistics")
commits_label = fmt_number(stats.total_commits)
if stats.is_shallow_clone:
commits_label += c(" ⚠ shallow clone — use --full-clone for full history", YELLOW)
print(f" {'Commits:':<20} {c(fmt_number(stats.total_commits), GREEN, bold=True)}{c(' ⚠ shallow clone — use --full-clone for full history', YELLOW) if stats.is_shallow_clone else ''}")
print(f" {'Contributors:':<20} {c(str(len(stats.contributors)), GREEN)}")
if stats.first_commit_date:
print(f" {'First commit:':<20} {stats.first_commit_date}")
if stats.last_commit_date:
print(f" {'Last commit:':<20} {stats.last_commit_date}")
if stats.repo_age_days:
print(f" {'Repository age:':<20} {fmt_days(stats.repo_age_days)}")
elif show_git:
print_section("Git Statistics")
print(f" {c('Not a git repository or git not available.', DIM)}")
# ── Contributors ─────────────────────────────────
if show_contributors and stats.git_available and stats.contributors:
print_section("Contributors")
for contrib in stats.contributors:
b = bar(contrib["pct"], 18)
name = contrib["name"][:30]
print(f" {name:<30} {c(b, MAGENTA)} "
f"{c(str(contrib['pct']) + '%', WHITE)} "
f"{c(fmt_number(contrib['commits']) + ' commits', DIM)}")
# ── Directories ──────────────────────────────────
if show_dirs and stats.directory_stats:
print_section("Largest Directories")
total = sum(stats.directory_stats.values()) or 1
for dirname, lines in list(stats.directory_stats.items())[:8]:
pct = lines / total * 100
b = bar(pct, 18)
print(f" {dirname:<20} {c(b, YELLOW)} "
f"{c(fmt_number(lines) + ' lines', WHITE)} "
f"{c(f'{pct:.1f}%', DIM)}")
# ── TODOs ────────────────────────────────────────
if show_todos:
print_section("Developer Notes")
if stats.todos:
for marker, count in sorted(stats.todos.items(), key=lambda x: -x[1]):
color = RED if marker in ("FIXME", "BUG", "HACK") else YELLOW
print(f" {c(marker + ':', color):<28} {c(str(count), WHITE, bold=True)}")
else:
print(f" {c('No markers found.', DIM)}")
# ── Dependencies ─────────────────────────────────
if show_deps and stats.dependencies:
print_section("Dependencies")
for dtype, count in sorted(stats.dependencies.items(), key=lambda x: -x[1]):
print(f" {dtype:<30} {c(str(count) + ' packages', GREEN)}")
elif show_deps:
print_section("Dependencies")
print(f" {c('No recognized dependency files found.', DIM)}")
# ── Health ───────────────────────────────────────
if show_health:
print_section("Code Quality Indicators")
print(f" {'Avg file size:':<25} {stats.avg_file_lines} lines")
print(f" {'Comment ratio:':<25} {c(str(stats.comment_ratio) + '%', GREEN)}")
print(f" {'Code density:':<25} {c(str(stats.code_density) + '%', GREEN)}")
if stats.largest_files:
largest = stats.largest_files[0]
print(f" {'Largest file:':<25} {c(largest.path, YELLOW)} "
f"({fmt_number(largest.total_lines)} lines)")
print()
def print_json_output(stats: RepoStats):
out = {
"repo": stats.repo_name,
"path": stats.repo_path,
"files": {
"total": stats.total_files,
"total_size_bytes": stats.total_size_bytes,
"average_size_kb": stats.average_file_size,
},
"loc": {
"total": stats.total_lines,
"code": stats.code_lines,
"comments": stats.comment_lines,
"blank": stats.blank_lines,
},
"languages": {
lang: {
"files": data["files"],
"lines": data["lines"],
"pct": round(data["lines"] / (stats.total_lines or 1) * 100, 1),
}
for lang, data in stats.languages.items()
},
"git": {
"available": stats.git_available,
"commits": stats.total_commits,
"contributors": stats.contributors,
"first_commit": stats.first_commit_date,
"last_commit": stats.last_commit_date,
"age_days": stats.repo_age_days,
"branch": stats.current_branch,
},
"directories": stats.directory_stats,
"todos": stats.todos,
"dependencies": stats.dependencies,
"health": {
"avg_file_lines": stats.avg_file_lines,
"comment_ratio_pct": stats.comment_ratio,
"code_density_pct": stats.code_density,
"largest_file": stats.largest_files[0].path if stats.largest_files else None,
"largest_file_lines": stats.largest_files[0].total_lines if stats.largest_files else 0,
},
}
print(json.dumps(out, indent=2))
def print_markdown_output(stats: RepoStats):
print(f"# repo-stats: `{stats.repo_name}`\n")
print(f"> Generated by repo-stats\n")
print(f"**Path:** `{stats.repo_path}` ")
if stats.git_available and stats.current_branch:
print(f"**Branch:** `{stats.current_branch}`\n")
print("## File Statistics\n")
print(f"| Metric | Value |")
print(f"|--------|-------|")
print(f"| Total Files | {fmt_number(stats.total_files)} |")
print(f"| Total Size | {fmt_size(stats.total_size_bytes)} |")
print(f"| Lines of Code | {fmt_number(stats.total_lines)} |")
print(f"| Code Lines | {fmt_number(stats.code_lines)} |")
print(f"| Comment Lines | {fmt_number(stats.comment_lines)} |")
print(f"| Blank Lines | {fmt_number(stats.blank_lines)} |")
if stats.largest_files:
print("\n### Largest Files\n")
print("| # | File | Lines |")
print("|---|------|-------|")
for i, fs in enumerate(stats.largest_files[:5], 1):
print(f"| {i} | `{fs.path}` | {fmt_number(fs.total_lines)} |")
if stats.languages:
print("\n## Languages\n")
total = stats.total_lines or 1
print("| Language | Files | Lines | % |")
print("|----------|-------|-------|---|")
for lang, data in list(stats.languages.items())[:10]:
pct = round(data["lines"] / total * 100, 1)
print(f"| {lang} | {data['files']} | {fmt_number(data['lines'])} | {pct}% |")
if stats.git_available:
print("\n## Git Statistics\n")
print(f"| Metric | Value |")
print(f"|--------|-------|")
print(f"| Commits | {fmt_number(stats.total_commits)} |")
print(f"| Contributors | {len(stats.contributors)} |")