This repository has been archived by the owner on Apr 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathmkcmake.py
executable file
·244 lines (196 loc) · 7.36 KB
/
mkcmake.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
#!/usr/bin/env python3
import os
import re
import sys
from collections import defaultdict
from os.path import normpath
def main():
name = None
srcdirs = ['.']
apps = []
state = 'normal'
mapping = defaultdict(list)
previous_token = ''
for line in open('Recipe').readlines():
line = line.strip()
if line.startswith('#') or not line:
continue
if 'block' == state:
if '!end' == line:
state = 'normal'
continue
if line.startswith('!'):
parts = line.split(' ')
if '!name' == parts[0]:
assert 2 == len(parts)
name = parts[1]
elif '!makefile' == parts[0] or '!cflags' == parts[0]:
pass # ignored
elif '!srcdir' == parts[0]:
assert 2 == len(parts)
srcdirs += [parts[1]]
elif '!begin' == parts[0]:
state = 'block'
else:
raise Exception("unknown token {}".format(parts[0]))
continue
parts = re.split(r"\s+", line)
token = parts.pop(0)
if '+' == token:
token = previous_token
else:
op = parts.pop(0)
if ':' == op:
token += parts.pop(0)
apps += [token]
else:
assert '=' == op
assert parts
mapping[token].extend(parts)
previous_token = token
# print(name)
# print(srcdirs)
# print(mapping)
print("""\
# generated by mkcmake.py
# verbatim section:
cmake_minimum_required (VERSION 3.4)
project ({})
if (UNIX)
find_package (PkgConfig REQUIRED)
pkg_check_modules (GTK3 REQUIRED gtk+-3.0)
find_package (X11 REQUIRED)
include_directories (${{GTK3_INCLUDE_DIRS}} ${{X11_INCLUDE_DIR}})
link_directories (${{GTK3_LIBRARY_DIRS}})
add_definitions (${{GTK3_CFLAGS_OTHER}})
#configure_file (unix/uxconfig.h.in ${{CMAKE_CURRENT_BINARY_DIR}}/uxconfig.h)
#include_directories (${{CMAKE_CURRENT_BINARY_DIR}})
#add_definitions (-DHAVE_CONFIG_H)
endif (UNIX)
if (WIN32)
add_definitions(-D_WINDOWS=1)
add_definitions(-DNO_MANIFESTS=1)
endif (WIN32)
if (MSVC)
# cmake's quoting rules are a bit mad here. An unquoted argument will become a list-type,
# which will have semicolons randomly inserted when converted back to a string-type.
# cflags can't be a list-type (???), so we must be careful to keep everything as a string
# https://www.owasp.org/index.php/C-Based_Toolchain_Hardening#Visual_Studio
set(EXTRA_FLAGS "${{EXTRA_FLAGS}} /GS") # buffer security check
set(EXTRA_FLAGS "${{EXTRA_FLAGS}} /guard:cf") # control flow guard
set(EXTRA_FLAGS "${{EXTRA_FLAGS}} /wd4244") # disable type conversion warnings :(((((
set(EXTRA_FLAGS "${{EXTRA_FLAGS}} /wd4267") # disable type conversion warnings :(((((
add_definitions(-D_CRT_SECURE_NO_WARNINGS=1)
set(CMAKE_C_FLAGS "${{CMAKE_C_FLAGS}} ${{EXTRA_FLAGS}}")
set(CMAKE_CXX_FLAGS "${{CMAKE_CXX_FLAGS}} ${{EXTRA_FLAGS}}")
set(CMAKE_C_FLAGS_DEBUG "${{CMAKE_C_FLAGS_DEBUG}} /MTd")
set(CMAKE_CXX_FLAGS_DEBUG "${{CMAKE_CXX_FLAGS_DEBUG}} /MTd")
set(CMAKE_C_FLAGS_RELEASE "${{CMAKE_C_FLAGS_RELEASE}} /MT /GL")
set(CMAKE_CXX_FLAGS_RELEASE "${{CMAKE_CXX_FLAGS_RELEASE}} /MT /GL")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${{CMAKE_EXE_LINKER_FLAGS_DEBUG}} /guard:cf")
set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${{CMAKE_EXE_LINKER_FLAGS_RELEASE}} /guard:cf /ltcg /opt:ref")
endif (MSVC)
if (MINGW)
# undefined reference to `IN6_IS_ADDR_LOOPBACK'; probably a toolchain bug
add_definitions(-DNO_IPV6=1)
set(CMAKE_EXE_LINKER_FLAGS -static)
endif (MINGW)
# generated from Recipe:
""".format(name))
print('include_directories ({})'.format(' '.join(
sorted('${PROJECT_SOURCE_DIR}/' + normypath(src)
for src in srcdirs))))
for app in sorted(apps):
name, platform = app.split('[')
platform = platform[:-1]
win = None
if 'T' in platform:
continue
if platform in ['G', 'C']:
win = True
elif platform in ['X', 'U']:
win = False
else:
raise Exception('bad platform: ' + platform)
if win:
print('if (WIN32)')
else:
print('if (UNIX)')
expanded = list(expand(mapping, mapping[app]))
files = sorted(to_path(srcdirs, expanded))
# add headers, to placate CLion. Not needed by cmake.
HEADER = re.compile(r'#\s*include\s+"([^"]+)"')
headers = set()
for file in files:
with open(file) as f:
for line in f.readlines():
ma = HEADER.match(line.strip())
if ma:
headers.add(ma.group(1))
headers = sorted(find_literal_file(srcdirs, header)
for header in headers
# generated or build system nonsense
if header not in ['uxconfig.h', 'empty.h']
# evading #include "enum.c" (sigh)
and header.endswith('.h'))
if win:
headers.append('windows/winstuff.h')
files.extend('windows/{}.rc'.format(x.split('.')[0]) for x in expanded if x.endswith('.res'))
else:
headers.append('unix/unix.h')
print('add_executable({} {}\n {}\n {})'.format(
name,
'WIN32 windows/putty.manifest' if 'G' == platform else '# console app',
' '.join(files),
' '.join(sorted(headers)),
))
if win:
print('target_link_libraries ({}\n {})'.format(
name,
' '.join(file.split('.')[0] for file in expanded if file.endswith('.lib'))))
print('if (MINGW)')
print('target_link_libraries ({} -static-libgcc -static-libstdc++)'.format(name))
print('endif (MINGW)')
print('endif (WIN32)')
else:
print('target_link_libraries ({} -ldl)'.format(name))
if 'X' == platform:
print('target_link_libraries ({} '.format(name) +
'${GTK3_LIBRARIES} ${X11_LIBRARIES})')
print('endif (UNIX)')
def expand(map, list):
for item in list:
if item in map:
yield from expand(map, map[item])
else:
yield item
def to_path(dirs, items):
for item in items:
if '.' in item:
if not item.endswith('.lib') and not item.endswith('.res'):
sys.stderr.write('ignoring path {}\n'.format(item))
else:
yield find_c_file(dirs, item)
def find_c_file(dirs, item):
for ext in ['c', 'cpp']:
cand = dir_expand(dirs, '{}.{}'.format(item, ext))
if cand:
return cand
raise Exception('no file named {}.[c|cpp] found in {}'
.format(item, dirs))
def find_literal_file(dirs, item):
cand = dir_expand(dirs, item)
if cand:
return cand
raise Exception('no file named {} found in {}'
.format(item, dirs))
def dir_expand(dirs, path):
for sub in dirs:
cand = '{}/{}'.format(sub, path)
if os.path.isfile(cand):
return normypath(cand)
return None
def normypath(path):
return normpath(path).replace('\\', '/')
if '__main__' == __name__:
main()