-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinecount.py
More file actions
executable file
·77 lines (64 loc) · 2.08 KB
/
linecount.py
File metadata and controls
executable file
·77 lines (64 loc) · 2.08 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
#!/usr/bin/python
import os
import argparse
def count_lines(filepath: str):
"""Returns number of newline characters in a file"""
try:
with open(filepath, "r") as f:
return f.read().count("\n")
except UnicodeDecodeError as e:
# Likely a binary file, skip.
return 0
def has_extension(filepath: str, extensions: list[str]):
"""Returns True if filepath has any of the extensions in the
extensions list"""
for extension in extensions:
if filepath.endswith(extension):
return True
return False
def main(paths: list[str], extensions: list[str], ignore: list[str]):
"""Count number of lines in all the files in a directory that has
an extension that is in extensions list."""
count = 0
for path in paths:
for path, dirnames, files in os.walk(path, topdown=True):
# os.walk will only search directories present in dirnames.
for dir in ignore:
if dir in dirnames:
dirnames.remove(dir)
if os.path.basename(path) in ignore:
continue
for filepath in files:
if has_extension(filepath, extensions):
count += count_lines(os.path.join(path, filepath))
return count
class _LinecountNamespace(argparse.Namespace):
path: list[str]
ignore: list[str]
extension: list[str]
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--path",
action="append",
default=[],
help="Directories that should be searched"
)
parser.add_argument(
"-i",
"--ignore",
action="append",
default=[],
help="Directories with this name will be ignored.",
)
parser.add_argument(
"-e",
"--extension",
action="append",
default=[],
help="Files with this extension will be included in the count.",
)
args: _LinecountNamespace = parser.parse_args()
result = main(args.path, args.extension, args.ignore)
print(result)