|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Basic LOC counter for this repo. |
| 4 | +Counts non-blank, non-comment lines for file extensions typically used in this repo: |
| 5 | +- .py .pyx .c .cpp .cc .cxx .h .hpp |
| 6 | +
|
| 7 | +Comments are identified only if the line starts (after whitespace) with `#` or `//`. |
| 8 | +This is intentionally simple / fast. |
| 9 | +
|
| 10 | +Usage: |
| 11 | + python dev/count_loc_basic.py [--root ROOT] [--exclude DIR1,DIR2] [--ext py,pyx,c,cpp,h] [--top N] |
| 12 | +
|
| 13 | +The script prints a total and per-language breakdown. |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +from collections import defaultdict |
| 20 | +from pathlib import Path |
| 21 | +from typing import Iterable |
| 22 | +from typing import List |
| 23 | +from typing import Set |
| 24 | +from typing import Tuple |
| 25 | + |
| 26 | +DEFAULT_EXTS = ["py", "pyx", "c", "cpp", "cc", "cxx", "h", "hpp"] |
| 27 | +DEFAULT_EXCLUDES = {"build", "temp", "third_party", "dev", "dist", "scratch"} |
| 28 | + |
| 29 | + |
| 30 | +def parse_args(): |
| 31 | + p = argparse.ArgumentParser(description="Basic LOC counter (non-blank, non-comment lines)") |
| 32 | + p.add_argument("--root", default=".", help="Root directory to scan") |
| 33 | + p.add_argument( |
| 34 | + "--exclude", |
| 35 | + default=','.join(sorted(DEFAULT_EXCLUDES)), |
| 36 | + help=f"Comma-separated list of directory names to exclude. Default: {','.join(sorted(DEFAULT_EXCLUDES))}", |
| 37 | + ) |
| 38 | + p.add_argument( |
| 39 | + "--ext", |
| 40 | + default=','.join(DEFAULT_EXTS), |
| 41 | + help=f"Comma-separated extensions to include (no leading dot). Default: {','.join(DEFAULT_EXTS)}", |
| 42 | + ) |
| 43 | + p.add_argument( |
| 44 | + "--top", |
| 45 | + type=int, |
| 46 | + default=10, |
| 47 | + help="Show top N files by LOC (default 10)", |
| 48 | + ) |
| 49 | + p.add_argument( |
| 50 | + "--per-file", |
| 51 | + action="store_true", |
| 52 | + help="Show counts per file in addition to summary", |
| 53 | + ) |
| 54 | + return p.parse_args() |
| 55 | + |
| 56 | + |
| 57 | +def should_skip(path: Path, exclude_parts: Set[str]) -> bool: |
| 58 | + """Return True if any component of `path` is in exclude_parts.""" |
| 59 | + return any(part in exclude_parts for part in path.parts) |
| 60 | + |
| 61 | + |
| 62 | +def find_files(root: Path, exts: Set[str], exclude_parts: Set[str]) -> Iterable[Path]: |
| 63 | + for path in root.rglob("*"): |
| 64 | + if path.is_file(): |
| 65 | + if should_skip(path, exclude_parts): |
| 66 | + continue |
| 67 | + if path.suffix: |
| 68 | + suf = path.suffix[1:] |
| 69 | + if suf in exts: |
| 70 | + yield path |
| 71 | + |
| 72 | + |
| 73 | +def count_file(path: Path) -> int: |
| 74 | + cnt = 0 |
| 75 | + try: |
| 76 | + with path.open("r", errors="replace") as fh: |
| 77 | + for line in fh: |
| 78 | + if not line.strip(): |
| 79 | + continue |
| 80 | + s = line.lstrip() |
| 81 | + if s.startswith("#") or s.startswith("//"): |
| 82 | + continue |
| 83 | + cnt += 1 |
| 84 | + except (OSError, UnicodeDecodeError): |
| 85 | + # If we can't read a file for whatever reason, just skip it and return 0 |
| 86 | + return 0 |
| 87 | + return cnt |
| 88 | + |
| 89 | + |
| 90 | +def group_by_ext(path: Path) -> str: |
| 91 | + suf = path.suffix[1:] |
| 92 | + if suf in ("py", "pyx"): |
| 93 | + return "Python/Cython" |
| 94 | + if suf in ("c",): |
| 95 | + return "C" |
| 96 | + if suf in ("cpp", "cc", "cxx"): |
| 97 | + return "C++" |
| 98 | + if suf in ("h", "hpp"): |
| 99 | + return "Header" |
| 100 | + return suf |
| 101 | + |
| 102 | + |
| 103 | +def main(): |
| 104 | + args = parse_args() |
| 105 | + root = Path(args.root).resolve() |
| 106 | + exts = {e.strip() for e in args.ext.split(",") if e.strip()} |
| 107 | + excludes = {p.strip() for p in args.exclude.split(",") if p.strip()} |
| 108 | + |
| 109 | + files = list(find_files(root, exts, excludes)) |
| 110 | + |
| 111 | + per_file_counts: List[Tuple[Path, int]] = [] |
| 112 | + ext_totals: defaultdict[str, int] = defaultdict(int) |
| 113 | + |
| 114 | + total = 0 |
| 115 | + for p in files: |
| 116 | + c = count_file(p) |
| 117 | + per_file_counts.append((p, c)) |
| 118 | + total += c |
| 119 | + ext_totals[group_by_ext(p)] += c |
| 120 | + |
| 121 | + print("LOC Summary (non-blank, non-comment lines)") |
| 122 | + print(f"Root: {root}") |
| 123 | + print(f"Files scanned: {len(files)}") |
| 124 | + print(f"Total LOC: {total}") |
| 125 | + print("") |
| 126 | + print("Breakdown by language:") |
| 127 | + for k in sorted(ext_totals.keys()): |
| 128 | + print(f" {k:12s}: {ext_totals[k]}") |
| 129 | + |
| 130 | + if args.per_file: |
| 131 | + print("") |
| 132 | + print("Top files by LOC:") |
| 133 | + per_file_counts.sort(key=lambda t: t[1], reverse=True) |
| 134 | + for p, c in per_file_counts[: args.top]: |
| 135 | + print(f" {c:6d} {p}") |
| 136 | + |
| 137 | + |
| 138 | +if __name__ == "__main__": |
| 139 | + main() |
0 commit comments