This repository has been archived by the owner on Dec 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcmake_build.py
360 lines (326 loc) · 12.3 KB
/
cmake_build.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env python
class Tools(object):
def __init__(self):
pass
def createDir(self, path):
'''
Creates the specified directory if not exists.
'''
import errno, os
# create dir
try:
if not os.path.isdir(path):
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def isSubirectory(self, directory, subDirectory):
'''
Checks whether a directory is a sub directory of another directory.
'''
import os
# Make both paths absolute
directory = os.path.abspath(directory)
subDirectory = os.path.abspath(subDirectory)
# return true, if the common prefix of both is equal to directory
return os.path.commonprefix([directory, subDirectory]) == directory
def getCPUCount(self):
'''
Returns the number of CPUs in the system.
'''
import multiprocessing
return multiprocessing.cpu_count()
def removeDir(self, path):
'''
Deletes the folders in the given path recursively.
'''
import errno, os, shutil
if os.path.isdir(path):
try:
shutil.rmtree(path)
except OSError as error:
if error.errno != errno.ENOENT:
raise
def runCommand(self, directory, command, extraEnv=None):
'''
Executes the command in the specified directory.
'''
import os, subprocess
try:
basestring
except NameError:
basestring = str
shell = isinstance(command, basestring)
env = os.environ.copy()
if extraEnv:
env.update(extraEnv)
print("Executing command '%s' in directory '%s'" % (command, directory))
subprocess.check_call(command, shell=shell, env=env, cwd=directory)
class Build(object):
def __init__(self):
'''
Constructor
'''
import argparse, sys
progName = argparse.ArgumentParser().prog
parser = argparse.ArgumentParser(
description='%s' % progName,
usage='''%s <command> [<args>]
The supported build commands are:
all [<options>] builds all the targets
supported build options:
[--mode=<mode>] the build mode, should we either 'release' or 'debug' mode
clean_all cleans all the build directories
configure [<options>] configures the cmake project
supported configuration options:
[--mode=<mode>] the build mode, should we either 'release' or 'debug' mode
devenv starts the IDE (Visual Studio on Windows) and loads the project
supported build options:
[--mode=<mode>] the build mode, should we either 'release' or 'debug' mode
update fetches sources from master and integrates then into the local branch
update submodules fetches latest version of all git submodules
''' % progName)
parser.add_argument('command', help='Subcommand to run')
args = parser.parse_args(sys.argv[1:2])
if not hasattr(self, args.command):
print('Unrecognized command')
parser.print_help()
exit(1)
# helper vars
self._tools = Tools()
self._buildDir = None
self._buildMode = "release"
# use dispatch pattern to invoke method with same name
getattr(self, args.command)()
def all(self):
'''
Builds all the targets.
'''
import argparse, sys
parser = argparse.ArgumentParser(description='build all')
parser.add_argument('--mode', type=str, dest='mode',
choices = ['release', 'debug'], action='store',
default='release', help="the build mode, ' \
'should we either 'release' or 'debug' mode.")
args = parser.parse_args(sys.argv[2:])
self._cmakeConfigure(args)
self._doBuild(args)
def clean_all(self):
'''
Removes all the build directories.
'''
# - Remove the release build directory
self._tools.removeDir(self._getBuildDirectory(releaseBuild=True))
# - Remove the debug build directory
self._tools.removeDir(self._getBuildDirectory(releaseBuild=False))
def configure(self):
'''
Parses the configure command and runs the cmake configure command.
'''
import argparse, sys
parser = argparse.ArgumentParser(description='configure')
parser.add_argument('--mode', type=str, dest='mode',
choices = ['release', 'debug'], action='store',
default='release', help="the build mode, ' \
'should we either 'release' or 'debug' mode.")
args = parser.parse_args(sys.argv[2:])
self._cmakeConfigure(args)
def devenv(self):
'''
Parses the devenv command and starts the IDE.
'''
import argparse, sys
parser = argparse.ArgumentParser(description='devenv')
parser.add_argument('--mode', type=str, dest='mode',
choices = ['release', 'debug'], action='store',
default='release', help="the build mode, ' \
'should we either 'release' or 'debug' mode.")
args = parser.parse_args(sys.argv[2:])
self._devenv(args)
def update(self):
'''
Fetches sources from master and integrates then into the local branch.
'''
import os, sys
updateArgs = sys.argv[2:]
if len(updateArgs) == 0:
# Pull latest version from master
gitPullCmd = ['git', 'pull', 'origin', 'master']
self._tools.runCommand(os.getcwd(), gitPullCmd)
else:
updateMode = updateArgs[0]
# Pull latest version of all git submodules
if updateMode == 'submodules':
gitPullCmd = ['git', 'submodule', 'update', '--recursive',
'--remote']
self._tools.runCommand(os.getcwd(), gitPullCmd)
def _getBuildDirectory(self, releaseBuild = True):
"""
Returns the name of the build directory.
"""
return ["debug_build", "release_build"][releaseBuild]
def _cmakeConfigure(self, args):
'''
Runs the cmake configure command.
'''
# determine the build directory name
isReleaseBuild = (args.mode == 'release')
self._buildDir = self._getBuildDirectory(isReleaseBuild)
self._buildMode = args.mode
# create the build directory
self._tools.createDir(self._buildDir)
# get the cmake options
cmakeOptions = self._getCMakeOptions(
releaseBuild = isReleaseBuild
)
# Configures the cmake project
cmakeCmd = ["cmake", "../"] + cmakeOptions
self._tools.runCommand(self._buildDir, cmakeCmd)
def _devenv(self, args):
'''
Starts the IDE (Visual Studio on Windows) and loads the project
'''
# determine the build directory name
isReleaseBuild = (args.mode == 'release')
self._buildDir = self._getBuildDirectory(isReleaseBuild)
self._buildMode = args.mode
# start the IDE
devenvCommand = self.getDevenvCommand()
self._tools.runCommand(self._buildDir, devenvCommand)
def _getCMakeOptions(self, releaseBuild = True):
"""
Returns the cmake options.
"""
# build mode
cmakeOptions = ["-DCMAKE_BUILD_TYPE=%s" % \
["Debug", "Release"][releaseBuild]]
# cmake generator
cmakeOptions += ["-G", self.getCMakeGenerator()]
return cmakeOptions
def _doBuild(self, args):
"""
Returns the build.
"""
# determine the build directory name
isReleaseBuild = (args.mode == 'release')
self._buildDir = self._getBuildDirectory(isReleaseBuild)
self._buildMode = args.mode
# run the build
buildCommand = self.getBuildCommand()
self._tools.runCommand(self._buildDir, buildCommand)
class LinuxBuild(Build):
def __init__(self):
'''
Constructor.
'''
Build.__init__(self)
def getCMakeGenerator(self):
'''
Returns the CMake generator.
'''
return 'Unix Makefiles'
def getDevenvCommand(self):
'''
Returns command to start the IDE.
'''
return ''
def getPlatformKey(self):
'''
Returns the platform key.
'''
import platform, sys
bitness = '64' if platform.architecture()[0] == '64bit' else '32'
if sys.platform == 'linux' or sys.platform == 'linux2':
return 'linux_x86_%s' % bitness
return 'unknown'
def getBuildCommand(self, verbose=False):
'''
Returns the build command.
'''
# Create the make command
buildCommand = ["make"]
if verbose:
# - Enable verbose mode
buildCommand += ["--debug=v"]
# - Specifies the number of jobs to run simultaneously
buildCommand += ["--jobs=%d" % self._tools.getCPUCount()]
return buildCommand
class WindowsBuild(Build):
def __init__(self, msvcVer='vs2017Community'):
'''
Constructor.
'''
# Microsoft Visual Studio defintions
self._msvcDefs = {
# Microsoft Visual Studio 2017 Community Version
'vs2017Community': {
'productName': 'Visual Studio 2017',
'versionNumber': '15.0',
'cmakeGeneratorPlatform': 'Visual Studio 15 2017 Win64',
'path': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\Auxiliary\\Build\\vcvars64.bat'
},
'vs2019Community': {
'productName': 'Visual Studio 2019',
'versionNumber': '16.0',
'cmakeGeneratorPlatform': 'Visual Studio 16 2019',
'path': 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\Auxiliary\\Build\\vcvars64.bat'
}
}
self._msvcDef = self._msvcDefs[msvcVer]
# init superclass
Build.__init__(self)
def getCMakeGenerator(self):
'''
Returns the CMake generator for Microsoft Visual Studio.
'''
return self._msvcDef['cmakeGeneratorPlatform']
def getDevenvCommand(self):
'''
Returns command to start Visual Studio.
'''
return 'start BabylonCpp.sln'
def getPlatformKey(self):
'''
Returns the platform key.
'''
import platform, sys
bitness = '64' if platform.architecture()[0] == '64bit' else '32'
if sys.platform == 'win32':
return 'win32_%s' % bitness
return 'unknown'
def getBuildCommand(self, verbose=False):
'''
Returns the build command.
'''
import os
# Create batch file for running the build
batchFileName = 'runMSVCBuild.bat'
batchFile = os.path.join(self._buildDir, batchFileName)
projectFile = 'BabylonCpp.sln'
# Build swicthes
switches = []
# - Build mode
buildMode = {'release': 'Release', 'debug': 'Debug'}[self._buildMode]
switches += ['/p:Configuration=%s' % buildMode]
# - Maximum number of concurrent processes to use when building
switches += ['/m']
# - Amount of information to display in the build log
switches += ['/v:minimal']
# Create build script
with open(batchFile, "w") as f:
# Run the Visual Studio developer command prompt
f.write('call "%s"\n' % self._msvcDef['path'])
f.write('msbuild %s %s\n' % (projectFile, ' '.join(switches)))
buildCommand = batchFileName
return buildCommand
def main():
# Platform dependent build
import sys
if sys.platform == 'linux' or sys.platform == 'linux2':
# linux OS
LinuxBuild()
elif sys.platform == 'win32':
# Windows OS
WindowsBuild()
if __name__ == '__main__':
main()