-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
executable file
·1649 lines (1318 loc) · 56.9 KB
/
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
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#---------------------------------------------------------------------------
# This script is used to run through the commands used for the various stages
# of building Phoenix, and can also be a front-end for building wxWidgets and
# the Python extension modules.
#---------------------------------------------------------------------------
from __future__ import absolute_import
import sys
import glob
import hashlib
import optparse
import os
import re
import shlex
import shutil
import subprocess
import tarfile
import tempfile
import datetime
if sys.version_info < (3,):
from urllib2 import urlopen
else:
from urllib.request import urlopen
from distutils.dep_util import newer, newer_group
from distutils.dir_util import copy_tree
from buildtools.config import Config, msg, opj, posixjoin, loadETG, etg2outfile, findCmd, \
phoenixDir, wxDir, copyIfNewer, copyFile, \
macFixDependencyInstallName, macSetLoaderNames, \
getSvnRev, runcmd, textfile_open, getSipFiles, \
getVisCVersion
import buildtools.version as version
# defaults
PYVER = '2.7'
PYSHORTVER = '27'
PYTHON = None # it will be set later
PYTHON_ARCH = 'UNKNOWN'
# wx version numbers
version2 = "%d.%d" % (version.VER_MAJOR, version.VER_MINOR)
version3 = "%d.%d.%d" % (version.VER_MAJOR, version.VER_MINOR, version.VER_RELEASE)
version2_nodot = version2.replace(".", "")
version3_nodot = version3.replace(".", "")
unstable_series = (version.VER_MINOR % 2) == 1 # is the minor version odd or even?
isWindows = sys.platform.startswith('win')
isDarwin = sys.platform == "darwin"
baseName = 'wxPython_Phoenix'
eggInfoName = baseName + '.egg-info'
# Some tools will be downloaded for the builds. These are the versions and
# MD5s of the tool binaries currently in use.
sipCurrentVersion = '4.14.4'
sipMD5 = {
'darwin' : 'dd8d1128fc43586072206038bfa35a66',
'win32' : '3edfb918fbddc19ac7a26b931addfeed',
'linux' : 'b9fa64b1f6f5a6407777a0dda0de5778',
}
wafCurrentVersion = '1.7.10'
wafMD5 = '6825d465baf2968c1d20a58dd65a0e9d'
doxygenCurrentVersion = '1.8.2'
doxygenMD5 = {
'darwin' : '96a3012d97893f4e05387cda544de0e8',
'win32' : '71f97ebaa87171c824a7742de5bf3381',
'linux' : '6fca3d2016f8019a7737716eee4d5377',
}
# And the location where they can be downloaded from
toolsURL = 'http://wxpython.org/Phoenix/tools'
#---------------------------------------------------------------------------
def usage():
print ("""\
Usage: ./build.py [command(s)] [options]
Commands:
N.N NN Major.Minor version number of the Python to use to run
the other commands. Default is 2.7. Or you can use
--python to specify the actual Python executable to use.
dox Run Doxygen to produce the XML file used by ETG scripts
doxhtml Run Doxygen to create the HTML documetation for wx
touch 'touch' the etg files so they will all get run the next
time the etg command is run.
etg Run the ETG scripts that are out of date to update their
SIP files and their Sphinx input files
sip Run sip to generate the C++ wrapper source
cffi_gen Run the cffi binding generator
wxlib Build the Sphinx input files for wx.lib
wxpy Build the Sphinx input files for wx.py
wxtools Build the Sphinx input files for wx.tools
sphinx Run the documentation building process using Sphinx
build Build both wxWidgets and wxPython
build_wx Do only the wxWidgets part of the build
build_py Build wxPython only
install Install both wxWidgets and wxPython
install_wx Install wxWidgets (but only if this tool was used to
build it)
install_py Install wxPython only
sdist Build a tarball containing all source files
bdist Create a binary tarball release of wxPython Phoenix
docs_bdist Build a tarball containing the documentation
bdist_egg Build a Python egg. Requires magic.
bdist_wheel Build a Python wheel. Requires magic.
test Run the unit test suite
test_* Run just the one named test module
clean_wx Clean the wx parts of the build
clean_py Clean the wxPython parts of the build
clean_sphinx Clean the sphinx files
clean Clean both wx and wxPython
cleanall Clean all and do a little extra scrubbing too
""")
parser = makeOptionParser()
parser.print_help()
def main(args):
setPythonVersion(args)
setDevModeOptions(args)
os.environ['PYTHONPATH'] = phoenixDir()
os.environ['PYTHONUNBUFFERED'] = 'yes'
os.environ['WXWIN'] = wxDir()
cfg = Config(noWxConfig=True)
msg('cfg.VERSION: %s' % cfg.VERSION)
msg('')
wxpydir = os.path.join(phoenixDir(), "wx")
if not os.path.exists(wxpydir):
os.makedirs(wxpydir)
if not args or 'help' in args or '--help' in args or '-h' in args:
usage()
sys.exit(1)
options, commands = parseArgs(args)
while commands:
# ensure that each command starts with the CWD being the phoenix dir.
os.chdir(phoenixDir())
cmd = commands.pop(0)
if not cmd:
continue # ignore empty command-line args (possible with the buildbot)
elif cmd.startswith('test_'):
testOne(cmd, options, args)
elif 'cmd_'+cmd in globals():
function = globals()['cmd_'+cmd]
function(options, args)
else:
print('*** Unknown command: ' + cmd)
usage()
sys.exit(1)
msg("Done!")
#---------------------------------------------------------------------------
# Helper functions (see also buildtools.config for more)
#---------------------------------------------------------------------------
def setPythonVersion(args):
global PYVER
global PYSHORTVER
global PYTHON
global PYTHON_ARCH
havePyVer = False
havePyPath = False
for idx, arg in enumerate(args):
if re.match(r'^[0-9]\.[0-9]$', arg):
havePyVer = True
PYVER = arg
PYSHORTVER = arg[0] + arg[2]
del args[idx]
break
if re.match(r'^[0-9][0-9]$', arg):
havePyVer = True
PYVER = '%s.%s' % (arg[0], arg[1])
PYSHORTVER = arg
del args[idx]
break
if arg.startswith('--python'):
havePyPath = True
if '=' in arg:
PYTHON = arg.split('=')[1]
del args[idx]
else:
PYTHON = args[idx+1]
del args[idx:idx+2]
PYVER = runcmd('"%s" -c "import sys; print(sys.version[:3])"' % PYTHON,
getOutput=True, echoCmd=False)
PYSHORTVER = PYVER[0] + PYVER[2]
break
if havePyVer:
if isWindows and os.environ.get('TOOLS'):
# Use $TOOLS to find the correct Python. It should be the install
# root of all Python's on the system, with the 64-bit ones in an
# amd64 subfolder, like this:
#
# $TOOLS\Python27\python.exe
# $TOOLS\Python33\python.exe
# $TOOLS\amd64\Python27\python.exe
# $TOOLS\amd64\Python33\python.exe
#
TOOLS = os.environ.get('TOOLS')
if 'cygdrive' in TOOLS:
TOOLS = runcmd('c:/cygwin/bin/cygpath -w '+TOOLS, True, False)
use64flag = '--x64' in args
if use64flag:
args.remove('--x64')
CPU = os.environ.get('CPU')
if use64flag or CPU in ['AMD64', 'X64', 'amd64', 'x64']:
TOOLS = posixjoin(TOOLS, 'amd64')
PYTHON = posixjoin(TOOLS,
'python%s' % PYSHORTVER,
'python.exe')
elif isWindows:
# Otherwise check if the invoking Python is the right version
if sys.version[:3] != PYVER:
msg('ERROR: The invoking Python is not the requested version. Perhaps you should use --python')
sys.exit(1)
PYTHON = sys.executable
PYVER = sys.version[:3]
PYSHORTVER = PYVER[0] + PYVER[2]
elif not isWindows:
# find a pythonX.Y on the PATH
PYTHON = runcmd("which python%s" % PYVER, True, False)
if not PYTHON:
# If no version or path were specified then default to the python
# that invoked this script
PYTHON = sys.executable
PYVER = sys.version[:3]
PYSHORTVER = PYVER[0] + PYVER[2]
PYTHON = os.path.abspath(PYTHON)
msg('Build using: "%s"' % PYTHON)
msg(runcmd('"%s" -c "import sys; print(sys.version)"' % PYTHON, True, False))
PYTHON_ARCH = runcmd('"%s" -c "import platform; print(platform.architecture()[0])"'
% PYTHON, True, False)
msg('Python\'s architecture is %s' % PYTHON_ARCH)
os.environ['PYTHON'] = PYTHON
if PYTHON_ARCH == '64bit':
# Make sure this is set in case it wasn't above.
os.environ['CPU'] = 'X64'
def setDevModeOptions(args):
# Using --dev is a shortcut for setting several build options that I use
# while working on the code in my local workspaces. Most people will
# probably not use this so it is not part for the documented options and
# is explicitly handled here before the options parser is created. If
# anybody besides Robin is using this option do not depend on the options
# it inserts into the args list being consistent. They could change at any
# update from the repository.
myDevModeOptions = [
#'--build_dir=../bld',
#'--prefix=/opt/wx/2.9',
'--jobs=6', # % numCPUs(),
# These will be ignored on the other platforms so it is okay to
# include them unconditionally
'--osx_cocoa',
'--mac_arch=x86_64',
#'--osx_carbon',
#'--mac_arch=i386',
#'--mac_arch=i386,x86_64',
]
if not isWindows:
myDevModeOptions.append('--debug')
if isWindows:
myDevModeOptions.append('--cairo')
if '--dev' in args:
idx = args.index('--dev')
# replace the --dev item with the items from the list
args[idx:idx+1] = myDevModeOptions
def numCPUs():
"""
Detects the number of CPUs on a system.
This approach is from detectCPUs here: http://www.artima.com/weblogs/viewpost.jsp?thread=230001
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
else: # OSX:
p = subprocess.Popen("sysctl -n hw.ncpu", shell=True, stdout=subprocess.PIPE)
return int(p.stdout.read())
# Windows:
if "NUMBER_OF_PROCESSORS" in os.environ:
ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
if ncpus > 0:
return ncpus
return 1 # Default
def getMSWSettings(options):
checkCompiler(quiet=True)
class MSWsettings(object):
pass
msw = MSWsettings()
msw.CPU = os.environ.get('CPU')
if msw.CPU in ['AMD64', 'X64'] or PYTHON_ARCH == '64bit':
msw.dllDir = posixjoin(wxDir(), "lib", "vc%s_x64_dll" % getVisCVersion())
else:
msw.dllDir = posixjoin(wxDir(), "lib", "vc%s_dll" % getVisCVersion())
msw.buildDir = posixjoin(wxDir(), "build", "msw")
msw.dll_type = "u"
if options.debug:
msw.dll_type = "ud"
return msw
def makeOptionParser():
OPTS = [
("python", ("", "The python executable to build for.")),
("debug", (False, "Build wxPython with debug symbols")),
("keep_hash_lines",(False, "Don't remove the '#line N' lines from the SIP generated code")),
("generator", ('sip', "The binding generator to use. Available "
"generators: sip, cffi")),
("osx_cocoa", (True, "Build the OSX Cocoa port on Mac (default)")),
("osx_carbon", (False, "Build the OSX Carbon port on Mac (unsupported)")),
("mac_framework", (False, "Build wxWidgets as a Mac framework.")),
("mac_arch", ("", "Comma separated list of architectures to build on Mac")),
("use_syswx", (False, "Try to use an installed wx rather than building the "
"one in this source tree. The wx-config in {prefix}/bin "
"or the first found on the PATH determines which wx is "
"used. Implies --no_magic.")),
("force_config", (False, "Run configure when building even if the script "
"determines it's not necessary.")),
("no_config", (False, "Turn off configure step on autoconf builds")),
("no_magic", (False, "Do NOT use the magic that will enable the wxWidgets "
"libraries to be bundled with wxPython. (Such as when "
"using an uninstalled wx/wxPython from the build dir, "
"or when distributing wxPython as an egg.) When using "
"this flag you should either build with an already "
"installed wxWidgets, or allow this script to build and "
"install wxWidgets.")),
("build_dir", ("", "Directory to store wx build files. (Not used on Windows)")),
("prefix", ("", "Prefix value to pass to the wx build.")),
("destdir", ("", "Installation root for wxWidgets, files will go to {destdir}/{prefix}")),
("extra_setup", ("", "Extra args to pass on setup.py's command line.")),
("extra_make", ("", "Extra args to pass on [n]make's command line.")),
("extra_waf", ("", "Extra args to pass on waf's command line.")),
("jobs", ("", "Number of parallel compile jobs to do, if supported.")),
("both", (False, "Build both a debug and release version. (Only used on Windows)")),
("unicode", (True, "Build wxPython with unicode support (always on for wx2.9+)")),
("verbose", (False, "Print out more information.")),
("nodoc", (False, "Do not run the default docs generator")),
("upload", (False, "Upload bdist and/or sdist packages to snapshot server.")),
("cairo", (False, "Allow Cairo use with wxGraphicsContext (Windows only)")),
("x64", (False, "Use and build for the 64bit version of Python on Windows")),
("jom", (False, "Use jom instead of nmake for the wxMSW build")),
]
parser = optparse.OptionParser("build options:")
for opt, info in OPTS:
default, txt = info
action = 'store'
if type(default) == bool:
action = 'store_true'
parser.add_option('--'+opt, default=default, action=action,
dest=opt, help=txt)
return parser
def parseArgs(args):
parser = makeOptionParser()
options, args = parser.parse_args(args)
if isWindows:
# We always use magic on Windows
options.no_magic = False
options.use_syswx = False
elif options.use_syswx:
options.no_magic = True
return options, args
class pushDir(object):
def __init__(self, newDir):
self.cwd = os.getcwd()
os.chdir(newDir)
def __del__(self):
# pop back to the original dir
os.chdir(self.cwd)
def getBuildDir(options):
BUILD_DIR = opj(phoenixDir(), 'build', 'wxbld')
if options.build_dir:
BUILD_DIR = os.path.abspath(options.build_dir)
return BUILD_DIR
def deleteIfExists(deldir, verbose=True):
if os.path.exists(deldir) and os.path.isdir(deldir):
try:
if verbose:
msg("Removing folder: %s" % deldir)
shutil.rmtree(deldir)
except Exception:
if verbose:
import traceback
msg("Error: %s" % traceback.format_exc(1))
def delFiles(fileList, verbose=True):
for afile in fileList:
if verbose:
print("Removing file: %s" % afile)
os.remove(afile)
def getTool(cmdName, version, MD5, envVar, platformBinary):
# Check in the bin dir for the specified version of the tool command. If
# it's not there then attempt to download it. Validity of the binary is
# checked with an MD5 hash.
if os.environ.get(envVar):
# Setting a a value in the environment overrides other options
return os.environ.get(envVar)
else:
if platformBinary:
platform = 'linux' if sys.platform.startswith('linux') else sys.platform
ext = ''
if platform == 'win32':
ext = '.exe'
if platform == 'linux' and PYTHON_ARCH == '32bit':
print('ERROR: 32 bit platform tools not available')
print(' Set %s in the environment to use a local build of %s instead' % (envVar, cmdName))
sys.exit(1)
cmd = opj(phoenixDir(), 'bin', '%s-%s-%s%s' % (cmdName, version, platform, ext))
md5 = MD5[platform]
else:
cmd = opj(phoenixDir(), 'bin', '%s-%s' % (cmdName, version))
md5 = MD5
msg('Checking for %s...' % cmd)
if os.path.exists(cmd):
m = hashlib.md5()
m.update(open(cmd, 'rb').read())
if m.hexdigest() != md5:
print('ERROR: MD5 mismatch, got "%s"' % m.hexdigest())
print(' expected "%s"' % md5)
print(' Set %s in the environment to use a local build of %s instead' % (envVar, cmdName))
sys.exit(1)
return cmd
msg('Not found. Attempting to download...')
url = '%s/%s.bz2' % (toolsURL, os.path.basename(cmd))
try:
connection = urlopen(url)
msg('Connection successful...')
data = connection.read()
msg('Data downloaded...')
except Exception:
print('ERROR: Unable to download ' + url)
print(' Set %s in the environment to use a local build of %s instead' % (envVar, cmdName))
import traceback
traceback.print_exc()
sys.exit(1)
import bz2
data = bz2.decompress(data)
with open(cmd, 'wb') as f:
f.write(data)
os.chmod(cmd, 0o755)
# Recursive call so the MD5 value will be double-checked on what was
# just downloaded
return getTool(cmdName, version, MD5, envVar, platformBinary)
# The download and MD5 check only needs to happen once per run, cache the sip
# cmd value here the first time through.
_sipCmd = None
def getSipCmd():
global _sipCmd
if _sipCmd is None:
_sipCmd = getTool('sip', sipCurrentVersion, sipMD5, 'SIP', True)
return _sipCmd
# Same thing for WAF
_wafCmd = None
def getWafCmd():
global _wafCmd
if _wafCmd is None:
_wafCmd = getTool('waf', wafCurrentVersion, wafMD5, 'WAF', False)
return _wafCmd
# and Doxygen
_doxCmd = None
def getDoxCmd():
global _doxCmd
if _doxCmd is None:
_doxCmd = getTool('doxygen', doxygenCurrentVersion, doxygenMD5, 'DOXYGEN', True)
return _doxCmd
class CommandTimer(object):
def __init__(self, name):
self.name = name
self.startTime = datetime.datetime.now()
msg('Running command: %s' % self.name)
def __del__(self):
delta = datetime.datetime.now() - self.startTime
time = ""
if delta.seconds / 60 > 0:
time = "%dm" % (delta.seconds / 60)
time += "%d.%ds" % (delta.seconds % 60, delta.microseconds / 1000)
msg('Finished command: %s (%s)' % (self.name, time))
def uploadPackage(fileName, KEEP=50):
"""
Upload the given filename to the configured package server location. Only
the KEEP most recent files will be kept so the server spece is not overly
consumed. It is assumed that if the files are in sorted order then the
end of the list will be the newest files.
"""
msg("Preparing to upload %s..." % fileName)
configfile = os.path.join(os.getenv("HOME"), "phoenix_package_server.cfg")
if not os.path.exists(configfile):
msg("ERROR: Can not upload, server configuration not set.")
return
import ConfigParser
parser = ConfigParser.ConfigParser()
parser.read(configfile)
msg("Connecting to FTP server...")
from ftplib import FTP
ftp = FTP(parser.get("FTP", "host"))
ftp.login(parser.get("FTP", "user"), parser.get("FTP", "pass"))
ftp_dir = parser.get("FTP", "dir")
ftp_path = '%s/%s' % (ftp_dir, os.path.basename(fileName))
msg("Uploading package (this may take some time)...")
f = open(fileName, 'rb')
ftp.storbinary('STOR %s' % ftp_path, f)
f.close()
allFiles = ftp.nlst(ftp_dir)
allFiles.sort() # <== if an alpha sort is not the correct order, pass a cmp function!
# leave the last KEEP builds, including this new one, on the server
for name in allFiles[:-KEEP]:
msg("Deleting %s" % name)
ftp.delete(name)
ftp.close()
msg("Upload complete!")
def checkCompiler(quiet=False):
if isWindows:
# Make sure that the compiler that Python wants to use can be found.
# It will terminate if the compiler is not found or other exceptions
# are raised.
cmd = "import distutils.msvc9compiler as msvc; " \
"mc = msvc.MSVCCompiler(); " \
"mc.initialize(); " \
"print(mc.cc)"
CC = runcmd('"%s" -c "%s"' % (PYTHON, cmd), getOutput=True, echoCmd=False)
if not quiet:
msg("MSVC: %s" % CC)
# Now get the environment variables which that compiler needs from
# its vcvarsall.bat command and load them into this process's
# environment.
cmd = "import distutils.msvc9compiler as msvc; " \
"arch = msvc.PLAT_TO_VCVARS[msvc.get_platform()]; " \
"env = msvc.query_vcvarsall(msvc.VERSION, arch); " \
"print(env)"
env = eval(runcmd('"%s" -c "%s"' % (PYTHON, cmd), getOutput=True, echoCmd=False))
os.environ['PATH'] = bytes(env['path'])
os.environ['INCLUDE'] = bytes(env['include'])
os.environ['LIB'] = bytes(env['lib'])
os.environ['LIBPATH'] = bytes(env['libpath'])
def getWafBuildBase():
base = posixjoin('build', 'waf', PYVER)
if isWindows:
if PYTHON_ARCH == '64bit':
base = posixjoin(base, 'x64')
else:
base = posixjoin(base, 'x86')
return base
#---------------------------------------------------------------------------
# Command functions and helpers
#---------------------------------------------------------------------------
def _doDox(arg):
doxCmd = getDoxCmd()
doxCmd = os.path.abspath(doxCmd)
if isWindows:
doxCmd = doxCmd.replace('\\', '/')
doxCmd = runcmd('c:/cygwin/bin/cygpath -u '+doxCmd, True, False)
os.environ['DOXYGEN'] = doxCmd
os.environ['WX_SKIP_DOXYGEN_VERSION_CHECK'] = '1'
d = posixjoin(wxDir(), 'docs/doxygen')
d = d.replace('\\', '/')
cmd = 'c:/cygwin/bin/bash.exe -l -c "cd %s && ./regen.sh %s"' % (d, arg)
else:
os.environ['DOXYGEN'] = doxCmd
os.environ['WX_SKIP_DOXYGEN_VERSION_CHECK'] = '1'
pwd = pushDir(posixjoin(wxDir(), 'docs/doxygen'))
cmd = './regen.sh %s' % arg
runcmd(cmd)
def cmd_dox(options, args):
cmdTimer = CommandTimer('dox')
_doDox('xml')
def cmd_doxhtml(options, args):
cmdTimer = CommandTimer('doxhtml')
_doDox('html')
_doDox('chm')
def cmd_etg(options, args):
cmdTimer = CommandTimer('etg')
cfg = Config()
assert os.path.exists(cfg.DOXY_XML_DIR), "Doxygen XML folder not found: " + cfg.DOXY_XML_DIR
pwd = pushDir(cfg.ROOT_DIR)
# TODO: Better support for selecting etg cmd-line flags...
flags = ''
if options.generator == 'sip':
flags = '--sip'
elif options.generator == 'cffi':
flags = '--cffi'
else:
raise Exception('Invalid generator selection')
if options.nodoc:
flags += ' --nodoc'
# get the files to run, moving _core the to the front of the list
etgfiles = glob.glob(opj('etg', '_*.py'))
core_file = opj('etg', '_core.py')
if core_file in etgfiles:
etgfiles.remove(core_file)
etgfiles.insert(0, core_file)
for script in etgfiles:
outfile = etg2outfile(options.generator, script)
deps = [script]
ns = loadETG(script)
if hasattr(ns, 'ETGFILES'):
etgfiles += ns.ETGFILES[1:] # all but itself
if hasattr(ns, 'DEPENDS'):
deps += ns.DEPENDS
if hasattr(ns, 'OTHERDEPS'):
deps += ns.OTHERDEPS
# run the script only if any dependencies are newer
if newer_group(deps, outfile):
runcmd('"%s" %s %s' % (PYTHON, script, flags))
def cmd_sphinx(options, args):
from sphinxtools.postprocess import SphinxIndexes, MakeHeadings, PostProcess, GenGallery
cmdTimer = CommandTimer('sphinx')
pwd = pushDir(phoenixDir())
sphinxDir = os.path.join(phoenixDir(), 'docs', 'sphinx')
if not os.path.isdir(sphinxDir):
raise Exception('Missing sphinx folder in the distribution')
textFiles = glob.glob(sphinxDir + '/*.txt')
if not textFiles:
raise Exception('No documentation files found. Please run "build.py touch etg" first')
# Copy the rst files into txt files
restDir = os.path.join(sphinxDir, 'rest_substitutions', 'overviews')
rstFiles = glob.glob(restDir + '/*.rst')
for rst in rstFiles:
rstName = os.path.split(rst)[1]
txt = os.path.join(sphinxDir, os.path.splitext(rstName)[0] + '.txt')
copyIfNewer(rst, txt)
SphinxIndexes(sphinxDir)
GenGallery()
todo = os.path.join(phoenixDir(), 'TODO.txt')
copyIfNewer(todo, sphinxDir)
txtFiles = glob.glob(os.path.join(phoenixDir(), 'docs', '*.txt'))
for txtFile in txtFiles:
copyIfNewer(txtFile, sphinxDir)
MakeHeadings()
pwd2 = pushDir(sphinxDir)
buildDir = os.path.join(sphinxDir, 'build')
htmlDir = os.path.join(phoenixDir(), 'docs', 'html')
runcmd('sphinx-build -b html -d %s/doctrees . %s' % (buildDir, htmlDir))
del pwd2
msg('Postprocesing sphinx output...')
PostProcess(htmlDir)
def cmd_wxlib(options, args):
from sphinxtools.modulehunter import ModuleHunter
cmdTimer = CommandTimer('wx.lib')
pwd = pushDir(phoenixDir())
libDir = os.path.join(phoenixDir(), 'wx', 'lib')
if not os.path.isdir(libDir):
raise Exception('Missing wx.lib folder in the distribution')
init_name = os.path.join(libDir, '__init__.py')
import_name = 'lib'
version = version3
ModuleHunter(init_name, import_name, version)
def cmd_wxpy(options, args):
from sphinxtools.modulehunter import ModuleHunter
cmdTimer = CommandTimer('wx.py')
pwd = pushDir(phoenixDir())
libDir = os.path.join(phoenixDir(), 'wx', 'py')
if not os.path.isdir(libDir):
raise Exception('Missing wx.py folder in the distribution')
init_name = os.path.join(libDir, '__init__.py')
import_name = 'py'
version = version3
ModuleHunter(init_name, import_name, version)
def cmd_wxtools(options, args):
from sphinxtools.modulehunter import ModuleHunter
cmdTimer = CommandTimer('wx.tools')
pwd = pushDir(phoenixDir())
libDir = os.path.join(phoenixDir(), 'wx', 'tools')
if not os.path.isdir(libDir):
raise Exception('Missing wx.tools folder in the distribution')
init_name = os.path.join(libDir, '__init__.py')
import_name = 'tools'
version = version3
ModuleHunter(init_name, import_name, version)
def cmd_docs_bdist(options, args):
cmdTimer = CommandTimer('docs_bdist')
pwd = pushDir(phoenixDir())
cfg = Config()
rootname = "%s-%s-docs" % (baseName, cfg.VERSION)
tarfilename = "dist/%s.tar.gz" % rootname
if not os.path.exists('dist'):
os.makedirs('dist')
if os.path.exists(tarfilename):
os.remove(tarfilename)
msg("Archiving Phoenix documentation...")
tarball = tarfile.open(name=tarfilename, mode="w:gz")
tarball.add('docs/html', os.path.join(rootname, 'docs/html'),
filter=lambda info: None if '.svn' in info.name else info)
tarball.close()
if options.upload:
uploadPackage(tarfilename)
msg('Documentation tarball built at %s' % tarfilename)
def cmd_sip(options, args):
cmdTimer = CommandTimer('sip')
cfg = Config()
pwd = pushDir(cfg.ROOT_DIR)
modules = glob.glob(opj(cfg.SIPGEN, '_*.sip'))
# move _core the to the front of the list
core_file = opj(cfg.SIPGEN, '_core.sip')
if core_file in modules:
modules.remove(core_file)
modules.insert(0, core_file)
for src_name in modules:
tmpdir = tempfile.mkdtemp()
tmpdir = tmpdir.replace('\\', '/')
src_name = src_name.replace('\\', '/')
base = os.path.basename(os.path.splitext(src_name)[0])
sbf = posixjoin(cfg.SIPOUT, base) + '.sbf'
pycode = base[1:] # remove the leading _
pycode = posixjoin(cfg.PKGDIR, pycode) + '.py'
# Check if any of the included files are newer than the .sbf file
# produced by the previous run of sip. If not then we don't need to
# run sip again.
etg = loadETG(posixjoin('etg', base + '.py'))
sipFiles = getSipFiles(etg.INCLUDES) + [opj(cfg.SIPGEN, base+'.sip')]
if not newer_group(sipFiles, sbf) and os.path.exists(pycode):
continue
pycode = '-X pycode'+base+':'+pycode
sip = getSipCmd()
cmd = '%s %s -c %s -b %s %s %s' % \
(sip, cfg.SIPOPTS, tmpdir, sbf, pycode, src_name)
runcmd(cmd)
def processSrc(src, keepHashLines=False):
with textfile_open(src, 'rt') as f:
srcTxt = f.read()
if keepHashLines:
# Either just fix the pathnames in the #line lines...
srcTxt = srcTxt.replace(tmpdir, cfg.SIPOUT)
else:
# ...or totally remove them by replacing those lines with ''
import re
srcTxt = re.sub(r'^#line.*\n', '', srcTxt, flags=re.MULTILINE)
return srcTxt
# Check each file in tmpdir to see if it is different than the same file
# in cfg.SIPOUT. If so then copy the new one to cfg.SIPOUT, otherwise
# ignore it.
for src in glob.glob(tmpdir + '/*'):
dest = opj(cfg.SIPOUT, os.path.basename(src))
if not os.path.exists(dest):
msg('%s is a new file, copying...' % os.path.basename(src))
srcTxt = processSrc(src, options.keep_hash_lines)
f = textfile_open(dest, 'wt')
f.write(srcTxt)
f.close()
continue
srcTxt = processSrc(src, options.keep_hash_lines)
with textfile_open(dest, 'rt') as f:
destTxt = f.read()
if srcTxt == destTxt:
pass
else:
msg('%s is changed, copying...' % os.path.basename(src))
f = textfile_open(dest, 'wt')
f.write(srcTxt)
f.close()
# Remove tmpdir and its contents
shutil.rmtree(tmpdir)
def cmd_cffi_gen(options, args):
from etgtools.cffi.bindgen import BindingGenerator, LiteralVerifyArg
cmdTimer = CommandTimer('cffi_gen')
cfg = Config()
pwd = pushDir(cfg.ROOT_DIR)
CFFI_DIR = opj(cfg.ROOT_DIR, 'cffi')
BUILD_DIR = getBuildDir(options)
if not isWindows:
WX_CONFIG = posixjoin(BUILD_DIR, 'wx-config')
if options.use_syswx:
wxcfg = posixjoin(options.prefix, 'bin', 'wx-config')
if options.prefix and os.path.exists(wxcfg):
WX_CONFIG = wxcfg
else:
WX_CONFIG = 'wx-config' # hope it is on the PATH
# TODO(amauryfa): have different libs for each module
libnames = 'core,base,net,adv,html,stc'
libs = runcmd(WX_CONFIG + ' --libs %s' % libnames, True, False)
cxxflags = runcmd(WX_CONFIG + ' --cxxflags', True, False)
if '-D__WXGTK__' in cxxflags:
cxxflags += ' ' + runcmd('pkg-config --cflags gtk+-2.0', True, False)
libs += ' ' + runcmd('pkg-config --libs gtk+-2.0', True, False)
libs = shlex.split(libs)
cxxflags = shlex.split(cxxflags)
else:
msw = getMSWSettings(options)
libs = ['-LIBPATH:' + msw.dllDir]
cxxflags = ['-I' + wxDir() + '/include',
'-I' + wxDir() + '/include/msvc',
'-DwxMSVC_VERSION_AUTO',
'-DWXUSINGDLL',
'-DwxSUFFIX=' + msw.dll_type,
'-D_CRT_SECURE_NO_WARNINGS',
'-wd 4800', #disable performance warning forcing int to bool
'-EHsc', # c++ exception handling
]
cxxflags.append('-I' + opj(CFFI_DIR, 'include'))
cxxflags.append('-I' + opj(CFFI_DIR, 'cpp_gen'))
cxxflags.append('-I' + opj(cfg.ROOT_DIR, 'src'))
cxxflags.append('-O0')
cxxflags.append('-g')
globalVerifyArgs = {'extra_compile_args': cxxflags,
'extra_link_args': libs,
}
DEF_DIR = os.path.join(CFFI_DIR, 'def_gen')
def_path_pattern = os.path.join(DEF_DIR, '%s.def')
def_glob = def_path_pattern % '_*'
gen = BindingGenerator(def_path_pattern)
# get the files to run, moving _core the to the front of the list
def_files = glob.glob(def_glob)
core_file = def_path_pattern % '_core'
if core_file in def_files:
def_files.remove(core_file)
def_files.insert(0, core_file)
for mod_path in def_files:
mod_name = os.path.basename(mod_path)[:-4]
print("Generate %s" % mod_name)
gen.generate(mod_name)
cppfilepath = opj(CFFI_DIR, 'cpp_gen', mod_name + '.cpp')
hfile = open(opj(CFFI_DIR, 'cpp_gen', mod_name + '.h'), 'w')
cppfile = open(cppfilepath, 'w')
pyfile = open(opj(CFFI_DIR, 'wx', mod_name + '.py'), 'w')
userpyfile = open(opj(CFFI_DIR, 'wx', mod_name.strip('_') + '.py'), 'w')
verify_args = dict(sources=[cppfilepath], **globalVerifyArgs)
print("Compile %s" % mod_name)
gen.write_files(mod_name, pyfile, userpyfile, cppfile, hfile,
verify_args)
# Copy src/__init__.py
copyFile(opj(cfg.ROOT_DIR, 'src', '__init__.py'),
opj(cfg.ROOT_DIR, 'cffi', 'wx', '__init__.py'))
# Write cffi/wx/__version__.py
with open(opj(cfg.ROOT_DIR, 'cffi', 'wx', '__version__.py'), 'w') as f:
f.write(
"# This file was generated by Phoenix's build.py script.\n\n"