-
Notifications
You must be signed in to change notification settings - Fork 0
/
buildlib.py
557 lines (427 loc) · 14.5 KB
/
buildlib.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#
# Common routines for python build scripts
#
# @maintainer Morgan McGuire, matrix@graphics3d.com
#
# @created 2003-02-15
# @edited 2005-07-17
#
# This script is written in Python. Be aware that
# whitespaces (particularly, indentation and newlines)
# are significant in Python when editing the file.
#
import sys
import string
import os
import os.path
import fileinput
import tempfile
import shutil
import re
###############################################################################
"""
Reads the command line arguments (sys.argv) and dispatches to the appropriate
build target by name.
validTargets - A list of functions that are build targets.
help - A build target to execute if no target is specified
"""
def dispatchOnTarget(validTargets, help):
# Execute the appropriate target:
if (len(sys.argv) == 1) or (sys.argv[1] == "help"):
# No arguments; print help
help()
sys.exit(-1)
target = sys.argv[1]
targetArgs = sys.argv[2:]
found = 0
for v in validTargets:
if (target == v.func_name):
v(targetArgs)
found = 1
break
if (not found):
print '"' + target + '" is not a valid build target (type "build help" to see all targets).'
sys.exit(-1)
sys.exit(0)
###############################################################################
"""Regular explression patterns that will be excluded from copying by
copyIfNewer."""
_excludeFromCopyingPatterns =\
['\^.svn$', \
'\.ncb$', \
'\.opt$', \
'\.ilk$', \
'\.pdb$', \
'\.bsc$', \
'\.o$', \
'\.pch$', \
'\.obj$', \
'\.pyc$', \
'\.plg$', \
'^#.*#$', \
'~$', \
'G3D-Map\.ppt', \
'\.sbr$', \
'-debug\.exe$', \
'^temp$', \
'^tmp$', \
'\.old$' \
'^log.txt$', \
'^stderr\.txt$', \
'^stdout\.txt$', \
'\.log$', \
'\.cvsignore$', \
'^graveyard$', \
'^CVS$', \
'^Debug$', \
'^Release$']
"""
A regular expression matching files that should be excluded from copying.
"""
excludeFromCopying = re.compile(string.join(_excludeFromCopyingPatterns, '|'))
###############################################################################
"""Create a directory if it does not exist."""
def mkdir(path):
if (not os.path.exists(path)):
print 'mkdir ' + path
os.makedirs(path)
def rmdir(path):
if (os.path.exists(path)):
print 'rmdir ' + path
shutil.rmtree(path, 1)
def rm(path):
if os.path.exists(path):
print 'rm ' + path
os.remove(path)
###############################################################################
def removeTrailingSlash(s):
if (s[len(s)-1] == '/'):
s = s[:len(s)-2]
if (s[len(s)-1] == '\\'):
s = s[:len(s)-2]
return s
def moveIfNewer(source, dest):
copyIfNewer(source, dest, 1)
""" Recursively copies all contents of source to dest
(including source itself) that are out of date. Does
not copy files matching the excludeFromCopying patterns.
"""
def copyIfNewer(source, dest, move = 0):
if source == dest:
# Copying in place
return
dest = removeTrailingSlash(dest)
if (not os.path.exists(source)):
# Source does not exist
return
if (not os.path.isdir(source) and newer(source, dest)):
if (move):
print 'mv ' + source + ' ' + dest
shutil.movefile(source, dest)
else:
print 'cp ' + source + ' ' + dest
shutil.copyfile(source, dest)
else:
# Walk is a special iterator that visits all of the
# children and executes the 2nd argument on them.
os.path.walk(source, _copyIfNewerVisit, [len(source), dest, move])
"""os.path.basename strips one extra character from the beginning.
This restores it."""
def _basename(filename):
# Find the index of the last slash
i = max(string.rfind(filename, '/'), string.rfind(filename, '\\'))
# Copy from there on (whole string if no slashes)
return filename[(i + 1):]
"""Helper for copyIfNewer.
args is a list of the length of the source prefix in
sourceDirname and the root of the destination tree.
"""
def _copyIfNewerVisit(args, sourceDirname, names):
prefixLen = args[0]
destDirname = args[1] + sourceDirname[prefixLen:]
move = args[2]
dirName = _basename(destDirname)
if (excludeFromCopying.search(dirName) != None):
# Don't recurse into subdirectories
del names[:]
return
# Create the corresponding destination dir if necessary
mkdir(destDirname)
# Iterate through the contents of this directory
for name in names:
source = sourceDirname + '/' + name
if ((excludeFromCopying.search(name) == None) and \
(not os.path.isdir(source))):
# Copy files if newer
dest = destDirname + '/' + name
if (newer(source, dest)):
if move:
print 'mv ' + source + ' ' + dest
shutil.movefile(source, dest)
else:
print 'cp ' + source + ' ' + dest
shutil.copyfile(source, dest)
###############################################################################
"""Determine if a target is out of date.
Returns nonzero if file1 is newer than file2.
Throws an error if file1 does not exist, returns
nonzero if file2 does not exist."""
def newer(file1, file2):
time1 = os.path.getmtime(file1)
time2 = 0
try:
time2 = os.path.getmtime(file2)
except OSError:
time2 = 0
return time1 >= time2
###############################################################################
"""
Finds an executable on Windows."""
def findBinary(program):
# Paths that may contain the program
PATH = os.getenv('PATH', '').split(';') + \
['.',\
'C:/Program Files/Microsoft Visual Studio 8/Common7/IDE',\
'C:/Program Files/Microsoft Visual Studio/Common/MSDev98/Bin',\
'C:/Program Files/Microsoft Visual Studio .NET 2003/Common7/IDE',\
'C:/Program Files/Microsoft Visual Studio .NET 2002/Common7/IDE',\
'C:/Program Files/Microsoft Visual Studio .NET/Common7/IDE',\
'C:/python',\
'C:/doxygen/bin',\
'C:/Program Files/doxygen/bin',\
'C:/Program Files/PKZIP']
for path in PATH:
filename = path + '/' + program + '.exe'
if (os.path.exists(filename)):
return filename
break
filename = path + '/' + program + '.com'
if (os.path.exists(filename)):
return filename
break
raise 'Error', 'Cannot find "' + program + '"'
return program
###############################################################################
"""Runs MSDEV (VC6) on the given dsw filename and builds the
specified configs. configs is a list of strings
"""
def msdev(filename, configs):
binary = 'msdev'
logfile = tempfile.mktemp()
args = [filename]
for config in configs:
args.append('/MAKE')
args.append('"' + config + '"')
args.append('/OUT')
args.append(logfile)
x = run(binary, args)
# Print the output to standard out
for line in fileinput.input(logfile):
print line.rstrip('\n')
return x
###############################################################################
"""Runs DEVENV (VC7) on the given sld filename and builds the
specified configs. configs is a list of strings
"""
def devenv(filename, configs):
binary = 'devenv'
for config in configs:
for target in ['debug', 'release']:
logfile = tempfile.mktemp()
args = [filename]
args.append('/build')
args.append(target)
args.append('/project "' + config + '"')
args.append('/out')
args.append(logfile)
x = run(binary, args)
# Print the output to standard out
for line in fileinput.input(logfile):
print line.rstrip('\n')
if x != 0:
# Abort-- a build failed
return x;
return 0
##############################################
"""Runs VCExpress (VC8) on the given sln filename and builds the
specified configs. configs is a list of strings
"""
def VCExpress(filename, configs):
binary = 'VCExpress'
for config in configs:
for target in ['debug', 'release']:
logfile = tempfile.mktemp()
args = [filename]
args.append('/build')
args.append(target)
args.append('/project "' + config + '"')
args.append('/out')
args.append(logfile)
x = run(binary, args)
# Print the output to standard out
for line in fileinput.input(logfile):
print line.rstrip('\n')
if x != 0:
# Abort-- a build failed
return x;
return 0
###############################################################################
"""
Recursively zips the source into zipfile
"""
def zip(source, zipfile):
print 'Creating ' + zipfile
if (os.name == 'nt'):
run('pkzip25', ['-add', '-rec', '-lev=9', '-path=relative', zipfile, source])
else:
run('zip', [])
###############################################################################
"""Convert path separators to local style from Unix style.
s is a string that contains a path name."""
def to_local_path(s):
return string.replace(s, '/', os.sep)
###############################################################################
def removeQuotes(s):
if (s[1] == '"'):
s = s[2:]
if (s[(len(s)-2):] == '"'):
s = s[:len(s)-2]
return s
###############################################################################
"""Run a program with command line arguments.
args must be a list.
Switches the slashes from unix to dos style in program.
Blocks until shell returns, then returns the exit code of the program.
"""
def run(program, args = [], env = {}):
program = removeQuotes(to_local_path(program))
# Windows doesn't support spawnvp, so we have to locate the binary
if (os.name == 'nt'):
program = findBinary(program)
# spawn requires specification of argv[0]
# Because the program name may contain spaces, we
# add quotes around it.
args.insert(0, '"' + program + '"')
print string.join(args) + '\n'
print '\n'
if (os.name == 'nt'):
# Windows doesn't support spawnvp
if env != {}:
exitcode = os.spawnve(os.P_WAIT, program, args, env)
else:
exitcode = os.spawnv(os.P_WAIT, program, args)
else:
if env != {}:
exitcode = os.spawnvpe(os.P_WAIT, program, args, env)
else:
exitcode = os.spawnvp(os.P_WAIT, program, args)
# Since we mutated the list, remove the element
# that was inserted.
args.pop(0)
return exitcode
###############################################################################
def isDigit(c):
return (c >= '0') and (c <= '9')
"""
verInfo: A string containing (somewhere) a version number
"""
def findVersion(verInfo):
# Look for a number followed by a period.
for i in xrange(1, len(verInfo) - 1):
if verInfo[i] == '.' and \
isDigit(verInfo[i - 1]) and \
isDigit(verInfo[i + 1]):
# We've found a version number. Walk back to the
# beginning.
i = i - 2
while (i > 0) and isDigit(verInfo[i]):
i = i - 1
i = i + 1
version = []
while (i < len(verInfo)) and isDigit(verInfo[i]):
d = ''
# Now walk forward
while (i < len(verInfo)) and isDigit(verInfo[i]):
d = d + verInfo[i]
i = i + 1
version.append(int(d))
# Skip the non-digit
i = i + 1
return version
return [0]
###############################################################################
class Error(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
"""
Errors out if the version number is not at least minVerString
e.g. checkVersion('python -V', '2.0', 'Requires python 2.0', 1)
stderr: must be set to true if the program prints its version to stderr
"""
def checkVersion(verCmdString, minVerString, errString, stderr = 0):
print '--------------------------------'
actualVerString = shell(verCmdString, stderr)
print '--------------------------------'
print actualVerString
actualVer = findVersion(actualVerString)
minVer = findVersion(minVerString)
# Make the lengths match
while (len(actualVer) < len(minVer)):
actualVer.append(0)
while (len(actualVer) > len(minVer)):
minVer.append(0)
# Check the version from most significant bit to least.
for i in xrange(0, len(minVer)):
if actualVer[i] < minVer[i]:
raise Error, "*** Error: unsupported tool version ***\n" +errString
if actualVer[i] > minVer[i]:
# We are over qualified
return
# If the for loop completes we exactly meet the min requirement.
###############################################################################
def shell(cmd, stderr = 0):
mkdir('temp')
print cmd
try:
os.remove('tmp/system.tmp')
except:
pass
if (stderr):
os.system(cmd + ' >& temp/system.tmp')
else:
os.system(cmd + ' > temp/system.tmp')
result = ''
for line in fileinput.input('temp/system.tmp'):
result = result + line
return result
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()