Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/misc/scripts/header_guards.py
20941 views
1
#!/usr/bin/env python3
2
3
import sys
4
5
if len(sys.argv) < 2:
6
print("Invalid usage of header_guards.py, it should be called with a path to one or multiple files.")
7
sys.exit(1)
8
9
changed = []
10
invalid = []
11
12
for file in sys.argv[1:]:
13
header_start = -1
14
header_end = -1
15
16
with open(file.strip(), "rt", encoding="utf-8", newline="\n") as f:
17
lines = f.readlines()
18
19
for idx, line in enumerate(lines):
20
sline = line.strip()
21
22
if header_start < 0:
23
if sline == "": # Skip empty lines at the top.
24
continue
25
26
if sline.startswith("/**********"): # Godot header starts this way.
27
header_start = idx
28
else:
29
header_end = 0 # There is no Godot header.
30
break
31
else:
32
if not sline.startswith(("*", "/*")): # Not in the Godot header anymore.
33
header_end = idx + 1 # The guard should be two lines below the Godot header.
34
break
35
36
if (HEADER_CHECK_OFFSET := header_end) < 0 or HEADER_CHECK_OFFSET >= len(lines):
37
invalid.append(file)
38
continue
39
40
if lines[HEADER_CHECK_OFFSET].startswith("#pragma once"):
41
continue
42
43
# Might be using legacy header guards.
44
HEADER_BEGIN_OFFSET = HEADER_CHECK_OFFSET + 1
45
HEADER_END_OFFSET = len(lines) - 1
46
47
if HEADER_BEGIN_OFFSET >= HEADER_END_OFFSET:
48
invalid.append(file)
49
continue
50
51
if (
52
lines[HEADER_CHECK_OFFSET].startswith("#ifndef")
53
and lines[HEADER_BEGIN_OFFSET].startswith("#define")
54
and lines[HEADER_END_OFFSET].startswith("#endif")
55
):
56
lines[HEADER_CHECK_OFFSET] = "#pragma once"
57
lines[HEADER_BEGIN_OFFSET] = "\n"
58
lines.pop()
59
with open(file, "wt", encoding="utf-8", newline="\n") as f:
60
f.writelines(lines)
61
changed.append(file)
62
continue
63
64
# Verify `#pragma once` doesn't exist at invalid location.
65
misplaced = False
66
for line in lines:
67
if line.startswith("#pragma once"):
68
misplaced = True
69
break
70
71
if misplaced:
72
invalid.append(file)
73
continue
74
75
# Assume that we're simply missing a guard entirely.
76
lines.insert(HEADER_CHECK_OFFSET, "#pragma once\n\n")
77
with open(file, "wt", encoding="utf-8", newline="\n") as f:
78
f.writelines(lines)
79
changed.append(file)
80
81
if changed:
82
for file in changed:
83
print(f"FIXED: {file}")
84
if invalid:
85
for file in invalid:
86
print(f"REQUIRES MANUAL CHANGES: {file}")
87
sys.exit(1)
88
89