-
Notifications
You must be signed in to change notification settings - Fork 0
/
fix_include_statements.py
400 lines (384 loc) · 17.5 KB
/
fix_include_statements.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# -*- coding: utf-8 -*-
"""
Copyright 2024 Kristof Mulier.
"""
# SUMMARY:
# This script is used to check the codebase for inconsistencies between the include statements in
# the files and the actual filenames in the filesystem. These inconsistencies can be a problem on
# case-sensitive filesystems, such as Linux, and can cause build errors. The script lists all the
# inconsistencies and allows the user to fix them by choosing the correct filename from the
# filesystem. Additionally, it corrects backslashes in include statements to use forward slashes
# for better cross-platform compatibility. The script is intended to be run from the top-level
# directory of the codebase.
import os
import re
import argparse
import sys
from typing import Dict, List, Tuple
def print_help() -> None:
'''
Print the help message.
'''
print(
"\n"
"fix_include_statements.py\n"
"=========================\n"
"This script is used to check the codebase for inconsistencies between the include\n"
"statements in the files and the actual filenames in the filesystem, and to correct\n"
"backslashes in include statements to use forward slashes. These inconsistencies can\n"
"be a problem on case-sensitive filesystems, such as Linux, and can cause build errors.\n"
"The script lists all the inconsistencies and allows the user to fix them by choosing\n"
"the correct filename from the filesystem. The script is intended to be run from the\n"
"top-level directory of the codebase.\n"
"\n"
"Usage: python fix_include_statements.py [options]\n"
"\n"
"Options:\n"
"--------\n"
" -h, --help Show this help message and exit.\n"
"\n"
" -n, --dry-run Print the results without fixing the\n"
" include statements.\n"
"\n"
" -d DIRECTORY, Toplevel directory of the codebase\n"
" --directory=DIRECTORY to process. If not provided,\n"
" the current directory is used.\n"
"\n"
"Examples:\n"
"---------\n"
" Show the inconsistencies in the codebase, assuming that this script is in the \n"
" top-level directory:\n"
" > python fix_include_statements.py --dry-run\n"
"\n"
" Fix the inconsistencies and backslashes in include statements:\n"
" > python fix_include_statements.py\n"
"\n"
)
return
def crawl_codebase(root_dir: str) -> Dict[str, List[str]]:
'''
Crawls the codebase and returns a dictionary with the relative path of each file as key and a
list of its includes as value.
'''
include_pattern = re.compile(r'#include\s*["<](.*?)[">]')
include_dict: Dict[str, List[str]] = {}
print("Crawling the codebase")
i = 0
for root, dirs, files in os.walk(root_dir):
for filename in files:
if not filename.endswith(('.h', '.hpp', '.c', '.cpp')):
continue
file_path = os.path.join(root, filename)
relative_path = os.path.relpath(file_path, start=root_dir).replace('\\', '/')
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
include_list: List[str] = include_pattern.findall(content)
# include_list = [include.replace('\\', '/') for include in include_list]
if include_list:
include_dict[relative_path] = include_list
i += 1
if i % 100 == 0:
print(".", end="")
sys.stdout.flush()
continue
continue
print("")
return include_dict
def list_all_files(root_dir: str) -> Dict[str, List[Tuple[str, str]]]:
'''
Lists all filenames in the codebase with extensions .h, .hpp, .c, and .cpp, mapping lower case
filenames to their actual cases and relative paths in the filesystem.
'''
filename_dict: Dict[str, List[Tuple[str, str]]] = {}
print("Listing all filenames")
i = 0
for root, dirs, files in os.walk(root_dir):
for filename in files:
if not filename.endswith(('.h', '.hpp', '.c', '.cpp')):
continue
file_path = os.path.join(root, filename)
relative_path = os.path.relpath(file_path, start=root_dir).replace('\\', '/')
lower_filename = filename.lower()
if lower_filename not in filename_dict:
filename_dict[lower_filename] = [(filename, relative_path)]
else:
filename_dict[lower_filename].append((filename, relative_path))
i += 1
if i % 100 == 0:
print(".", end="")
sys.stdout.flush()
continue
continue
print("")
return filename_dict
def check_codebase(root_dir: str, dry_run:bool) -> None:
'''
Checks the codebase for inconsistencies between the include statements in the files and the
actual filenames in the filesystem, and corrects backslashes in include statements to use
forward slashes.
'''
include_dict: Dict[str, List[str]] = crawl_codebase(root_dir)
all_filenames: Dict[str, List[Tuple[str, str]]] = list_all_files(root_dir)
results = {}
print("Analyzing the codebase")
i = 0
# Loop over all the files and their include statements
for path, include_list in include_dict.items():
# Loop over all the include statements in the file (more precisely - the values of these
# include statements, which are the filenames of the included files, or sometimes relative
# paths to the included files).
for include_statement_value in include_list:
i += 1
if i % 100 == 0:
print(".", end="")
sys.stdout.flush()
include_filename_lower = include_statement_value.replace('\\', '/').split('/')[-1].lower()
if include_filename_lower not in all_filenames:
# The include statement refers to a file that does not exist in the filesystem. This
# could be an include from a file in the compiler toolchain (eg. string.h). We skip,
# but not before checking for backslashes.
if '\\' in include_statement_value:
if path in results:
results[path][include_statement_value] = {
'actual_filenames': [None, ],
'actual_paths' : [None, ],
}
else:
results[path] = {
include_statement_value: {
'actual_filenames': [None, ],
'actual_paths' : [None, ],
},
}
continue
# Extract the matches - a list of tuples with the actual filename and its relative path.
# Each tuple is a possible candidate for the file that the include statement refers to.
matches: List[Tuple[str, str]] = all_filenames[include_filename_lower]
# Only one match
if len(matches) == 1:
actual_filename, actual_path = matches[0]
if actual_filename != include_statement_value.replace('\\', '/').split('/')[-1]:
if path in results:
results[path][include_statement_value] = {
'actual_filenames': [actual_filename, ],
'actual_paths' : [actual_path, ],
}
else:
results[path] = {
include_statement_value: {
'actual_filenames': [actual_filename, ],
'actual_paths' : [actual_path, ],
},
}
else:
# Still check for backslashes
if '\\' in include_statement_value:
if path in results:
results[path][include_statement_value] = {
'actual_filenames': [None, ],
'actual_paths' : [None, ],
}
else:
results[path] = {
include_statement_value: {
'actual_filenames': [None, ],
'actual_paths' : [None, ],
},
}
# Multiple matches
else:
actual_filenames = []
actual_paths = []
filename_matches: bool = False
for match in matches:
actual_filename, actual_path = match
actual_filenames.append(actual_filename)
actual_paths.append(actual_path)
if actual_filename == include_statement_value.replace('\\', '/').split('/')[-1]:
filename_matches = True
if not filename_matches:
if path in results:
results[path][include_statement_value] = {
'actual_filenames': actual_filenames,
'actual_paths' : actual_paths,
}
else:
results[path] = {
include_statement_value: {
'actual_filenames': actual_filenames,
'actual_paths' : actual_paths,
},
}
else:
# Still check for backslashes
if '\\' in include_statement_value:
if path in results:
results[path][include_statement_value] = {
'actual_filenames': [None, ],
'actual_paths' : [None, ],
}
else:
results[path] = {
include_statement_value: {
'actual_filenames': [None, ],
'actual_paths' : [None, ],
},
}
continue
continue
print("\n")
print("Results:")
print("========")
n = len(results)
print(
f"Found {n} include statement issues:\n"
f" - Inconsistencies between the include statement and filename in the filesystem.\n"
f" - Backslashes in the include statement (causes build to fail on Linux).\n"
f"Start fix...\n"
)
k = 0
s = 0
e = 0
g = 0
automatic = False
for path in results.keys():
k += 1
print(f"File({k}/{n}): {path}")
for include_statement_value, actual_filenames_and_paths in results[path].items():
print(f" '#include \"{include_statement_value}\"'")
if len(actual_filenames_and_paths['actual_filenames']) == 1:
print(f" Should be:")
else:
print(f" Should be one of:")
correct_include_statement_values = []
for j in range(len(actual_filenames_and_paths['actual_filenames'])):
actual_filename = actual_filenames_and_paths['actual_filenames'][j]
actual_path = actual_filenames_and_paths['actual_paths'][j]
if actual_filename is None:
# Just correct the backslashes
correct_include_statement_values.append(
include_statement_value.replace('\\', '/')
)
print(f" {j + 1}: '#include \"{correct_include_statement_values[-1]}\"'")
else:
correct_include_statement_values.append(
include_statement_value.replace(
include_statement_value.replace('\\', '/').split('/')[-1], actual_filename
).replace('\\', '/')
)
print(f" {j + 1}: '#include \"{correct_include_statement_values[-1]}\"' ({actual_path})")
print(f" {j + 2}: Skip")
print(f" {j + 3}: Fix all {n} files automatically")
print(f" {j + 4}: Skip all - quit program")
if not dry_run:
if not automatic:
chosen_nr = input(" Choose a number and hit enter (no value = first choice): ")
else:
chosen_nr = '1'
if chosen_nr == '':
chosen_nr = '1'
if chosen_nr == str(j + 2):
print(f" Skipped.")
print("\n")
s += 1
continue
if chosen_nr == str(j + 3):
automatic = True
print(f" Fixing all automatically.")
print("\n")
chosen_nr = '1'
if chosen_nr == str(j + 4):
print(f" Quitting program.")
sys.exit(0)
try:
chosen_nr = int(chosen_nr)
except ValueError:
print(f" Invalid choice. Skipped.")
print("\n")
s += 1
continue
try:
correct_include_statement_value = correct_include_statement_values[chosen_nr - 1]
except IndexError:
print(f" Invalid choice. Skipped.")
print("\n")
s += 1
continue
with open(os.path.join(root_dir, path), 'r', encoding='utf-8', errors='replace') as f:
old_content = f.read()
correct_with_quotes = True
new_content = old_content.replace(f'#include \"{include_statement_value}\"', f'#include \"{correct_include_statement_value}\"')
if new_content == old_content:
# The include statement was probably with '<>' instead of '""'
correct_with_quotes = False
new_content = old_content.replace(f'#include <{include_statement_value}>', f'#include <{correct_include_statement_value}>')
if new_content == old_content:
print(f" Unable to correct include statement. Do it manually. Skipped.")
print("\n")
e += 1
continue
with open(os.path.join(root_dir, path), 'w', encoding='utf-8', errors='replace') as f:
f.write(new_content)
if correct_with_quotes:
print(f" Fixed include statement from '#include \"{include_statement_value}\"' to '#include \"{correct_include_statement_value}\"'.")
else:
print(f" Fixed include statement from '#include <{include_statement_value}>' to '#include <{correct_include_statement_value}>'.")
g += 1
print("\n")
continue
continue
print(f"Summary:")
print(f"========")
print(f"Skipped: {s}")
print(f"Fixed: {g}")
print(f"Errors: {e}")
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=str(
"Check the codebase for inconsistencies between the include statements in the files "
"and the actual filenames in the filesystem."
)
)
# Add arguments to the parser
parser.add_argument(
'-n',
'--dry-run',
action='store_true',
help='Print the results without fixing the include statements',
)
parser.add_argument(
'-d',
'--directory',
type=str,
help='The root directory of the codebase to check (default: .)',
default=os.getcwd(),
)
# Override the default help message with a custom one
parser.print_help = print_help
# Parse the arguments. If the '-h' or '--help' argument is provided, the help message is printed
# and the script exits automatically.
args = parser.parse_args()
# If this script runs in active mode (not dry-run), prompt the user first to confirm the action.
if not args.dry_run:
print(
f"\n"
f"WARNING:\n"
f"This script will check the codebase for inconsistencies between the include\n"
f"statements in the files and the actual filenames in the filesystem. It will\n"
f"process the folder '{args.directory}'.\n"
f"This action is irreversible. Type 'yes' to confirm you made a backup of the folder.\n"
f"Type anything else to abort the operation.\n"
f"\n"
)
response = input("Type 'yes' to confirm: ")
if response.lower() == "yes":
print("Confirmed. Starting the process.")
else:
print("Operation aborted. Showing help info...")
print("\n")
print_help()
sys.exit(0)
# Check the codebase for inconsistencies
check_codebase(args.directory, args.dry_run)
sys.exit(0)