59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Count Lines of Code (LOC) in Python files.
|
|
Quick utility: counts total, code, comment, and blank lines.
|
|
"""
|
|
import argparse
|
|
from pathlib import Path
|
|
|
|
def count_loc(filepath: Path) -> dict:
|
|
"""Return LOC breakdown for a Python file."""
|
|
total, code, comment, blank = 0, 0, 0, 0
|
|
in_multiline = False
|
|
|
|
with open(filepath, 'r') as f:
|
|
for line in f:
|
|
total += 1
|
|
stripped = line.strip()
|
|
|
|
if in_multiline:
|
|
if '"""' in stripped or "'''" in stripped:
|
|
in_multiline = False
|
|
comment += 1
|
|
continue
|
|
|
|
if not stripped:
|
|
blank += 1
|
|
elif stripped.startswith('#'):
|
|
comment += 1
|
|
elif '"""' in stripped or "'''" in stripped:
|
|
comment += 1
|
|
if stripped.count('"""') < 2 and stripped.count("'''") < 2:
|
|
in_multiline = True
|
|
else:
|
|
code += 1
|
|
|
|
return {'total': total, 'code': code, 'comment': comment, 'blank': blank}
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description='Count LOC in Python files')
|
|
parser.add_argument('path', type=Path, help='Python file or directory')
|
|
args = parser.parse_args()
|
|
|
|
if args.path.is_file():
|
|
result = count_loc(args.path)
|
|
print(f"File: {args.path}")
|
|
print(f" Total: {result['total']}")
|
|
print(f" Code: {result['code']}")
|
|
print(f" Comment: {result['comment']}")
|
|
print(f" Blank: {result['blank']}")
|
|
elif args.path.is_dir():
|
|
total = {'total': 0, 'code': 0, 'comment': 0, 'blank': 0}
|
|
for py_file in args.path.rglob('*.py'):
|
|
result = count_loc(py_file)
|
|
for key in total:
|
|
total[key] += result[key]
|
|
print(f"Directory: {args.path}")
|
|
print(f" Total: {total['total']}")
|
|
print(f" Code: {total['code']}")
|
|
print(f" Comment: {total['comment']}")
|
|
print(f" Blank: {total['blank']}") |