forked from wxWidgets/Phoenix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
executable file
·1922 lines (1531 loc) · 66.3 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
#----------------------------------------------------------------------
# Name: build.py
# Purpose: Master build controller script.
# 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 wxPython distribution files.
#
# Author: Robin Dunn
#
# Created: 3-Dec-2010
# Copyright: (c) 2010-2016 by Total Control Software
# License: wxWindows License
#----------------------------------------------------------------------
from __future__ import absolute_import
import sys
import glob
import hashlib
import optparse
import os
import re
import shutil
import subprocess
import tarfile
import tempfile
import datetime
from distutils.dep_util import newer, newer_group
from buildtools.config import Config, msg, opj, posixjoin, loadETG, etg2sip, findCmd, \
phoenixDir, wxDir, copyIfNewer, copyFile, \
macSetLoaderNames, \
getVcsRev, runcmd, textfile_open, getSipFiles, \
getVisCVersion, getToolsPlatformName
import buildtools.version as version
# which version of Python is running this script
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
# defaults
PYVER = '2.7'
PYSHORTVER = '27'
PYTHON = None # it will be set later
PYTHON_ARCH = 'UNKNOWN'
# convenience access to the wxPython version digits
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(".", "")
# same for the wxWidgets version
wxversion2 = "%d.%d" % (version.wxVER_MAJOR, version.wxVER_MINOR)
wxversion3 = "%d.%d.%d" % (version.wxVER_MAJOR, version.wxVER_MINOR, version.wxVER_RELEASE)
wxversion2_nodot = wxversion2.replace(".", "")
wxversion3_nodot = wxversion3.replace(".", "")
unstable_series = (version.wxVER_MINOR % 2) == 1 # is the minor version odd or even?
isWindows = sys.platform.startswith('win')
isDarwin = sys.platform == "darwin"
devMode = False
baseName = version.PROJECT_NAME
eggInfoName = baseName + '.egg-info'
defaultMask='%s-%s*' % (baseName, version.VER_MAJOR)
pyICON = 'docs/sphinx/_static/images/sphinxdocs/phoenix_title.png'
wxICON = 'docs/sphinx/_static/images/sphinxdocs/mondrian.png'
# Some tools will be downloaded for the builds. These are the versions and
# MD5s of the tool binaries currently in use.
sipCurrentVersion = '4.19.2'
sipMD5 = {
'darwin' : '9a1ba6447b05926f8ff58a602bd156ba',
'win32' : 'e358f96f1e10649a62e3657fc599cbb6',
'linux32' : 'd9909d1c12ae758f68c025b644257e20',
'linux64' : '8dc9cd737f9f0a7c1538c0c85ce7120e',
}
wafCurrentVersion = '1.7.15-p1'
wafMD5 = 'e44003373c965f4221bbdc4c9b846128'
doxygenCurrentVersion = '1.8.8'
doxygenMD5 = {
'darwin' : '71c590e6cab47100f23919a2696cc7fd',
'win32' : 'a3dcff227458e423c132f16f57e26510',
'linux' : '083b3d8f614b538696041c7364e0f334',
}
# And the location where they can be downloaded from
toolsURL = 'https://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 documentation 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
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
docset Build Dash or Zeal compatible docsets
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
sdist_demo Build a tarball containing just the demo and samples folders
bdist Create a binary tarball release of wxPython Phoenix
bdist_docs 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()
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)
cfg = Config(noWxConfig=True)
msg('cfg.VERSION: %s' % cfg.VERSION)
msg('')
# For collecting test names or files, to be run after all have been pulled
# off the command line
test_names = []
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_'):
test_names.append('unittests/%s.py' % cmd)
elif cmd.startswith('unittests/test_'):
test_names.append(cmd)
elif 'cmd_'+cmd in globals():
function = globals()['cmd_'+cmd]
function(options, args)
else:
print('*** Unknown command: ' + cmd)
usage()
sys.exit(1)
# Now run the collected tests names, if any
if test_names:
cmd_test(options, args, test_names)
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([PYTHON, '-c', 'import sys; print(sys.version[:3])'],
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. If set then 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(getCygwinPath()+'/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('Will build using: "%s"' % PYTHON)
msg(runcmd([PYTHON, '-c', 'import sys; print(sys.version)'], True, False))
PYTHON_ARCH = runcmd(
[PYTHON, '-c', 'import platform; print(platform.architecture()[0])'],
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:
global devMode
devMode = True
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")),
("relwithdebug", (False, "Turn on the generation of debug info for release builds on MSW.")),
("release", (False, "Turn off some development options for a release build.")),
("keep_hash_lines",(False, "Don't remove the '#line N' lines from the SIP generated code")),
("gtk3", (False, "On Linux build for gtk3 (default gtk2)")),
("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 independently of wxPython.")),
("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.")),
("extra_pytest", ("", "Extra args to pass on py.test's command line.")),
(("j","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+)")),
(("v", "verbose"), (False, "Print out more information during the build.")),
("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")),
("pytest_timeout", ("0", "Timeout, in seconds, for stopping stuck test cases. (Currently not working as expected, so disabled by default.)")),
("pytest_jobs", ("", "Number of parallel processes py.test should run")),
("vagrant_vms", ("all", "Comma separated list of VM names to use for the build_vagrant command. Defaults to \"all\"")),
]
parser = optparse.OptionParser("build options:")
for opt, info in OPTS:
default, txt = info
action = 'store'
if type(default) == bool:
action = 'store_true'
if isinstance(opt, str):
opts = ('--'+opt, )
dest = opt
else:
opts = ('-'+opt[0], '--'+opt[1])
dest = opt[1]
parser.add_option(*opts, default=default, action=action,
dest=dest, 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:
# Turn off magic if using the system wx
options.no_magic = True
# Some options don't make sense for release builds
if options.release:
options.debug = False
options.both = False
if os.path.exists('REV.txt'):
os.unlink('REV.txt')
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, linuxBits=False):
# 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 value in the environment overrides other options
return os.environ.get(envVar)
else:
# setup
if platformBinary:
platform = getToolsPlatformName(linuxBits)
ext = ''
if platform == 'win32':
ext = '.exe'
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
def _error_msg(txt):
msg('ERROR: ' + txt)
msg(' Set %s in the environment to use a local build of %s instead' % (envVar, cmdName))
msg('Checking for %s...' % cmd)
if os.path.exists(cmd):
# if the file exists run some verification checks on it
# first make sure it is a normal file
if not os.path.isfile(cmd):
_error_msg('%s exists but is not a regular file.' % cmd)
sys.exit(1)
# now check the MD5 if not in dev mode and it's set to None
if not (devMode and md5 is None):
m = hashlib.md5()
m.update(open(cmd, 'rb').read())
if m.hexdigest() != md5:
_error_msg('MD5 mismatch, got "%s"\n '
'expected "%s"' % (m.hexdigest(), md5))
sys.exit(1)
# If the cmd is a script run by some interpreter, or similar,
# then we don't need to check anything else
if not platformBinary:
return cmd
# Ensure that commands that are platform binaries are executable
if not os.access(cmd, os.R_OK | os.X_OK):
_error_msg('Cannot execute %s due to permissions error' % cmd)
sys.exit(1)
try:
p = subprocess.Popen([cmd, '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
p.wait()
except OSError as e:
_error_msg('Could not execute %s, got "%s"' % (cmd, e))
sys.exit(1)
# if we get this far then all is well, the cmd is good to go
return cmd
msg('Not found. Attempting to download...')
url = '%s/%s.bz2' % (toolsURL, os.path.basename(cmd))
try:
import requests
resp = requests.get(url)
resp.raise_for_status()
msg('Connection successful...')
data = resp.content
msg('Data downloaded...')
except Exception:
_error_msg('Unable to download ' + url)
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, linuxBits)
# 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, 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, options, mask=defaultMask, keep=50):
"""
Upload the given filename to the configured package server location. Only
the `keep` most recent files matching `mask` will be kept so the server
space 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.
"""
fileName = fileName.replace('\\', '/')
msg("Uploading %s..." % fileName)
# NOTE: It is expected that there will be a host entry defined in
# ~/.ssh/config named wxpython-rbot, with the proper host, user, identity
# file, etc. needed for making an SSH connection to the snapshots server.
# Release builds work similarly with their own host configuration defined
# in the ~/.ssh/config file.
if options.release:
host = 'wxpython-release'
uploadDir = 'release-builds'
else:
host = 'wxpython-rbot'
uploadDir = 'snapshot-builds'
# copy the new file to the server
cmd = 'scp {} {}:{}'.format(fileName, host, uploadDir)
runcmd(cmd)
# Make sure it is readable by all
cmd = 'ssh {} "cd {}; chmod a+r {}"'.format(host, uploadDir, os.path.basename(fileName))
runcmd(cmd)
if not options.release:
# get the list of all snapshot files on the server
cmd = 'ssh {} "cd {}; ls {}"'.format(host, uploadDir, mask)
allFiles = runcmd(cmd, getOutput=True)
allFiles = allFiles.strip().split('\n')
allFiles.sort()
# Leave the last keep number of builds, including this new one, on the server.
# Delete the rest.
rmFiles = allFiles[:-keep]
if rmFiles:
msg("Deleting %s" % ", ".join(rmFiles))
cmd = 'ssh {} "cd {}; rm {}"'.format(host, uploadDir, " ".join(rmFiles))
runcmd(cmd)
msg("Upload complete!")
def uploadTree(srcPath, destPath, options, keep=30):
"""
Similar to the above but uploads a tree of files.
"""
msg("Uploading tree at {}...".format(srcPath))
if options.release:
host = 'wxpython-release'
uploadDir = opj('release-builds', destPath)
else:
host = 'wxpython-rbot'
uploadDir = opj('snapshot-builds', destPath)
# Ensure the destination exists
cmd = 'ssh {0} "if [ ! -d {1} ]; then mkdir -p {1}; fi"'.format(host, uploadDir)
runcmd(cmd)
# Upload the tree
cmd = 'scp -r {} {}:{}'.format(srcPath, host, uploadDir)
runcmd(cmd)
# Make sure it is readable by all
cmd = 'ssh {} "chmod -R a+r {}"'.format(host, uploadDir)
runcmd(cmd)
if not options.release:
# Remove files that were last modified more than `keep` days ago
msg("Cleaning up old builds.")
cmd = 'ssh {} "find {} -type f -mtime +{} -delete"'.format(host, uploadDir, keep)
runcmd(cmd)
msg("Tree upload and cleanup 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))
def _b(v):
return str(v)
#if PY2:
# return bytes(v)
#else:
# return bytes(v, 'utf8')
os.environ['PATH'] = _b(env['path'])
os.environ['INCLUDE'] = _b(env['include'])
os.environ['LIB'] = _b(env['lib'])
os.environ['LIBPATH'] = _b(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
def getCygwinPath():
"""
Try to locate the path where cygwin is installed.
If CYGWIN_BASE is set in the environment then use that. Otherwise look in
default install locations.
"""
if os.environ.get('CYGWIN_BASE'):
return os.environ.get('CYGWIN_BASE')
for path in ['c:/cygwin', 'c:/cygwin64']:
if os.path.isdir(path):
return path
return None
#---------------------------------------------------------------------------
# Command functions and helpers
#---------------------------------------------------------------------------
def _doDox(arg):
doxCmd = getDoxCmd()
doxCmd = os.path.abspath(doxCmd)
if isWindows:
cygwin_path = getCygwinPath()
doxCmd = doxCmd.replace('\\', '/')
doxCmd = runcmd(cygwin_path+'/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 = '%s/bin/bash.exe -l -c "cd %s && ./regen.sh %s"' % (cygwin_path, d, arg)
else:
os.environ['DOXYGEN'] = doxCmd
os.environ['WX_SKIP_DOXYGEN_VERSION_CHECK'] = '1'
pwd = pushDir(posixjoin(wxDir(), 'docs/doxygen'))
cmd = 'bash ./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')
# NOTE: Because of the use of defaults and plutil the following docset
# commands will only work correctly on OSX.
def cmd_docset_wx(options, args):
cmdTimer = CommandTimer('docset_wx')
cfg = Config()
# Use Doxygen to generate the docset
_doDox('docset')
# Remove any existing docset in the dist dir and move the new docset in
srcname = posixjoin(wxDir(), 'docs/doxygen/out/docset',
'wxWidgets-%s.docset' % wxversion2)
destname = 'dist/wxWidgets-%s.docset' % wxversion3
if not os.path.isdir(srcname):
msg('ERROR: %s not found' % srcname)
sys.exit(1)
if os.path.isdir(destname):
shutil.rmtree(destname)
shutil.move(srcname, destname)
shutil.copyfile(wxICON, posixjoin(destname, 'icon.png'))
runcmd('plutil -convert xml1 {}/Contents/Info.plist'.format(destname))
def cmd_docset_py(options, args):
cmdTimer = CommandTimer('docset_py')
if not os.path.isdir('docs/html'):
msg('ERROR: No docs/html, has the sphinx build command been run?')
sys.exit(1)
# clear out any old docset build
name = 'wxPython-{}'.format(version3)
docset = posixjoin('dist', '{}.docset'.format(name))
if os.path.isdir(docset):
shutil.rmtree(docset)
# run the docset generator
VERBOSE = '--verbose' if options.verbose else ''
runcmd('doc2dash {} --name "{}" --icon {} --destination dist docs/html'
.format(VERBOSE, name, pyICON))
# update its Info.plist file
docset = os.path.abspath(docset)
runcmd('defaults write {}/Contents/Info isJavaScriptEnabled true'.format(docset))
runcmd('defaults write {}/Contents/Info dashIndexFilePath main.html'.format(docset))
runcmd('defaults write {}/Contents/Info DocSetPlatformFamily wxpy'.format(docset))
runcmd('plutil -convert xml1 {}/Contents/Info.plist'.format(docset))
def cmd_docset(options, args):
cmd_docset_wx(options, args)
cmd_docset_py(options, args)
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 = '--sip'
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:
sipfile = etg2sip(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, sipfile):
runcmd('"%s" %s %s' % (PYTHON, script, flags))
def cmd_sphinx(options, args):
from sphinxtools.postprocess import genIndexes, 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)
genIndexes(sphinxDir)
genGallery()
# Copy the hand-edited top level doc files too
rstFiles = [os.path.join(phoenixDir(), 'TODO.rst')] + \
glob.glob(os.path.join(phoenixDir(), 'docs', '*.rst'))
for rst in rstFiles:
txt = os.path.join(sphinxDir, os.path.splitext(os.path.basename(rst))[0] + '.txt')
copyIfNewer(rst, txt)
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('Postprocessing sphinx output...')
postProcess(htmlDir, options)
def cmd_wxlib(options, args):
from sphinxtools.modulehunter import ModuleHunter
cmdTimer = CommandTimer('wx.lib')
pwd = pushDir(phoenixDir())
for wx_pkg in ['lib', 'py', 'tools']:
libDir = os.path.join(phoenixDir(), 'wx', wx_pkg)
if not os.path.isdir(libDir):
raise Exception('Missing wx.{} folder in the distribution'.format(wx_pkg))
init_name = os.path.join(libDir, '__init__.py')
import_name = 'wx.{}'.format(wx_pkg)
ModuleHunter(init_name, import_name, version3)
def cmd_wxpy(options, args):
msg('Command wxpy has been folded into command wxlib.')
def cmd_wxtools(options, args):
msg('Command wxtools has been folded into command wxlib.')
def cmd_bdist_docs(options, args):
cmdTimer = CommandTimer('bdist_docs')
pwd = pushDir(phoenixDir())
cfg = Config()
msg("Archiving wxPython Phoenix documentation...")
rootname = "%s-docs-%s" % (baseName, cfg.VERSION)