-
Notifications
You must be signed in to change notification settings - Fork 517
/
build.py
executable file
·2419 lines (1957 loc) · 86.1 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-2020 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
import shlex
import textwrap
import warnings
try:
import pathlib
except ImportError:
import buildtools.backports.pathlib2 as pathlib
try:
from shutil import which
except ImportError:
from buildtools.backports.shutil_which import which
try:
from setuptools.modified import newer, newer_group
except ImportError:
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, updateLicenseFiles, \
TemporaryDirectory, getMSVCInfo, generateVersionFiles
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 = 'packaging/docset/Vippi-blocks-icon-32.png'
wxICON = 'packaging/docset/mondrian.png'
# Some tools will be downloaded for the builds. These are the versions and
# MD5s of the tool binaries currently in use.
wafCurrentVersion = '2.1.2'
wafMD5 = '8ff717c068819e488a337030ec8abf6c'
doxygenCurrentVersion = '1.8.8'
doxygenMD5 = {
'darwin' : '71c590e6cab47100f23919a2696cc7fd',
'win32' : 'a3dcff227458e423c132f16f57e26510',
'linux' : '083b3d8f614b538696041c7364e0f334',
}
# And the location where they can be downloaded from
toolsURL = 'https://wxwidgets.github.io/wxPython-tools'
# MS Edge code and DLLs needed for the wxWEBVIEW_BACKEND_EDGE backend
MS_edge_version = '1.0.1185.39'
MS_edge_url = 'https://www.nuget.org/api/v2/package/Microsoft.Web.WebView2/{}'.format(MS_edge_version)
#---------------------------------------------------------------------------
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
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):
setDevModeOptions(args)
options, commands = parseArgs(args)
setPythonVersion(args)
os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', '') + os.pathsep + phoenixDir()
os.environ['PYTHONUNBUFFERED'] = 'yes'
os.environ['WXWIN'] = wxDir()
# Ensure that PYTHON's containing folder is on the PATH. Normally it will
# already be there, and probably at the beginning. But if this script was
# invoked with a venv Python without activating the venv (like we do on the
# BuildBot) then it may not be in the PATH at all.
os.environ['PATH'] += os.pathsep + os.path.dirname(PYTHON)
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)
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][0-9]?$', arg):
havePyVer = True
PYVER = arg
PYSHORTVER = arg[0] + arg[2:]
del args[idx]
break
if re.match(r'^[0-9][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 = bash2dosPath(TOOLS)
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 = '{}.{}'.format(sys.version_info.major, sys.version_info.minor)
PYSHORTVER = '{}{}'.format(sys.version_info.major, sys.version_info.minor)
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={}'.format(max(2, int(numCPUs()/2))),
# These will be ignored on the other platforms so it is okay to
# include them unconditionally
'--osx_cocoa',
'--mac_arch=arm64,x86_64',
'--no_allmo',
]
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")),
("gtk2", (False, "On Linux build for gtk2 (default gtk3)")),
("gtk3", (True, "On Linux build for gtk3")),
("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")),
("docker_img", ("all", "Comma separated list of image tags to use for the build_docker command. Defaults to \"all\"")),
("dump_waf_log", (False, "If the waf build tool fails then using this option will cause waf's configure log to be printed")),
("regenerate_sysconfig", (False, "Waf uses Python's sysconfig and related tools to configure the build. In some cases that info can be incorrect, so this option regenerates it. Must have write access to Python's lib folder.")),
("no_allmo", (False, "Skip regenerating the wxWidgets message catalogs")),
("no_msedge", (False, "Do not include the MS Edge backend for wx.html2.WebView. (Windows only)")),
("quiet", (False, "Silence some of the messages from build.py"))
]
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):
# If WXPYTHON_BUILD_ARGS is set in the environment, split it and add to args
if os.environ.get('WXPYTHON_BUILD_ARGS', None):
args += shlex.split(os.environ.get('WXPYTHON_BUILD_ARGS'))
# Parse the args into options
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')
if options.gtk2:
options.gtk3 = False
if options.quiet:
import buildtools.config
buildtools.config.runSilently = 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):
if not isDarwin and not isWindows:
BUILD_DIR = opj(phoenixDir(), 'build', 'wxbld', 'gtk3' if options.gtk3 else 'gtk2')
else:
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))
else:
if verbose:
msg("Unable to delete: '%s' (it doesn't exist or is not a folder)" % deldir)
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()
with open(cmd, 'rb') as fid:
m.update(fid.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.communicate()
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.
_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
def getMSWebView2():
fname = '{}.zip'.format(MS_edge_version)
dest = opj(wxDir(), '3rdparty', 'webview2')
if not os.path.exists(dest) or not os.path.exists(opj(dest, fname)):
if os.path.exists(dest):
shutil.rmtree(dest)
os.makedirs(dest)
msg('Downloading microsoft.web.webview2 {}...'.format(MS_edge_version))
try:
import requests
resp = requests.get(MS_edge_url)
resp.raise_for_status()
msg('Connection successful...')
data = resp.content
msg('Data downloaded...')
except Exception:
import traceback
traceback.print_exc()
sys.exit(1)
# Write the downloaded data to a local file
with open(opj(dest, fname), 'wb') as f:
f.write(data)
# Unzip it
from zipfile import ZipFile
with ZipFile(opj(dest, fname)) as zip:
zip.extractall(dest)
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=75):
"""
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 = os.path.relpath(fileName)
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, and writable by rbot
cmd = 'ssh {} "cd {}; chmod 644 {}"'.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, days=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 `days` days ago
msg("Cleaning up old builds.")
cmd = 'ssh {} "find {} -type f -mtime +{} -delete"'.format(host, uploadDir, days)
runcmd(cmd)
msg("Tree upload and cleanup complete!")
def checkCompiler(quiet=False):
if isWindows:
# Set up the PATH and other environment variables so the proper version
# of MSVC will be used. The setuptools package is used to find the
# needed info, so the target python shoudl have a recent version of
# setuptools installed.
arch = 'x64' if PYTHON_ARCH == '64bit' else 'x86'
info = getMSVCInfo(PYTHON, arch, set_env=True)
# # Just needed for debugging
# if not quiet:
# msg('MSVCinfo:')
# msg(f' vc_ver: {info.vc_ver}')
# msg(f' vs_ver: {info.vs_ver}')
# msg(f' arch: {info.arch}')
# msg(f' include: {info.include}')
# msg(f' lib: {info.lib}')
# msg(f' libpath: {info.libpath}')
# Make sure there is now a cl.exe on the PATH
CL = 'NOT FOUND'
for d in os.environ['PATH'].split(os.pathsep):
p = pathlib.Path(d, 'cl.exe')
if p.exists():
CL = p
break
if not quiet:
msg(f' CL.exe: {CL}')
# # Just needed for debugging
# for d in info.include.split(os.pathsep):
# p = pathlib.Path(d, 'tchar.h')
# if p.exists():
# msg(f' tchar.h: {p}')
# break
# else:
# msg('**** tchar.h NOT FOUND!')
# NOTE: SIP is now generating code with scoped-enums. Older linux
# platforms like what we're using for builds, and also TravisCI for
# example, are using GCC versions that are still defaulting to C++98,
# so this flag is needed to turn on the C++11 mode. If this flag
# causes problems with other non-Windows, non-Darwin compilers then
# we'll need to make this a little smarter about what flag (if any)
# needs to be used.
#
# NOTE 2: SIP changed its output such that this doesn't appear to be
# needed anymore, but we'll leave the code in place to make it easy to
# turn it back on again if/when needed.
if False and not isWindows and not isDarwin:
stdflag = '-std=c++11'
curflags = os.environ.get('CXXFLAGS', '')
if stdflag not in curflags:
os.environ['CXXFLAGS'] = '{} {}'.format(stdflag, curflags)
#print('**** Using CXXFLAGS:', os.environ.get('CXXFLAGS', ''))
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 getBashPath():
"""Check if there is a bash.exe on the PATH"""
bash = which('bash.exe')
return bash
def dos2bashPath(path):
"""
Convert an absolute dos-style path to one bash.exe can understand.
"""
path = path.replace('\\', '/')
cygpath = which('cygpath')
wsl = which('wsl')
# If we have cygwin then we can use cygpath to convert the path.
# Note that MSYS2 (and Git Bash) now also have cygpath so this should
# work there too.
if cygpath:
path = runcmd('"{}" -u "{}"'.format(cygpath, path), getOutput=True, echoCmd=False)
return path
elif wsl:
# Are we using Windows System for Linux? (untested)
path = runcmd('"{}" wslpath -a -u "{}"'.format(wsl, path), getOutput=True, echoCmd=False)
return path
else:
# Otherwise, do a simple translate and hope for the best?
# c:/foo --> /c/foo
# TODO: Check this!!
drive, rest = os.path.splitdrive(path)
path = '/{}/{}'.format(drive[0], rest)
return path
def bash2dosPath(path):
"""
Convert an absolute unix-style path to one Windows can understand.
"""
cygpath = which('cygpath')
wsl = which('wsl')
# If we have cygwin then we can use cygpath to convert the path.
# Note that MSYS2 (and Git Bash) now also have cygpath so this should
# work there too.
if cygpath:
path = runcmd('"{}" -w "{}"'.format(cygpath, path), getOutput=True, echoCmd=False)
return path
elif wsl:
# Are we using Windows System for Linux? (untested)
path = runcmd('"{}" wslpath -a -w "{}"'.format(wsl, path), getOutput=True, echoCmd=False)
return path
else:
# Otherwise, do a simple translate and hope for the best?
# /c/foo --> c:/foo
# There's also paths like /cygdrive/c/foo or /mnt/c/foo, but in those
# cases cygpath or wsl should be available.
components = path.split('/')
assert components[0] == '' and len(components[1]) == 1, "Expecting a path like /c/foo"
path = components[1] + ':/' + '/'.join(components[2:])
return path
def do_regenerate_sysconfig():
"""
If a Python environment has been relocated to a new folder then it's
possible that the sysconfig can still be using paths for the original
location. Since wxPython's build uses WAF, which uses the sysconfig (via
python-config, distutils.sysconfig, etc.) then we need to ensure that these
paths match the current environment.
TODO: Can this be done in a way that doesn't require overwriting a file in
the environment?
"""
with TemporaryDirectory() as td:
pwd = pushDir(td)
# generate a new sysconfig data file
cmd = [PYTHON, '-m', 'sysconfig', '--generate-posix-vars']
runcmd(cmd)
# On success the new data module will have been written to a subfolder
# of the current folder, which is recorded in ./pybuilddir.txt
with open('pybuilddir.txt', 'r') as fp:
pybd = fp.read()
# grab the file in that folder and copy it into the Python lib
p = opj(td, pybd, '*')
datafile = glob.glob(opj(td, pybd, '*'))[0]
cmd = [PYTHON, '-c', 'import sysconfig; print(sysconfig.get_path("stdlib"))']
stdlib = runcmd(cmd, getOutput=True)
shutil.copy(datafile, stdlib)
del pwd
def _setTarItemPerms(tarinfo):
"""
Used to set permissions of the files and fodlers in the source tarball
"""
if tarinfo.isdir():
tarinfo.mode = 0o755
else:
tarinfo.mode |= 0o644
return tarinfo
#---------------------------------------------------------------------------
# Command functions and helpers
#---------------------------------------------------------------------------
def _doDox(arg):
doxCmd = getDoxCmd()
doxCmd = os.path.abspath(doxCmd)
if isWindows:
bash = getBashPath()
if not bash:
raise RuntimeError("ERROR: Unable to find bash.exe, needed for running regen.sh")
doxCmd = dos2bashPath(doxCmd)
print(doxCmd)
os.environ['DOXYGEN'] = doxCmd
os.environ['WX_SKIP_DOXYGEN_VERSION_CHECK'] = '1'
d = posixjoin(wxDir(), 'docs/doxygen')
d = d.replace('\\', '/')
cmd = '"{}" -l -c "cd {} && ./regen.sh {}"'.format(bash, 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')