-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathfile-headers.py
381 lines (301 loc) · 10.5 KB
/
file-headers.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/python3
#############################################################################
#
# MIT License
#
# Copyright (c) 2023, Michael Becker (michael.f.becker@gmail.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
# OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#############################################################################
"""
Script to recursively update a set of files' headers.
"""
import os
import re
import sys
import argparse
def find_all_files(directory, filename_filter = None, dirname_filter = None,
ignore_dot_files = True):
""" Return a list of all normal files in the directory
as well as all subdirs. This performs a breath first
search because, well, I've never programed one before.
By default, we will ignore any file or directory that
starts with a dot, as per Unix convention.
"""
# Normalize the initial directory.
directory = os.path.realpath(directory)
original_dir = os.getcwd()
os.chdir(directory)
dir_list = []
file_list = []
for e in os.listdir(directory):
if ignore_dot_files and e[0] == ".":
continue
if os.path.isfile(e):
e = os.path.realpath(e)
if filename_filter == None:
file_list.append(e)
elif filename_filter(e):
file_list.append(e)
elif os.path.isdir(e):
e = os.path.realpath(e)
if dirname_filter == None:
dir_list.append(e)
elif dirname_filter(e):
dir_list.append(e)
for d in dir_list:
file_list = file_list + find_all_files(d, filename_filter)
os.chdir(original_dir)
return file_list
def make_file_extension_match(extension):
"""Return a function that searches for filename extensions.
"""
def is_file_match(filename):
match = re.search("\." + extension + "$", filename)
if match:
return True
else:
return False
return is_file_match
def make_filename_match(base_name):
"""Return a function that searches for a filename.
"""
def is_file_match(filename):
match = re.search(base_name + "$", filename)
if match:
return True
else:
return False
return is_file_match
def read_file(filename):
"""Read a text file and return the contents as
a list of lines
"""
f = open(filename, "r")
try:
lines = f.readlines()
except:
print ("Failed reading " + filename)
f.close()
return lines
def write_file(filename, lines):
"""Write a list of lines into a text file.
"""
f = open(filename, "w")
for l in lines:
f.write(l)
f.close()
def strip_header(lines, find_header_start, find_header_end, find_shebang = False):
""" Remove the header lines from a list of file lines.
We require that the header start on the _first_ line,
unless there is a shebang and we are looking for it, in
which case it may start on the second line if there is a
shebang.
"""
search_for_header = True
in_header = False
new_lines = []
for l in lines:
# Run once, if ever. But if it's here we need to
# look before we look for a header.
if find_shebang:
find_shebang = False
# Using match is "like" using regex "^#!"
match = re.match("#!", l)
if match:
new_lines.append(l)
continue
# Condition: The header has to start on the first line
# (or the second if there's a shebang line present).
if search_for_header:
search_for_header = False
if find_header_start(l):
in_header = True
# We need to continue here. If we don't, for files
# that have symetric comment delimiters we pick up
# the end marker as the same line as the start.
continue
if not in_header:
new_lines.append(l)
if in_header:
if find_header_end(l):
in_header = False
return new_lines
def insert_new_header(file_lines, new_header, find_shebang = False):
""" Insert the list of new header lines in the file.
"""
new_lines = []
if find_shebang:
find_shebang = False
# Using match is "like" using regex "^#!"
match = re.match("#!", file_lines[0])
if match:
new_lines.append(file_lines[0])
new_lines = new_lines + new_header
new_lines = file_lines[1:]
else:
new_lines = new_header + file_lines
else:
new_lines = new_header + file_lines
return new_lines
def print_lines(lines):
""" Debug utility, just print out the lines.
"""
for l in lines:
l = l.rstrip()
print(l,)
def generate_c_header_finders():
""" Generate the header finders for c style files.
"""
def find_header_start(line):
match = re.search("/\*\*", line)
if match:
return True
else:
return False
def find_header_end(line):
match = re.search("\*\*/", line)
if match:
return True
else:
return False
return find_header_start, find_header_end
def generate_c_and_cpp_header_finders():
""" Generate the header finders for c & c++ style files.
"""
c_style = False
cpp_style = False
def find_header_start(line):
nonlocal c_style, cpp_style
match = re.search("/\*\*", line)
if match:
c_style = True
return True
match = re.search("///", line)
if match:
cpp_style = True
return True
else:
return False
def find_header_end(line):
nonlocal c_style, cpp_style
if c_style:
match = re.search("\*\*/", line)
if match:
return True
else:
return False
elif cpp_style:
match = re.search("///", line)
if match:
return True
else:
return False
else:
return False
return find_header_start, find_header_end
def update_all_cpp_files(start_dir, new_header):
""" Handle c++ source files.
"""
start, end = generate_c_and_cpp_header_finders()
file_list = find_all_files(start_dir, make_file_extension_match("cpp"))
for f in file_list:
lines = read_file(f)
lines = strip_header(lines, start, end)
lines = insert_new_header(lines, new_header)
write_file(f, lines)
def update_all_hpp_files(start_dir, new_header):
""" Handle c++ header files.
"""
start, end = generate_c_and_cpp_header_finders()
file_list = find_all_files(start_dir, make_file_extension_match("hpp"))
for f in file_list:
lines = read_file(f)
lines = strip_header(lines, start, end)
lines = insert_new_header(lines, new_header)
write_file(f, lines)
def update_all_c_files(start_dir, new_header):
""" Handle c source files.
"""
start, end = generate_c_header_finders()
file_list = find_all_files(start_dir, make_file_extension_match("c"))
for f in file_list:
lines = read_file(f)
lines = strip_header(lines, start, end)
lines = insert_new_header(lines, new_header)
write_file(f, lines)
def update_all_h_files(start_dir, new_header):
""" Handle c header files.
"""
start, end = generate_c_header_finders()
file_list = find_all_files(start_dir, make_file_extension_match("h"))
for f in file_list:
lines = read_file(f)
lines = strip_header(lines, start, end)
lines = insert_new_header(lines, new_header)
write_file(f, lines)
def update_all_makefiles(start_dir, new_header):
""" Handle makefiles.
"""
def find_header_start_and_end(line):
match = re.match("##", line)
if match:
return True
else:
return False
file_list = find_all_files(start_dir, make_filename_match("makefile"))
for f in file_list:
lines = read_file(f)
lines = strip_header(lines, find_header_start_and_end,
find_header_start_and_end)
lines = insert_new_header(lines, new_header)
write_file(f, lines)
def debug_print_all(start_dir):
""" Debugging, print all files / dirs found.
"""
file_list = find_all_files(start_dir)
for f in file_list:
print(f)
# Script proper starts here.
parser = argparse.ArgumentParser()
parser.add_argument("header_file", help="File containing the new header.")
parser.add_argument("file_type", help="[c|h|cpp|hpp|makefile] File type to be updated.")
parser.add_argument("--dir", help="Directory to start scaning in. Default is current directory.")
args = parser.parse_args()
if not args.dir:
start_dir = "."
else:
start_dir = args.dir
header_lines = read_file(args.header_file)
if (args.file_type == "cpp"):
update_all_cpp_files(start_dir, header_lines)
elif (args.file_type == "c"):
update_all_c_files(start_dir, header_lines)
elif (args.file_type == "h"):
update_all_h_files(start_dir, header_lines)
elif (args.file_type == "hpp"):
update_all_hpp_files(start_dir, header_lines)
elif (args.file_type == "makefile"):
update_all_makefiles(start_dir, header_lines)
elif (args.file_type == "debugprintall"):
debug_print_all(start_dir)
else:
print("Unsupported file type")
sys.exit(0)