-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathadd-include-guard
executable file
·180 lines (156 loc) · 4.69 KB
/
add-include-guard
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
#!/usr/bin/env python
if __name__ != "__main__":
raise ImportError("not an importable module")
# replacement for types.SimpleNamespace in Python 3.3
class SimpleNamespace(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
return "{0}({1})".format(type(self).__name__, ", ".join(
"{0}={1!r}".format(k, v)
for k, v in sorted(self.__dict__.items())
))
def __eq__(self, other):
return self.__dict__ == other.__dict__
def scope(f):
'''Curry the given function with an empty instance of `SimpleNamespace` as
the first argument.'''
import functools
return functools.partial(f, SimpleNamespace())
@scope
def lazy(self, f):
def inner():
try:
return self.value
except AttributeError:
pass
value = f()
self.value = value
return value
return inner
@lazy
def preferredencoding():
import locale
return locale.getpreferredencoding()
def read_file(filename):
'''Read a binary file. If `filename` is `None`, standard input is used
instead.'''
# standard input
if filename is None:
return stdin.read()
# file
with open(filename, "rb") as f:
return f.read()
def write_file(filename, contents):
'''Write a binary file. If `filename` is `None`, standard output is used
instead.'''
# standard output
if filename is None:
stdout.write(contents)
return
# write to temporary file first
import os, tempfile
name = os.path.basename(filename)
with tempfile.NamedTemporaryFile(dir=os.path.dirname(filename),
prefix=name + ".",
suffix=".tmp",
delete=False) as tmp:
tmp_fn = tmp.name
try:
tmp.file.write(contents)
except:
os.remove(tmp_fn)
raise
# overwrite target file with temporary file
try:
os.rename(tmp_fn, filename)
except OSError:
import shutil
os.remove(filename)
os.rename(tmp_fn, filename)
import argparse, random, re, string, sys
try:
stdin = sys.stdin.buffer
stdout = sys.stdout.buffer
except AttributeError:
stdin = sys.stdin
stdout = sys.stdout
opts = argparse.ArgumentParser(description="Add include guards")
opts.add_argument(
"FILE",
nargs="?",
help="input file (defaults to stdin); must be UTF-8/ASCII",
)
opts.add_argument(
"-i",
"--in-place",
action="store_true",
help="modify the file instead of writing to stdout",
)
opts.add_argument(
"-p",
"--prefix",
help="prefix for the guard macro (default: 'G_')",
)
opts.add_argument(
"-s",
"--suffix",
help="suffix for the guard macro (default: none)",
)
mode = opts.add_mutually_exclusive_group()
mode.add_argument(
"-f",
"--force",
action="store_true",
help="don't check whether the file already has a guard",
)
mode.add_argument(
"-r",
"--replace",
action="store_true",
help="replace the existing guard",
)
args = opts.parse_args()
encoding = preferredencoding()
max_len = 31 # maximum length of macro name in C89
prefix = "G_" if args.prefix is None else args.prefix
suffix = "" if args.suffix is None else args.suffix
if len(prefix) + len(suffix) >= max_len:
sys.stderr.write("prefix and suffix are too long\n")
sys.exit(1)
if not prefix:
prefix = random.choice(string.ascii_uppercase)
macro = prefix
macro += "".join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(max_len - len(prefix) - len(suffix)))
macro += suffix
try:
input = read_file(args.FILE).decode(encoding)
except Exception as e:
sys.stderr.write(str(e) + "\n")
sys.exit(1)
if not args.FILE and args.in_place:
sys.stderr.write("can't use --in-place if input file is stdin\n")
sys.exit(1)
pattern = r"\s*#\s*ifndef\s+\S+\s*\n\s*#\s*define\s+\S+\s*\n(.*)\n#\s*endif\s*$"
match = re.match(pattern, input, flags=re.DOTALL)
if match:
if args.replace:
input, = match.groups()
elif not args.force:
sys.stderr.write("looks like the file already has a guard\n")
sys.stderr.write("use --replace (-r) to replace existing guard\n")
sys.stderr.write("or use --force (-f) to do it anyway\n")
sys.exit(1)
if not input.endswith("\n"):
input += "\n"
output = []
output.append("#ifndef ")
output.append(macro)
output.append("\n#define ")
output.append(macro)
output.append("\n")
output.append(input)
output.append("#endif\n")
write_file(args.FILE if args.in_place else None,
"".join(output).encode(encoding))