forked from riebl/artery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opp_cmake.py
executable file
·325 lines (263 loc) · 12 KB
/
opp_cmake.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python3
from functools import partial
from distutils.version import StrictVersion
import os
import re
import subprocess
import sys
class OmnetProject:
def __init__(self, makefile):
self.name = ""
self.makefile = makefile
self.makefile_defines = {}
self.root_directory = self.lookup_project_directory()
self.output_directory = "out"
self.include_directories = []
self.include_directories_deep = []
self.library_directories = []
self.link_libraries = []
self.compile_definitions = []
self.binary = "executable"
self.ned_folders = []
def lookup_project_directory(self):
candidate = os.path.dirname(self.makefile)
root = os.path.abspath(os.sep)
while (os.path.isfile(os.path.join(candidate, '.project')) is False):
candidate = os.path.abspath(os.path.join(candidate, os.path.pardir))
if (candidate == root):
raise ValueError("Can not determine project directory for ${self.makefile}")
return candidate
def read_ned_folders(self):
self.ned_folders = []
with open(os.path.join(self.root_directory, '.nedfolders'), 'r') as dotnedfolders:
for line in dotnedfolders:
if line[0] != '-':
self.ned_folders.append(line.strip())
class CMakeTarget:
def __init__(self, project, toolchain='gcc', debug_suffix=''):
self._project = project
self._toolchain = toolchain
self._debug_suffix = debug_suffix
self.include_directories = [self._make_absolute_path(self._makefile_path(), d) for d in self._project.include_directories]
for dd in self._project.include_directories_deep:
self.include_directories.append(dd)
self.library_directories = [self._make_absolute_path(self._makefile_path(), d) for d in self._project.library_directories]
self.ned_folders = [self._make_absolute_path(self.root_directory, d) for d in self._project.ned_folders]
def _make_absolute_path(self, root, path):
return os.path.normpath(os.path.join(root, path))
def _makefile_path(self):
return os.path.dirname(self._project.makefile)
def _target_output_path(self, mode):
out_subdir = os.path.relpath(self._makefile_path(), self._project.root_directory)
return os.path.join(self._project.root_directory, self._project.output_directory, mode, out_subdir)
def _filename(self, mode):
binary = {
'executable': "{}${{CMAKE_EXECUTABLE_SUFFIX}}",
'shared': "${{CMAKE_SHARED_LIBRARY_PREFIX}}{}${{CMAKE_SHARED_LIBRARY_SUFFIX}}",
'static': "${{CMAKE_STATIC_LIBRARY_PREFIX}}{}${{CMAKE_STATIC_LIBRARY_SUFFIX}}"
}
name = self._project.name + (self._debug_suffix if mode == 'debug' else '')
return binary[self._project.binary].format(name)
def _import_location(self, mode):
filename = self._filename(mode)
path = None
if (mode == "release"):
path = self._target_output_path('{}-release'.format(self._toolchain))
elif (mode == "debug"):
path = self._target_output_path('{}-debug'.format(self._toolchain))
else:
path = self._makefile_path()
return os.path.join(path, filename)
def __getattr__(self, name):
return getattr(self._project, name)
@property
def location(self):
return self._import_location()
@property
def location_debug(self):
return self._import_location('debug')
@property
def location_release(self):
return self._import_location('release')
@property
def target(self):
target = {
'executable': "add_executable({} IMPORTED GLOBAL)",
'shared': "add_library({} SHARED IMPORTED GLOBAL)",
'static': "add_library({} STATIC IMPORTED GLOBAL)"
}
return target[self._project.binary].format(self._project.name)
@property
def target_properties(self, ned_folders_property=True):
props = ["set_target_properties({} PROPERTIES".format(self.name)]
configurations = []
if os.path.exists(os.path.dirname(self.location_release)):
props.append(" IMPORTED_LOCATION_RELEASE \"{}\"".format(self.location_release))
props.append(" IMPORTED_NO_SONAME TRUE")
configurations.append("RELEASE")
if os.path.exists(os.path.dirname(self.location_debug)):
props.append(" IMPORTED_LOCATION_DEBUG \"{}\"".format(self.location_debug))
props.append(" IMPORTED_NO_SONAME TRUE")
configurations.append("DEBUG")
if self.binary != "executable":
if self.include_directories:
include_dirs = ';'.join(self.include_directories)
props.append(" INTERFACE_INCLUDE_DIRECTORIES \"{}\"".format(include_dirs))
if self.link_libraries:
link_libraries = ';'.join(self.link_libraries)
props.append(" INTERFACE_LINK_LIBRARIES \"{}\"".format(link_libraries))
if self.compile_definitions:
compile_defs = ';'.join(self.compile_definitions)
props.append(" INTERFACE_COMPILE_DEFINITIONS \"{}\"".format(compile_defs))
if ned_folders_property and self.ned_folders:
ned_folders = ';'.join(self.ned_folders)
props.append(" NED_FOLDERS \"{}\"".format(ned_folders))
props.append(" OMNETPP_LIBRARY TRUE")
props.append(")")
props.append("set_property(TARGET {target} PROPERTY IMPORTED_CONFIGURATIONS {configs})"
.format(target=self.name, configs=" ".join(configurations)))
return props
class FlagsHandler:
def __init__(self, makefile, configfile):
self._iterator = None
self._options = {
"-f": self.ignore,
"--force": self.ignore,
"-p": self.skip,
"--deep": self.ignore,
"--no-deep-includes": self.ignore,
"-s": partial(self.binary_type, "shared"),
"--make-so": partial(self.binary_type, "shared"),
"-a": partial(self.binary_type, "static"),
"--make-lib": partial(self.binary_type, "static"),
"-o": self.project_name,
"-O": self.output_directory,
"--out": self.output_directory,
"-X": self.exclude_directory,
"--except": self.exclude_directory,
"-I": self.include_directory,
"-L": self.library_directory,
"-l": self.library,
"-D": self.compile_definition,
"--define": self.compile_definition,
"-P": self.project_directory,
"--projectdir": self.project_directory,
"-K": self.makefile_define,
"--makefile-define": self.makefile_define
}
self._project = OmnetProject(makefile)
self._configfile = configfile
def process(self, flags):
self._iterator = iter(flags)
for flag in self._iterator:
if flag in self._options:
self._options[flag]()
else:
raise RuntimeError("Unknown flag", flag)
for key, value in self._project.makefile_defines.items():
key_pattern = "$(" + key + ")"
self._project.include_directories = [incdir.replace(key_pattern, value) for incdir
in self._project.include_directories]
self._project.library_directories = [libdir.replace(key_pattern, value) for libdir
in self._project.library_directories]
self._project.link_libraries = [lnklib.replace(key_pattern, value) for lnklib
in self._project.link_libraries]
def target(self):
self._project.read_ned_folders()
opp_version = StrictVersion(which_opp_version(self._configfile))
debug_suffix = '_dbg' if opp_version >= StrictVersion('5.2.0') else ''
return CMakeTarget(self._project, which_opp_toolchain(self._configfile), debug_suffix)
def ignore(self):
pass
def skip(self):
next(self._iterator)
def fetch(self):
return next(self._iterator)
def binary_type(self, binary):
self._project.binary = binary
def project_name(self):
self._project.name = self.fetch()
def output_directory(self):
self._project.output_directory = self.fetch()
def exclude_directory(self):
self.skip()
def include_directory(self):
self._project.include_directories.append(self.fetch())
def library_directory(self):
self._project.library_directories.append(self.fetch())
def library(self):
self._project.link_libraries.append(self.fetch())
def compile_definition(self):
self._project.compile_definitions.append(self.fetch())
def project_directory(self):
self._project.root_directory = self.fetch()
def makefile_define(self):
(name, value) = self.fetch().split('=', maxsplit=1)
self._project.makefile_defines[name] = value
def find_opp_configfile():
configfile = None
if os.environ.get('OMNETPP_CONFIGFILE'):
configfile = os.environ['OMNETPP_CONFIGFILE']
elif os.environ.get('OMNETPP_ROOT'):
configfile = os.path.join(os.environ['OMNETPP_ROOT'], 'Makefile.inc')
else:
opp_configfilepath = subprocess.check_output('opp_configfilepath', shell=True)
configfile = str(opp_configfilepath, encoding='utf-8').rstrip('\n')
if not os.path.isfile(configfile):
raise Exception('Assumed OMNeT++ configfile at {} does not exist'.format(configfile))
return configfile
def which_opp_toolchain(configfile_path):
with open(configfile_path, "r", encoding="utf-8") as configfile:
toolchain_pattern = re.compile(r"TOOLCHAIN_NAME = (\S+)")
for line in configfile:
line_match = toolchain_pattern.match(line)
if line_match:
return line_match.group(1)
def which_opp_version(configfile_path):
with open(configfile_path, "r", encoding="utf-8") as configfile:
version_pattern = re.compile(r"OMNETPP_VERSION = ([0-9\.]+)")
for line in configfile:
line_match = version_pattern.match(line)
if line_match:
return line_match.group(1)
def parse_opp_makefile(makefile):
command = extract_makemake_command(makefile)
makemake_flags = command.split()
makemake_flags.pop(0)
# Normalize flags
for i, flag in enumerate(makemake_flags):
if len(flag) > 2 and flag.startswith("-") and not flag.startswith("--"):
makemake_flags.insert(i + 1, flag[2:])
makemake_flags[i] = flag[0:2]
handler = FlagsHandler(makefile, find_opp_configfile())
handler.process(makemake_flags)
return handler.target()
def extract_makemake_command(makefile_path):
with open(makefile_path, "r", encoding="utf-8") as makefile:
command_pattern = re.compile("#\s+(opp_makemake .*)$")
for line in makefile:
line_match = command_pattern.match(line)
if line_match:
return line_match.group(1)
elif not line.startswith("#"):
break
raise ValueError("Can not find opp_makemake command call in Makefile")
def generate_cmake_target(cmake, destination):
fh = open(destination, "w", encoding="utf-8")
lines = ["# Generated by opp_cmake"]
lines.append(cmake.target)
lines.extend(cmake.target_properties)
fh.writelines(line + '\n' for line in lines)
def main():
if len(sys.argv) <= 2:
print(os.path.basename(sys.argv[0]), ": <OMNeT++ Makefile> <CMake targets destination>")
else:
makefile = sys.argv[1]
cmake = sys.argv[2]
target = parse_opp_makefile(makefile)
if target:
generate_cmake_target(target, cmake)
else:
print("No targets found in ", makefile)
if __name__ == "__main__":
main()