-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat_files.py
58 lines (42 loc) · 1.7 KB
/
format_files.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
# Formats C++ code in codebase
# - Adds trailing newline
# - Fixes incorrect header guards
# - Ensures sources files use the .cc extension
import os
CODE_PATHS = ["src", "test"]
root = os.path.dirname(os.path.realpath(__file__))
for path in CODE_PATHS:
for subdir, dirs, files in os.walk(path):
for file in files:
if not file.endswith(".cpp") and not file.endswith(".cc") and not file.endswith(".h"):
continue
modified = False
relative_path = os.path.join(subdir, file)
with open(relative_path, "r+") as file_handle:
lines = file_handle.read().split("\n")
# Enforce trailing newline
if len(lines[-1]) > 0:
lines.append("")
modified = True
# Coerce header guards
if file.endswith(".h"):
header_guard = relative_path.upper().replace("\\", "_").replace("/", "_")[:-2] + "_H_"
end_guard_line_index = 0
for (index, line) in enumerate(lines):
if line.startswith("#endif"):
end_guard_line_index = index
guard_line = f"#ifndef {header_guard}"
define_line = f"#define {header_guard}"
end_guard_line = f"#endif // {header_guard}"
if lines[0] != guard_line or lines[1] != define_line or lines[end_guard_line_index] != end_guard_line:
lines[0] = guard_line
lines[1] = define_line
lines[end_guard_line_index] = end_guard_line
modified = True
if modified:
file_handle.seek(0)
file_handle.write("\n".join(lines))
file_handle.truncate()
# .cpp -> .cc
if file.endswith(".cpp"):
os.rename(relative_path, relative_path[:-4] + ".cc")