-
Notifications
You must be signed in to change notification settings - Fork 0
/
count_loc.py
56 lines (47 loc) · 2.16 KB
/
count_loc.py
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
import os
import re
def count_lines(filename, ext):
"""Count the lines of code while ignoring comments."""
with open(filename, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
if ext in ['.c', '.cpp', '.h', '.hpp']:
# C and C++ single line comments start with //
# C and C++ multi-line comments are between /* and */
content = re.sub(r'//.*', '', content) # Remove single line comments
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL) # Remove multi-line comments
elif ext == '.py':
content = re.sub(r'#.*', '', content) # Remove Python single line comments
elif ext == '.lua':
# Lua single line comments start with --
# Lua multi-line comments are between --[[ and ]]
content = re.sub(r'--.*', '', content) # Remove single line comments
content = re.sub(r'--\[\[.*?\]\]', '', content, flags=re.DOTALL) # Remove multi-line comments
return len([line for line in content.split('\n') if line.strip()]) # Count non-empty lines
def pretty_format(n):
"""Format large numbers by splitting digits by 3."""
return "{:,}".format(n).replace(',', "'")
def main(directory="."):
loc_by_language = {
'C/C++': 0,
'Python': 0,
'Lua': 0
}
# Walk through the directory
for dirpath, dirnames, filenames in os.walk(directory):
# Skip 'extern' directories
if 'extern' in dirnames:
dirnames.remove('extern')
for filename in filenames:
ext = os.path.splitext(filename)[1]
if ext in ['.c', '.cpp', '.h', '.hpp']:
loc_by_language['C/C++'] += count_lines(os.path.join(dirpath, filename), ext)
elif ext == '.py':
loc_by_language['Python'] += count_lines(os.path.join(dirpath, filename), ext)
elif ext == '.lua':
loc_by_language['Lua'] += count_lines(os.path.join(dirpath, filename), ext)
# Display results
for lang, loc in loc_by_language.items():
print(f"{lang}: {pretty_format(loc)} lines of code")
if __name__ == "__main__":
# By default, start with the current directory.
main(".")