-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcntlines.py
More file actions
279 lines (214 loc) · 6.68 KB
/
cntlines.py
File metadata and controls
279 lines (214 loc) · 6.68 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
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
# A simple script to count lines of code inside source and header files.
#
# Copyright oxiKKK 2023 (c)
#
# Version: 1.0
#
import sys
import os
import datetime
from pathlib import Path
# script version
version = "1.0"
# initialize to current script directory
script_dir = os.path.dirname(__file__)
# directory to perform the search in
final_directory = ""
# list of extensions to search for
extensions = ('.php', '.css', '.js', '.html')
# add directory names here to not take place in counting
dir_filter = (
'.git',
'dumps'
)
# settings and their explanation
settings = {
'-v': "enables verbose mode",
'-f': "dumps to a file elegantly",
'-m': "Automatically modifies README.md"
}
def print_settings():
print("\nSettings:")
for s in settings.items():
print(s)
print("")
# settings
verbs = False
dump_to_file = False
modify_files = False
# sum of all lines
total_lines = 0
# passed in arguments
arguments = sys.argv
# dump file creation
created_file = False
dump_filename = ""
dumped_file = None # the file handle we'll dump to
# file print
def fprint(s):
if dump_to_file:
dumped_file.write(s)
dumped_file.write('\n')
print(s)
else:
print(s)
# create file and write header
def create_dump_file() -> bool:
print("creating dump file...")
# create dump\ directory if not exists
Path(r".\dumps").mkdir(parents=True, exist_ok=True)
global dump_filename
timestamp = str(datetime.datetime.now())[:10].replace(' ', '_')
dump_filename = r"dumps\lines_{}.txt".format(timestamp)
try:
global dumped_file
dumped_file = open(dump_filename, "w")
except OSError as e:
print(f"OSError: {e}")
return False
fprint(
f"""//
// File generated automatically by cntlines.py script
// Generated at: {timestamp}.
// Version: {version}
//
""")
return True
# verbose print
def verbose(s):
if verbs:
print(s)
# check settings passed in
def parse_settings():
# parse directory
global final_directory
final_directory = os.path.join(script_dir)
print(f"applying to '{final_directory}'")
if '-v' in arguments:
global verbs
verbs = True
if '-f' in arguments:
global dump_to_file
dump_to_file = True
if '-m' in arguments:
global modify_files
modify_files = True
# check parameters
def check_params() -> bool:
if len(arguments) <= 1:
print(f"error: invalid arguments: {arguments}")
print_settings()
return False
else:
parse_settings()
return True
# automatically modify README.md with linecount
def modify_readme_fn():
try:
file = open(r"README.md", "r", encoding="utf8")
except OSError as e:
print(f"OSError: {e}")
sys.exit()
contents = file.read()
token = 'Written in '
ending_token = '</h4>'
pos = contents.find(token)
ending_pos = contents.find(ending_token, pos)
to_replace_with = "Written in {:,} lines of code in {:,} files.".format(count_data.total_lines, len(count_data.files))
final_contents = contents[:pos] + to_replace_with + contents[ending_pos:]
file.close()
# reopen the file and write to it
file = open(r"README.md", "w", encoding="utf8")
file.write(final_contents)
print("wrote new README.md!")
# check directory
def check_directory() -> bool:
if os.path.exists(final_directory):
return True
else:
print(f"error: directory doesn't exist ({final_directory})")
return False
# object to hold counted data
class CountData:
class File:
def __init__(self, p, l):
self.path = p
self.lines = l
path = ""
lines = 0
total_lines = 0
files = []
count_data = CountData()
# count lines inside all files within a directory
def count_lines() -> None:
for subdir, dirs, files in os.walk(final_directory):
# see for blacklisted directories
filter = False
for blacklisted in dir_filter:
if blacklisted in subdir:
filter = True
if filter:
verbose(f"filtered '{subdir}'.")
continue
# now iterate over files
for file in files:
ext = os.path.splitext(file)[-1].lower()
if ext in extensions:
fulldir = os.path.join(subdir, file)
# Open the file and count lines, ignoring single-line and block comments
num_lines = 0
in_block_comment = False
with open(fulldir, encoding='utf8') as file_handle:
for line in file_handle:
line_stripped = line.strip()
if not line_stripped or line_stripped.startswith("//") or line_stripped.startswith("<?php") or line_stripped.startswith("?>"):
continue # Skip empty lines and single-line comments
if line_stripped.startswith("/*"):
in_block_comment = True
if not in_block_comment:
num_lines += 1
if line_stripped.endswith("*/"):
in_block_comment = False
file_data = CountData.File(
fulldir, num_lines
)
count_data.files.append(file_data)
count_data.total_lines += num_lines
# print results etc
def process_result():
# sort the list
count_data.files.sort(key=lambda x: x.lines, reverse=True)
for i, f in enumerate(count_data.files):
verbose(f"{i}: {f.path}: {f.lines} lines")
fprint("-----------------------------------------")
fprint(f"total lines: {count_data.total_lines} in {len(count_data.files)} files.")
fprint("")
fprint("Top 10 files by line count:")
for i in range(len(count_data.files) if len(count_data.files) < 10 else 10):
f = count_data.files[i]
fprint(f"{i}: {f.path}: {f.lines} lines")
print("")
#---------------------------------------------------------
def script():
print("starting...")
print(f"script directory: {script_dir}")
if not check_params():
sys.exit()
# create dump file
if dump_to_file:
if not create_dump_file():
print(f"error: could not create dump file. ({dump_filename})")
sys.exit()
else:
print(f"dumping to {dump_filename}.")
if not check_directory():
sys.exit()
count_lines()
process_result()
if modify_files:
modify_readme_fn()
# close the file if opened
if dump_to_file:
dumped_file.close()
print("finish!")
script()