-
-
Notifications
You must be signed in to change notification settings - Fork 826
/
Copy pathcountline.py
executable file
·297 lines (231 loc) · 7.21 KB
/
countline.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""Script to encourage more efficient coding practices.
Methodology:
Analyses the `lib` and `test` directories to find files that exceed a
pre-defined number of lines of code.
This script was created to help improve code quality by encouraging
contributors to create reusable code.
NOTE:
This script complies with our python3 coding and documentation standards
and should be used as a reference guide. It complies with:
1) Pylint
2) Pydocstyle
3) Pycodestyle
4) Flake8
Run these commands from the CLI to ensure the code is compliant for all
your pull requests.
"""
# Standard imports
import os
import sys
import argparse
from collections import namedtuple
def _valid_filename(filepath):
"""Determine whether filepath has the correct filename.
Args:
filepath: Filepath to check
Returns:
result: True if valid
"""
# Initialize key variables
invalid_filenames = [".test.", ".spec."]
result = True
# Test
for invalid_filename in invalid_filenames:
if invalid_filename.lower() not in filepath.lower():
continue
result = False
return result
def _valid_extension(filepath):
"""Determine whether filepath has the correct extension.
Args:
filepath: Filepath to check
Returns:
result: True if valid
"""
# Initialize key variables
invalid_extensions = [".css", ".jpg", ".png", ".jpeg"]
result = True
# Test
for invalid_extension in invalid_extensions:
if filepath.lower().endswith(invalid_extension.lower()) is False:
continue
result = False
return result
def _valid_exclusions(excludes):
"""Create a list of full file paths to exclude from the analysis.
Args:
excludes: Excludes object
Returns:
result: A list of full file paths
"""
# Initialize key variables
result = []
filenames = []
more_filenames = []
# Create a list of files to ignore
if bool(excludes.files):
filenames = excludes.files
if bool(excludes.directories):
more_filenames = _filepaths_in_directories(excludes.directories)
filenames.extend(more_filenames)
# Remove duplicates
filenames = list(set(filenames))
# Process files
for filename in filenames:
# Ignore files that appear to be full paths because they start
# with a '/' or whatever the OS uses to distinguish directories
if filename.startswith(os.sep):
continue
# Create a file path
filepath = "{}{}{}".format(os.getcwd(), os.sep, filename)
if os.path.isfile(filepath) is True:
result.append(filepath)
# Return
return result
def _filepaths_in_directories(directories):
"""Create a list of full file paths based on input directories.
Args:
directories: A list of directories
Returns:
result: A list of full file paths
"""
# Initialize key variables
result = []
# Iterate and analyze each directory
for directory in directories:
for root, _, files in os.walk(directory, topdown=False):
for name in files:
# Read each file and count the lines found
result.append(os.path.join(root, name))
# Return
return result
def _arg_parser_resolver():
"""Resolve the CLI arguments provided by the user.
Args:
None
Returns:
result: Parsed argument object
"""
# Initialize parser and add the CLI options we should expect
parser = argparse.ArgumentParser()
parser.add_argument(
"--lines",
type=int,
required=False,
default=300,
help="The maximum number of lines of code to accept.",
)
parser.add_argument(
"--directory",
type=str,
required=False,
default=os.getcwd(),
help="The parent directory of files to analyze.",
)
parser.add_argument(
"--exclude_files",
type=str,
required=False,
nargs="*",
default=None,
const=None,
help="""An optional space separated list of \
files to exclude from the analysis.""",
)
parser.add_argument(
"--exclude_directories",
type=str,
required=False,
nargs="*",
default=None,
const=None,
help="""An optional space separated list of \
directories to exclude from the analysis.""",
)
# Return parser
result = parser.parse_args()
return result
def main():
"""Analyze dart files.
This function finds, and prints the files that exceed the CLI
defined defaults.
Args:
None
Returns:
None
"""
# Initialize key variables
lookup = {}
errors_found = False
file_count = 0
Excludes = namedtuple("Excludes", "files directories")
# Get the CLI arguments
args = _arg_parser_resolver()
# Define the directories of interest
directories = [
os.path.expanduser(os.path.join(args.directory, "lib")),
os.path.expanduser(os.path.join(args.directory, "src")),
os.path.expanduser(os.path.join(args.directory, "test")),
]
# Get a corrected list of filenames to exclude
exclude_list = _valid_exclusions(
Excludes(
files=args.exclude_files, directories=args.exclude_directories
)
)
# Get interesting filepaths
repo_filepath_list = _filepaths_in_directories(directories)
# Iterate and analyze each directory
for filepath in repo_filepath_list:
# Skip excluded files
if filepath in exclude_list:
continue
# Skip /node_modules/ sub directories
if "{0}node_modules{0}".format(os.sep) in filepath:
continue
# Ignore invalid file extensions
if _valid_extension(filepath) is False:
continue
# Ignore invalid file filenames
if _valid_filename(filepath) is False:
continue
# Process the rest
with open(filepath, encoding="latin-1") as code:
line_count = sum(
1
for line in code
if line.strip()
and not (
line.strip().startswith("#")
or line.strip().startswith("/")
)
)
lookup[filepath] = line_count
# If the line rule is voilated then the value is changed to 1
for filepath, line_count in lookup.items():
if line_count > args.lines:
errors_found = True
file_count += 1
if file_count == 1:
print(
"""
LINE COUNT ERROR: Files with excessive lines of code have been found\n"""
)
print(" Line count: {:>5} File: {}".format(line_count, filepath))
# Evaluate and exit
if bool(errors_found) is True:
print(
"""
The {} files listed above have more than {} lines of code.
Please fix this. It is a pre-requisite for pull request approval.
""".format(
file_count, args.lines
)
)
sys.exit(1)
else:
sys.exit(0)
if __name__ == "__main__":
main()