Last active
September 17, 2017 19:29
-
-
Save gfrlv/5e79b494c27f706d255446dae80d01bc to your computer and use it in GitHub Desktop.
count lines of code in a project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Counting lines of code in a project | |
# Usage: python3 count_lines.py /path/to/project/src .cpp .h .py | |
# (if no extensions are specified, will count across all files) | |
import os | |
from collections import defaultdict | |
line_filters = {} | |
for ext in ('java', 'cpp', 'cc', 'cxx', 'c', 'h', 'hpp'): | |
line_filters[ext] = lambda line: line.strip().endswith(b';') | |
line_counts = defaultdict(lambda: 0) | |
def count_lines_in_file(path, extensions=None): | |
filename, extension = os.path.splitext(path) | |
line_filter = line_filters.get(extension, lambda line:not line.isspace()) | |
if extensions and extension not in extensions: | |
return | |
with open(path, 'rb') as f: | |
for line in f: | |
if line_filter(line): | |
line_counts[extension] += 1 | |
if __name__ == '__main__': | |
import sys | |
if len(sys.argv) > 1: | |
project_dir = sys.argv[1] | |
else: | |
project_dir = '.' | |
if len(sys.argv) > 2: | |
extensions = sys.argv[2:] | |
else: | |
extensions = None | |
for r,d,f in os.walk(project_dir): | |
for filename in f: | |
path = os.path.join(r, filename) | |
count_lines_in_file(path, extensions) | |
total_lines = 0 | |
for ext, nlines in line_counts.items(): | |
total_lines += nlines | |
print('{0}: {1}'.format(ext, nlines)) | |
print('total: {0}'.format(total_lines)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment