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