Debian Codegraph @

cpython27/Mac/BuildScript/build-installer.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """
3 This script is used to build "official" universal installers on macOS.
4
5 NEW for 3.6.8 / 2.7.16:
6 - also build and use Tk 8.6 for 10.6+ installers
7 NEW for 3.6.5:
8 - support Intel 64-bit-only () and 32-bit-only installer builds
9 - build and link with private Tcl/Tk 8.6 for 10.9+ builds
10 - deprecate use of explicit SDK (--sdk-path=) since all but the oldest
11 versions of Xcode support implicit setting of an SDK via environment
12 variables (SDKROOT and friends, see the xcrun man page for more info).
13 The SDK stuff was primarily needed for building universal installers
14 for 10.4; so as of 3.6.5, building installers for 10.4 is no longer
15 supported with build-installer.
16 - use generic "gcc" as compiler (CC env var) rather than "gcc-4.2"
17
18 Please ensure that this script keeps working with Python 2.5, to avoid
19 bootstrap issues (/usr/bin/python is Python 2.5 on OSX 10.5). Doc builds
20 use current versions of Sphinx and require a reasonably current python3.
21 Sphinx and dependencies are installed into a venv using the python3's pip
22 so will fetch them from PyPI if necessary. Since python3 is now used for
23 Sphinx, build-installer.py should also be converted to use python3!
24
25 For 10.6 or greater deployment targets, build-installer builds and links
26 with its own copy of Tcl/Tk 8.6 and the rest of this paragraph does not
27 apply. Otherwise, build-installer requires an installed third-party version
28 of Tcl/Tk 8.4 (for OS X 10.4 and 10.5 deployment targets) installed in
29 /Library/Frameworks. For 10.4 or 10.5, the Python built by this script
30 when installed will attempt to dynamically link first to Tcl and Tk frameworks
31 in /Library/Frameworks if available otherwise fall back to the ones in
32 /System/Library/Framework. For 10.4 or 10.5, we recommend
33 installing the most recent ActiveTcl 8.5 or 8.4 version, depending
34 on the deployment target. The actual version linked to depends on the
35 path of /Library/Frameworks/{Tcl,Tk}.framework/Versions/Current.
36
37 Usage: see USAGE variable in the script.
38 """
39 import platform, os, sys, getopt, textwrap, shutil, stat, time, pwd, grp
40 try:
41 import urllib2 as urllib_request
42 except ImportError:
43 import urllib.request as urllib_request
44
45 STAT_0o755 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
46 | stat.S_IRGRP | stat.S_IXGRP
47 | stat.S_IROTH | stat.S_IXOTH )
48
49 STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
50 | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
51 | stat.S_IROTH | stat.S_IXOTH )
52
53 INCLUDE_TIMESTAMP = 1
54 VERBOSE = 1
55
56 from plistlib import Plist
57
58 try:
59 from plistlib import writePlist
60 except ImportError:
61 # We're run using python2.3
62 def writePlist(plist, path):
63 plist.write(path)
64
65 def shellQuote(value):
66 """
67 Return the string value in a form that can safely be inserted into
68 a shell command.
69 """
70 return "'%s'"%(value.replace("'", "'\"'\"'"))
71
72 def grepValue(fn, variable):
73 """
74 Return the unquoted value of a variable from a file..
75 QUOTED_VALUE='quotes' -> str('quotes')
76 UNQUOTED_VALUE=noquotes -> str('noquotes')
77 """
78 variable = variable + '='
79 for ln in open(fn, 'r'):
80 if ln.startswith(variable):
81 value = ln[len(variable):].strip()
82 return value.strip("\"'")
83 raise RuntimeError("Cannot find variable %s" % variable[:-1])
84
85 _cache_getVersion = None
86
87 def getVersion():
88 global _cache_getVersion
89 if _cache_getVersion is None:
90 _cache_getVersion = grepValue(
91 os.path.join(SRCDIR, 'configure'), 'PACKAGE_VERSION')
92 return _cache_getVersion
93
94 def getVersionMajorMinor():
95 return tuple([int(n) for n in getVersion().split('.', 2)])
96
97 _cache_getFullVersion = None
98
99 def getFullVersion():
100 global _cache_getFullVersion
101 if _cache_getFullVersion is not None:
102 return _cache_getFullVersion
103 fn = os.path.join(SRCDIR, 'Include', 'patchlevel.h')
104 for ln in open(fn):
105 if 'PY_VERSION' in ln:
106 _cache_getFullVersion = ln.split()[-1][1:-1]
107 return _cache_getFullVersion
108 raise RuntimeError("Cannot find full version??")
109
110 FW_PREFIX = ["Library", "Frameworks", "Python.framework"]
111 FW_VERSION_PREFIX = "--undefined--" # initialized in parseOptions
112 FW_SSL_DIRECTORY = "--undefined--" # initialized in parseOptions
113
114 # The directory we'll use to create the build (will be erased and recreated)
115 WORKDIR = "/tmp/_py"
116
117 # The directory we'll use to store third-party sources. Set this to something
118 # else if you don't want to re-fetch required libraries every time.
119 DEPSRC = os.path.join(WORKDIR, 'third-party')
120 DEPSRC = os.path.expanduser('~/Universal/other-sources')
121
122 universal_opts_map = { '32-bit': ('i386', 'ppc',),
123 '64-bit': ('x86_64', 'ppc64',),
124 'intel': ('i386', 'x86_64'),
125 'intel-32': ('i386',),
126 'intel-64': ('x86_64',),
127 '3-way': ('ppc', 'i386', 'x86_64'),
128 'all': ('i386', 'ppc', 'x86_64', 'ppc64',) }
129 default_target_map = {
130 '64-bit': '10.5',
131 '3-way': '10.5',
132 'intel': '10.5',
133 'intel-32': '10.4',
134 'intel-64': '10.5',
135 'all': '10.5',
136 }
137
138 UNIVERSALOPTS = tuple(universal_opts_map.keys())
139
140 UNIVERSALARCHS = '32-bit'
141
142 ARCHLIST = universal_opts_map[UNIVERSALARCHS]
143
144 # Source directory (assume we're in Mac/BuildScript)
145 SRCDIR = os.path.dirname(
146 os.path.dirname(
147 os.path.dirname(
148 os.path.abspath(__file__
149 ))))
150
151 # $MACOSX_DEPLOYMENT_TARGET -> minimum OS X level
152 DEPTARGET = '10.5'
153
154 def getDeptargetTuple():
155 return tuple([int(n) for n in DEPTARGET.split('.')[0:2]])
156
157 def getTargetCompilers():
158 target_cc_map = {
159 '10.4': ('gcc-4.0', 'g++-4.0'),
160 '10.5': ('gcc', 'g++'),
161 '10.6': ('gcc', 'g++'),
162 }
163 return target_cc_map.get(DEPTARGET, ('gcc', 'g++') )
164
165 CC, CXX = getTargetCompilers()
166
167 PYTHON_2 = getVersionMajorMinor()[0] == 2
168 PYTHON_3 = getVersionMajorMinor()[0] == 3
169
170 USAGE = textwrap.dedent("""\
171 Usage: build_python [options]
172
173 Options:
174 -? or -h: Show this message
175 -b DIR
176 --build-dir=DIR: Create build here (default: %(WORKDIR)r)
177 --third-party=DIR: Store third-party sources here (default: %(DEPSRC)r)
178 --sdk-path=DIR: Location of the SDK (deprecated, use SDKROOT env variable)
179 --src-dir=DIR: Location of the Python sources (default: %(SRCDIR)r)
180 --dep-target=10.n macOS deployment target (default: %(DEPTARGET)r)
181 --universal-archs=x universal architectures (options: %(UNIVERSALOPTS)r, default: %(UNIVERSALARCHS)r)
182 """)% globals()
183
184 # Dict of object file names with shared library names to check after building.
185 # This is to ensure that we ended up dynamically linking with the shared
186 # library paths and versions we expected. For example:
187 # EXPECTED_SHARED_LIBS['_tkinter.so'] = [
188 # '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl',
189 # '/Library/Frameworks/Tk.framework/Versions/8.5/Tk']
190 EXPECTED_SHARED_LIBS = {}
191
192 # Are we building and linking with our own copy of Tcl/TK?
193 # For now, do so if deployment target is 10.6+.
194 def internalTk():
195 return getDeptargetTuple() >= (10, 6)
196
197 # List of names of third party software built with this installer.
198 # The names will be inserted into the rtf version of the License.
199 THIRD_PARTY_LIBS = []
200
201 # Instructions for building libraries that are necessary for building a
202 # batteries included python.
203 # [The recipes are defined here for convenience but instantiated later after
204 # command line options have been processed.]
205 def library_recipes():
206 result = []
207
208 LT_10_5 = bool(getDeptargetTuple() < (10, 5))
209
210 # Since Apple removed the header files for the deprecated system
211 # OpenSSL as of the Xcode 7 release (for OS X 10.10+), we do not
212 # have much choice but to build our own copy here, too.
213
214 result.extend([
215 dict(
216 name="OpenSSL 1.0.2u",
217 url="https://www.openssl.org/source/old/1.0.2/openssl-1.0.2u.tar.gz",
218 checksum='cdc2638f789ecc2db2c91488265686c1',
219 buildrecipe=build_universal_openssl,
220 configure=None,
221 install=None,
222 ),
223 ])
224
225 if internalTk():
226 result.extend([
227 dict(
228 name="Tcl 8.6.8",
229 url="ftp://ftp.tcl.tk/pub/tcl//tcl8_6/tcl8.6.8-src.tar.gz",
230 checksum='81656d3367af032e0ae6157eff134f89',
231 buildDir="unix",
232 configure_pre=[
233 '--enable-shared',
234 '--enable-threads',
235 '--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib'%(getVersion(),),
236 ],
237 useLDFlags=False,
238 install='make TCL_LIBRARY=%(TCL_LIBRARY)s && make install TCL_LIBRARY=%(TCL_LIBRARY)s DESTDIR=%(DESTDIR)s'%{
239 "DESTDIR": shellQuote(os.path.join(WORKDIR, 'libraries')),
240 "TCL_LIBRARY": shellQuote('/Library/Frameworks/Python.framework/Versions/%s/lib/tcl8.6'%(getVersion())),
241 },
242 ),
243 dict(
244 name="Tk 8.6.8",
245 url="ftp://ftp.tcl.tk/pub/tcl//tcl8_6/tk8.6.8-src.tar.gz",
246 checksum='5e0faecba458ee1386078fb228d008ba',
247 patches=[
248 "tk868_on_10_8_10_9.patch",
249 ],
250 buildDir="unix",
251 configure_pre=[
252 '--enable-aqua',
253 '--enable-shared',
254 '--enable-threads',
255 '--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib'%(getVersion(),),
256 ],
257 useLDFlags=False,
258 install='make TCL_LIBRARY=%(TCL_LIBRARY)s TK_LIBRARY=%(TK_LIBRARY)s && make install TCL_LIBRARY=%(TCL_LIBRARY)s TK_LIBRARY=%(TK_LIBRARY)s DESTDIR=%(DESTDIR)s'%{
259 "DESTDIR": shellQuote(os.path.join(WORKDIR, 'libraries')),
260 "TCL_LIBRARY": shellQuote('/Library/Frameworks/Python.framework/Versions/%s/lib/tcl8.6'%(getVersion())),
261 "TK_LIBRARY": shellQuote('/Library/Frameworks/Python.framework/Versions/%s/lib/tk8.6'%(getVersion())),
262 },
263 ),
264 ])
265
266 if PYTHON_3:
267 result.extend([
268 dict(
269 name="XZ 5.2.3",
270 url="http://tukaani.org/xz/xz-5.2.3.tar.gz",
271 checksum='ef68674fb47a8b8e741b34e429d86e9d',
272 configure_pre=[
273 '--disable-dependency-tracking',
274 ]
275 ),
276 ])
277
278 result.extend([
279 dict(
280 name="NCurses 5.9",
281 url="http://ftp.gnu.org/pub/gnu/ncurses/ncurses-5.9.tar.gz",
282 checksum='8cb9c412e5f2d96bc6f459aa8c6282a1',
283 configure_pre=[
284 "--enable-widec",
285 "--without-cxx",
286 "--without-cxx-binding",
287 "--without-ada",
288 "--without-curses-h",
289 "--enable-shared",
290 "--with-shared",
291 "--without-debug",
292 "--without-normal",
293 "--without-tests",
294 "--without-manpages",
295 "--datadir=/usr/share",
296 "--sysconfdir=/etc",
297 "--sharedstatedir=/usr/com",
298 "--with-terminfo-dirs=/usr/share/terminfo",
299 "--with-default-terminfo-dir=/usr/share/terminfo",
300 "--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib"%(getVersion(),),
301 ],
302 patchscripts=[
303 ("ftp://invisible-island.net/ncurses//5.9/ncurses-5.9-20120616-patch.sh.bz2",
304 "f54bf02a349f96a7c4f0d00922f3a0d4"),
305 ],
306 useLDFlags=False,
307 install='make && make install DESTDIR=%s && cd %s/usr/local/lib && ln -fs ../../../Library/Frameworks/Python.framework/Versions/%s/lib/lib* .'%(
308 shellQuote(os.path.join(WORKDIR, 'libraries')),
309 shellQuote(os.path.join(WORKDIR, 'libraries')),
310 getVersion(),
311 ),
312 ),
313 dict(
314 name="SQLite 3.31.1",
315 url="https://sqlite.org/2020/sqlite-autoconf-3310100.tar.gz",
316 checksum='2d0a553534c521504e3ac3ad3b90f125',
317 extra_cflags=('-Os '
318 '-DSQLITE_ENABLE_FTS5 '
319 '-DSQLITE_ENABLE_FTS4 '
320 '-DSQLITE_ENABLE_FTS3_PARENTHESIS '
321 '-DSQLITE_ENABLE_JSON1 '
322 '-DSQLITE_ENABLE_RTREE '
323 '-DSQLITE_TCL=0 '
324 '%s' % ('','-DSQLITE_WITHOUT_ZONEMALLOC ')[LT_10_5]),
325 configure_pre=[
326 '--enable-threadsafe',
327 '--enable-shared=no',
328 '--enable-static=yes',
329 '--disable-readline',
330 '--disable-dependency-tracking',
331 ]
332 ),
333 ])
334
335 if getDeptargetTuple() < (10, 5):
336 result.extend([
337 dict(
338 name="Bzip2 1.0.6",
339 url="http://bzip.org/1.0.6/bzip2-1.0.6.tar.gz",
340 checksum='00b516f4704d4a7cb50a1d97e6e8e15b',
341 configure=None,
342 install='make install CC=%s CXX=%s, PREFIX=%s/usr/local/ CFLAGS="-arch %s"'%(
343 CC, CXX,
344 shellQuote(os.path.join(WORKDIR, 'libraries')),
345 ' -arch '.join(ARCHLIST),
346 ),
347 ),
348 dict(
349 name="ZLib 1.2.3",
350 url="http://www.gzip.org/zlib/zlib-1.2.3.tar.gz",
351 checksum='debc62758716a169df9f62e6ab2bc634',
352 configure=None,
353 install='make install CC=%s CXX=%s, prefix=%s/usr/local/ CFLAGS="-arch %s"'%(
354 CC, CXX,
355 shellQuote(os.path.join(WORKDIR, 'libraries')),
356 ' -arch '.join(ARCHLIST),
357 ),
358 ),
359 dict(
360 # Note that GNU readline is GPL'd software
361 name="GNU Readline 6.1.2",
362 url="http://ftp.gnu.org/pub/gnu/readline/readline-6.1.tar.gz" ,
363 checksum='fc2f7e714fe792db1ce6ddc4c9fb4ef3',
364 patchlevel='0',
365 patches=[
366 # The readline maintainers don't do actual micro releases, but
367 # just ship a set of patches.
368 ('http://ftp.gnu.org/pub/gnu/readline/readline-6.1-patches/readline61-001',
369 'c642f2e84d820884b0bf9fd176bc6c3f'),
370 ('http://ftp.gnu.org/pub/gnu/readline/readline-6.1-patches/readline61-002',
371 '1a76781a1ea734e831588285db7ec9b1'),
372 ]
373 ),
374 ])
375
376 if not PYTHON_3:
377 result.extend([
378 dict(
379 name="Sleepycat DB 4.7.25",
380 url="http://download.oracle.com/berkeley-db/db-4.7.25.tar.gz",
381 checksum='ec2b87e833779681a0c3a814aa71359e',
382 buildDir="build_unix",
383 configure="../dist/configure",
384 configure_pre=[
385 '--includedir=/usr/local/include/db4',
386 ]
387 ),
388 ])
389
390 return result
391
392
393 # Instructions for building packages inside the .mpkg.
394 def pkg_recipes():
395 unselected_for_python3 = ('selected', 'unselected')[PYTHON_3]
396 result = [
397 dict(
398 name="PythonFramework",
399 long_name="Python Framework",
400 source="/Library/Frameworks/Python.framework",
401 readme="""\
402 This package installs Python.framework, that is the python
403 interpreter and the standard library.
404 """,
405 postflight="scripts/postflight.framework",
406 selected='selected',
407 ),
408 dict(
409 name="PythonApplications",
410 long_name="GUI Applications",
411 source="/Applications/Python %(VER)s",
412 readme="""\
413 This package installs IDLE (an interactive Python IDE),
414 Python Launcher and Build Applet (create application bundles
415 from python scripts).
416
417 It also installs a number of examples and demos.
418 """,
419 required=False,
420 selected='selected',
421 ),
422 dict(
423 name="PythonUnixTools",
424 long_name="UNIX command-line tools",
425 source="/usr/local/bin",
426 readme="""\
427 This package installs the unix tools in /usr/local/bin for
428 compatibility with older releases of Python. This package
429 is not necessary to use Python.
430 """,
431 required=False,
432 selected='selected',
433 ),
434 dict(
435 name="PythonDocumentation",
436 long_name="Python Documentation",
437 topdir="/Library/Frameworks/Python.framework/Versions/%(VER)s/Resources/English.lproj/Documentation",
438 source="/pydocs",
439 readme="""\
440 This package installs the python documentation at a location
441 that is useable for pydoc and IDLE.
442 """,
443 postflight="scripts/postflight.documentation",
444 required=False,
445 selected='selected',
446 ),
447 dict(
448 name="PythonProfileChanges",
449 long_name="Shell profile updater",
450 readme="""\
451 This packages updates your shell profile to make sure that
452 the Python tools are found by your shell in preference of
453 the system provided Python tools.
454
455 If you don't install this package you'll have to add
456 "/Library/Frameworks/Python.framework/Versions/%(VER)s/bin"
457 to your PATH by hand.
458 """,
459 postflight="scripts/postflight.patch-profile",
460 topdir="/Library/Frameworks/Python.framework",
461 source="/empty-dir",
462 required=False,
463 selected='selected',
464 ),
465 dict(
466 name="PythonInstallPip",
467 long_name="Install or upgrade pip",
468 readme="""\
469 This package installs (or upgrades from an earlier version)
470 pip, a tool for installing and managing Python packages.
471 """,
472 postflight="scripts/postflight.ensurepip",
473 topdir="/Library/Frameworks/Python.framework",
474 source="/empty-dir",
475 required=False,
476 selected='selected',
477 ),
478 ]
479
480 return result
481
482 def fatal(msg):
483 """
484 A fatal error, bail out.
485 """
486 sys.stderr.write('FATAL: ')
487 sys.stderr.write(msg)
488 sys.stderr.write('\n')
489 sys.exit(1)
490
491 def fileContents(fn):
492 """
493 Return the contents of the named file
494 """
495 return open(fn, 'r').read()
496
497 def runCommand(commandline):
498 """
499 Run a command and raise RuntimeError if it fails. Output is suppressed
500 unless the command fails.
501 """
502 fd = os.popen(commandline, 'r')
503 data = fd.read()
504 xit = fd.close()
505 if xit is not None:
506 sys.stdout.write(data)
507 raise RuntimeError("command failed: %s"%(commandline,))
508
509 if VERBOSE:
510 sys.stdout.write(data); sys.stdout.flush()
511
512 def captureCommand(commandline):
513 fd = os.popen(commandline, 'r')
514 data = fd.read()
515 xit = fd.close()
516 if xit is not None:
517 sys.stdout.write(data)
518 raise RuntimeError("command failed: %s"%(commandline,))
519
520 return data
521
522 def getTclTkVersion(configfile, versionline):
523 """
524 search Tcl or Tk configuration file for version line
525 """
526 try:
527 f = open(configfile, "r")
528 except OSError:
529 fatal("Framework configuration file not found: %s" % configfile)
530
531 for l in f:
532 if l.startswith(versionline):
533 f.close()
534 return l
535
536 fatal("Version variable %s not found in framework configuration file: %s"
537 % (versionline, configfile))
538
539 def checkEnvironment():
540 """
541 Check that we're running on a supported system.
542 """
543
544 if sys.version_info[0:2] < (2, 5):
545 fatal("This script must be run with Python 2.5 (or later)")
546
547 if platform.system() != 'Darwin':
548 fatal("This script should be run on a macOS 10.5 (or later) system")
549
550 if int(platform.release().split('.')[0]) < 8:
551 fatal("This script should be run on a macOS 10.5 (or later) system")
552
553 # Because we only support dynamic load of only one major/minor version of
554 # Tcl/Tk, if we are not using building and using our own private copy of
555 # Tcl/Tk, ensure:
556 # 1. there is a user-installed framework (usually ActiveTcl) in (or linked
557 # in) SDKROOT/Library/Frameworks. As of Python 3.6.5, we no longer
558 # enforce that the version of the user-installed framework also
559 # exists in the system-supplied Tcl/Tk frameworks. Time to support
560 # Tcl/Tk 8.6 even if Apple does not.
561 if not internalTk():
562 frameworks = {}
563 for framework in ['Tcl', 'Tk']:
564 fwpth = 'Library/Frameworks/%s.framework/Versions/Current' % framework
565 libfw = os.path.join('/', fwpth)
566 usrfw = os.path.join(os.getenv('HOME'), fwpth)
567 frameworks[framework] = os.readlink(libfw)
568 if not os.path.exists(libfw):
569 fatal("Please install a link to a current %s %s as %s so "
570 "the user can override the system framework."
571 % (framework, frameworks[framework], libfw))
572 if os.path.exists(usrfw):
573 fatal("Please rename %s to avoid possible dynamic load issues."
574 % usrfw)
575
576 if frameworks['Tcl'] != frameworks['Tk']:
577 fatal("The Tcl and Tk frameworks are not the same version.")
578
579 print(" -- Building with external Tcl/Tk %s frameworks"
580 % frameworks['Tk'])
581
582 # add files to check after build
583 EXPECTED_SHARED_LIBS['_tkinter.so'] = [
584 "/Library/Frameworks/Tcl.framework/Versions/%s/Tcl"
585 % frameworks['Tcl'],
586 "/Library/Frameworks/Tk.framework/Versions/%s/Tk"
587 % frameworks['Tk'],
588 ]
589 else:
590 print(" -- Building private copy of Tcl/Tk")
591 print("")
592
593 # Remove inherited environment variables which might influence build
594 environ_var_prefixes = ['CPATH', 'C_INCLUDE_', 'DYLD_', 'LANG', 'LC_',
595 'LD_', 'LIBRARY_', 'PATH', 'PYTHON']
596 for ev in list(os.environ):
597 for prefix in environ_var_prefixes:
598 if ev.startswith(prefix) :
599 print("INFO: deleting environment variable %s=%s" % (
600 ev, os.environ[ev]))
601 del os.environ[ev]
602
603 base_path = '/bin:/sbin:/usr/bin:/usr/sbin'
604 if 'SDK_TOOLS_BIN' in os.environ:
605 base_path = os.environ['SDK_TOOLS_BIN'] + ':' + base_path
606 # Xcode 2.5 on OS X 10.4 does not include SetFile in its usr/bin;
607 # add its fixed location here if it exists
608 OLD_DEVELOPER_TOOLS = '/Developer/Tools'
609 if os.path.isdir(OLD_DEVELOPER_TOOLS):
610 base_path = base_path + ':' + OLD_DEVELOPER_TOOLS
611 os.environ['PATH'] = base_path
612 print("Setting default PATH: %s"%(os.environ['PATH']))
613 if PYTHON_2:
614 # Ensure we have access to sphinx-build.
615 # You may have to define SDK_TOOLS_BIN and link to it there,
616 runCommand('sphinx-build --version')
617
618 def parseOptions(args=None):
619 """
620 Parse arguments and update global settings.
621 """
622 global WORKDIR, DEPSRC, SRCDIR, DEPTARGET
623 global UNIVERSALOPTS, UNIVERSALARCHS, ARCHLIST, CC, CXX
624 global FW_VERSION_PREFIX
625 global FW_SSL_DIRECTORY
626
627 if args is None:
628 args = sys.argv[1:]
629
630 try:
631 options, args = getopt.getopt(args, '?hb',
632 [ 'build-dir=', 'third-party=', 'sdk-path=' , 'src-dir=',
633 'dep-target=', 'universal-archs=', 'help' ])
634 except getopt.GetoptError:
635 print(sys.exc_info()[1])
636 sys.exit(1)
637
638 if args:
639 print("Additional arguments")
640 sys.exit(1)
641
642 deptarget = None
643 for k, v in options:
644 if k in ('-h', '-?', '--help'):
645 print(USAGE)
646 sys.exit(0)
647
648 elif k in ('-d', '--build-dir'):
649 WORKDIR=v
650
651 elif k in ('--third-party',):
652 DEPSRC=v
653
654 elif k in ('--sdk-path',):
655 print(" WARNING: --sdk-path is no longer supported")
656
657 elif k in ('--src-dir',):
658 SRCDIR=v
659
660 elif k in ('--dep-target', ):
661 DEPTARGET=v
662 deptarget=v
663
664 elif k in ('--universal-archs', ):
665 if v in UNIVERSALOPTS:
666 UNIVERSALARCHS = v
667 ARCHLIST = universal_opts_map[UNIVERSALARCHS]
668 if deptarget is None:
669 # Select alternate default deployment
670 # target
671 DEPTARGET = default_target_map.get(v, '10.5')
672 else:
673 raise NotImplementedError(v)
674
675 else:
676 raise NotImplementedError(k)
677
678 SRCDIR=os.path.abspath(SRCDIR)
679 WORKDIR=os.path.abspath(WORKDIR)
680 DEPSRC=os.path.abspath(DEPSRC)
681
682 CC, CXX = getTargetCompilers()
683
684 FW_VERSION_PREFIX = FW_PREFIX[:] + ["Versions", getVersion()]
685 FW_SSL_DIRECTORY = FW_VERSION_PREFIX[:] + ["etc", "openssl"]
686
687 print("-- Settings:")
688 print(" * Source directory: %s" % SRCDIR)
689 print(" * Build directory: %s" % WORKDIR)
690 print(" * Third-party source: %s" % DEPSRC)
691 print(" * Deployment target: %s" % DEPTARGET)
692 print(" * Universal archs: %s" % str(ARCHLIST))
693 print(" * C compiler: %s" % CC)
694 print(" * C++ compiler: %s" % CXX)
695 print("")
696 print(" -- Building a Python %s framework at patch level %s"
697 % (getVersion(), getFullVersion()))
698 print("")
699
700 def extractArchive(builddir, archiveName):
701 """
702 Extract a source archive into 'builddir'. Returns the path of the
703 extracted archive.
704
705 XXX: This function assumes that archives contain a toplevel directory
706 that is has the same name as the basename of the archive. This is
707 safe enough for almost anything we use. Unfortunately, it does not
708 work for current Tcl and Tk source releases where the basename of
709 the archive ends with "-src" but the uncompressed directory does not.
710 For now, just special case Tcl and Tk tar.gz downloads.
711 """
712 curdir = os.getcwd()
713 try:
714 os.chdir(builddir)
715 if archiveName.endswith('.tar.gz'):
716 retval = os.path.basename(archiveName[:-7])
717 if ((retval.startswith('tcl') or retval.startswith('tk'))
718 and retval.endswith('-src')):
719 retval = retval[:-4]
720 if os.path.exists(retval):
721 shutil.rmtree(retval)
722 fp = os.popen("tar zxf %s 2>&1"%(shellQuote(archiveName),), 'r')
723
724 elif archiveName.endswith('.tar.bz2'):
725 retval = os.path.basename(archiveName[:-8])
726 if os.path.exists(retval):
727 shutil.rmtree(retval)
728 fp = os.popen("tar jxf %s 2>&1"%(shellQuote(archiveName),), 'r')
729
730 elif archiveName.endswith('.tar'):
731 retval = os.path.basename(archiveName[:-4])
732 if os.path.exists(retval):
733 shutil.rmtree(retval)
734 fp = os.popen("tar xf %s 2>&1"%(shellQuote(archiveName),), 'r')
735
736 elif archiveName.endswith('.zip'):
737 retval = os.path.basename(archiveName[:-4])
738 if os.path.exists(retval):
739 shutil.rmtree(retval)
740 fp = os.popen("unzip %s 2>&1"%(shellQuote(archiveName),), 'r')
741
742 data = fp.read()
743 xit = fp.close()
744 if xit is not None:
745 sys.stdout.write(data)
746 raise RuntimeError("Cannot extract %s"%(archiveName,))
747
748 return os.path.join(builddir, retval)
749
750 finally:
751 os.chdir(curdir)
752
753 def downloadURL(url, fname):
754 """
755 Download the contents of the url into the file.
756 """
757 fpIn = urllib_request.urlopen(url)
758 fpOut = open(fname, 'wb')
759 block = fpIn.read(10240)
760 try:
761 while block:
762 fpOut.write(block)
763 block = fpIn.read(10240)
764 fpIn.close()
765 fpOut.close()
766 except:
767 try:
768 os.unlink(fname)
769 except OSError:
770 pass
771
772 def verifyThirdPartyFile(url, checksum, fname):
773 """
774 Download file from url to filename fname if it does not already exist.
775 Abort if file contents does not match supplied md5 checksum.
776 """
777 name = os.path.basename(fname)
778 if os.path.exists(fname):
779 print("Using local copy of %s"%(name,))
780 else:
781 print("Did not find local copy of %s"%(name,))
782 print("Downloading %s"%(name,))
783 downloadURL(url, fname)
784 print("Archive for %s stored as %s"%(name, fname))
785 if os.system(
786 'MD5=$(openssl md5 %s) ; test "${MD5##*= }" = "%s"'
787 % (shellQuote(fname), checksum) ):
788 fatal('MD5 checksum mismatch for file %s' % fname)
789
790 def build_universal_openssl(basedir, archList):
791 """
792 Special case build recipe for universal build of openssl.
793
794 The upstream OpenSSL build system does not directly support
795 OS X universal builds. We need to build each architecture
796 separately then lipo them together into fat libraries.
797 """
798
799 # OpenSSL fails to build with Xcode 2.5 (on OS X 10.4).
800 # If we are building on a 10.4.x or earlier system,
801 # unilaterally disable assembly code building to avoid the problem.
802 no_asm = int(platform.release().split(".")[0]) < 9
803
804 def build_openssl_arch(archbase, arch):
805 "Build one architecture of openssl"
806 arch_opts = {
807 "i386": ["darwin-i386-cc"],
808 "x86_64": ["darwin64-x86_64-cc", "enable-ec_nistp_64_gcc_128"],
809 "ppc": ["darwin-ppc-cc"],
810 "ppc64": ["darwin64-ppc-cc"],
811 }
812 configure_opts = [
813 "no-krb5",
814 "no-idea",
815 "no-mdc2",
816 "no-rc5",
817 "no-zlib",
818 "enable-tlsext",
819 "no-ssl2",
820 "no-ssl3",
821 # "enable-unit-test",
822 "shared",
823 "--install_prefix=%s"%shellQuote(archbase),
824 "--prefix=%s"%os.path.join("/", *FW_VERSION_PREFIX),
825 "--openssldir=%s"%os.path.join("/", *FW_SSL_DIRECTORY),
826 ]
827 if no_asm:
828 configure_opts.append("no-asm")
829 # OpenSSL 1.0.2o broke the Configure test for whether the compiler
830 # in use supports dependency rule generation (cc -M) with gcc-4.2
831 # used for the 10.6+ installer builds. Patch Configure here to
832 # force use of "cc -M" rather than "makedepend".
833 runCommand(
834 """sed -i "" 's|my $cc_as_makedepend = 0|my $cc_as_makedepend = 1|g' Configure""")
835
836 runCommand(" ".join(["perl", "Configure"]
837 + arch_opts[arch] + configure_opts))
838 runCommand("make depend")
839 runCommand("make all")
840 runCommand("make install_sw")
841 # runCommand("make test")
842 return
843
844 srcdir = os.getcwd()
845 universalbase = os.path.join(srcdir, "..",
846 os.path.basename(srcdir) + "-universal")
847 os.mkdir(universalbase)
848 archbasefws = []
849 for arch in archList:
850 # fresh copy of the source tree
851 archsrc = os.path.join(universalbase, arch, "src")
852 shutil.copytree(srcdir, archsrc, symlinks=True)
853 # install base for this arch
854 archbase = os.path.join(universalbase, arch, "root")
855 os.mkdir(archbase)
856 # Python framework base within install_prefix:
857 # the build will install into this framework..
858 # This is to ensure that the resulting shared libs have
859 # the desired real install paths built into them.
860 archbasefw = os.path.join(archbase, *FW_VERSION_PREFIX)
861
862 # build one architecture
863 os.chdir(archsrc)
864 build_openssl_arch(archbase, arch)
865 os.chdir(srcdir)
866 archbasefws.append(archbasefw)
867
868 # copy arch-independent files from last build into the basedir framework
869 basefw = os.path.join(basedir, *FW_VERSION_PREFIX)
870 shutil.copytree(
871 os.path.join(archbasefw, "include", "openssl"),
872 os.path.join(basefw, "include", "openssl")
873 )
874
875 shlib_version_number = grepValue(os.path.join(archsrc, "Makefile"),
876 "SHLIB_VERSION_NUMBER")
877 # e.g. -> "1.0.0"
878 libcrypto = "libcrypto.dylib"
879 libcrypto_versioned = libcrypto.replace(".", "."+shlib_version_number+".")
880 # e.g. -> "libcrypto.1.0.0.dylib"
881 libssl = "libssl.dylib"
882 libssl_versioned = libssl.replace(".", "."+shlib_version_number+".")
883 # e.g. -> "libssl.1.0.0.dylib"
884
885 try:
886 os.mkdir(os.path.join(basefw, "lib"))
887 except OSError:
888 pass
889
890 # merge the individual arch-dependent shared libs into a fat shared lib
891 archbasefws.insert(0, basefw)
892 for (lib_unversioned, lib_versioned) in [
893 (libcrypto, libcrypto_versioned),
894 (libssl, libssl_versioned)
895 ]:
896 runCommand("lipo -create -output " +
897 " ".join(shellQuote(
898 os.path.join(fw, "lib", lib_versioned))
899 for fw in archbasefws))
900 # and create an unversioned symlink of it
901 os.symlink(lib_versioned, os.path.join(basefw, "lib", lib_unversioned))
902
903 # Create links in the temp include and lib dirs that will be injected
904 # into the Python build so that setup.py can find them while building
905 # and the versioned links so that the setup.py post-build import test
906 # does not fail.
907 relative_path = os.path.join("..", "..", "..", *FW_VERSION_PREFIX)
908 for fn in [
909 ["include", "openssl"],
910 ["lib", libcrypto],
911 ["lib", libssl],
912 ["lib", libcrypto_versioned],
913 ["lib", libssl_versioned],
914 ]:
915 os.symlink(
916 os.path.join(relative_path, *fn),
917 os.path.join(basedir, "usr", "local", *fn)
918 )
919
920 return
921
922 def buildRecipe(recipe, basedir, archList):
923 """
924 Build software using a recipe. This function does the
925 'configure;make;make install' dance for C software, with a possibility
926 to customize this process, basically a poor-mans DarwinPorts.
927 """
928 curdir = os.getcwd()
929
930 name = recipe['name']
931 THIRD_PARTY_LIBS.append(name)
932 url = recipe['url']
933 configure = recipe.get('configure', './configure')
934 buildrecipe = recipe.get('buildrecipe', None)
935 install = recipe.get('install', 'make && make install DESTDIR=%s'%(
936 shellQuote(basedir)))
937
938 archiveName = os.path.split(url)[-1]
939 sourceArchive = os.path.join(DEPSRC, archiveName)
940
941 if not os.path.exists(DEPSRC):
942 os.mkdir(DEPSRC)
943
944 verifyThirdPartyFile(url, recipe['checksum'], sourceArchive)
945 print("Extracting archive for %s"%(name,))
946 buildDir=os.path.join(WORKDIR, '_bld')
947 if not os.path.exists(buildDir):
948 os.mkdir(buildDir)
949
950 workDir = extractArchive(buildDir, sourceArchive)
951 os.chdir(workDir)
952
953 for patch in recipe.get('patches', ()):
954 if isinstance(patch, tuple):
955 url, checksum = patch
956 fn = os.path.join(DEPSRC, os.path.basename(url))
957 verifyThirdPartyFile(url, checksum, fn)
958 else:
959 # patch is a file in the source directory
960 fn = os.path.join(curdir, patch)
961 runCommand('patch -p%s < %s'%(recipe.get('patchlevel', 1),
962 shellQuote(fn),))
963
964 for patchscript in recipe.get('patchscripts', ()):
965 if isinstance(patchscript, tuple):
966 url, checksum = patchscript
967 fn = os.path.join(DEPSRC, os.path.basename(url))
968 verifyThirdPartyFile(url, checksum, fn)
969 else:
970 # patch is a file in the source directory
971 fn = os.path.join(curdir, patchscript)
972 if fn.endswith('.bz2'):
973 runCommand('bunzip2 -fk %s' % shellQuote(fn))
974 fn = fn[:-4]
975 runCommand('sh %s' % shellQuote(fn))
976 os.unlink(fn)
977
978 if 'buildDir' in recipe:
979 os.chdir(recipe['buildDir'])
980
981 if configure is not None:
982 configure_args = [
983 "--prefix=/usr/local",
984 "--enable-static",
985 "--disable-shared",
986 #"CPP=gcc -arch %s -E"%(' -arch '.join(archList,),),
987 ]
988
989 if 'configure_pre' in recipe:
990 args = list(recipe['configure_pre'])
991 if '--disable-static' in args:
992 configure_args.remove('--enable-static')
993 if '--enable-shared' in args:
994 configure_args.remove('--disable-shared')
995 configure_args.extend(args)
996
997 if recipe.get('useLDFlags', 1):
998 configure_args.extend([
999 "CFLAGS=%s-mmacosx-version-min=%s -arch %s "
1000 "-I%s/usr/local/include"%(
1001 recipe.get('extra_cflags', ''),
1002 DEPTARGET,
1003 ' -arch '.join(archList),
1004 shellQuote(basedir)[1:-1],),
1005 "LDFLAGS=-mmacosx-version-min=%s -L%s/usr/local/lib -arch %s"%(
1006 DEPTARGET,
1007 shellQuote(basedir)[1:-1],
1008 ' -arch '.join(archList)),
1009 ])
1010 else:
1011 configure_args.extend([
1012 "CFLAGS=%s-mmacosx-version-min=%s -arch %s "
1013 "-I%s/usr/local/include"%(
1014 recipe.get('extra_cflags', ''),
1015 DEPTARGET,
1016 ' -arch '.join(archList),
1017 shellQuote(basedir)[1:-1],),
1018 ])
1019
1020 if 'configure_post' in recipe:
1021 configure_args = configure_args + list(recipe['configure_post'])
1022
1023 configure_args.insert(0, configure)
1024 configure_args = [ shellQuote(a) for a in configure_args ]
1025
1026 print("Running configure for %s"%(name,))
1027 runCommand(' '.join(configure_args) + ' 2>&1')
1028
1029 if buildrecipe is not None:
1030 # call special-case build recipe, e.g. for openssl
1031 buildrecipe(basedir, archList)
1032
1033 if install is not None:
1034 print("Running install for %s"%(name,))
1035 runCommand('{ ' + install + ' ;} 2>&1')
1036
1037 print("Done %s"%(name,))
1038 print("")
1039
1040 os.chdir(curdir)
1041
1042 def buildLibraries():
1043 """
1044 Build our dependencies into $WORKDIR/libraries/usr/local
1045 """
1046 print("")
1047 print("Building required libraries")
1048 print("")
1049 universal = os.path.join(WORKDIR, 'libraries')
1050 os.mkdir(universal)
1051 os.makedirs(os.path.join(universal, 'usr', 'local', 'lib'))
1052 os.makedirs(os.path.join(universal, 'usr', 'local', 'include'))
1053
1054 for recipe in library_recipes():
1055 buildRecipe(recipe, universal, ARCHLIST)
1056
1057
1058
1059 def buildPythonDocs():
1060 # This stores the documentation as Resources/English.lproj/Documentation
1061 # inside the framework. pydoc and IDLE will pick it up there.
1062 print("Install python documentation")
1063 rootDir = os.path.join(WORKDIR, '_root')
1064 buildDir = os.path.join('../../Doc')
1065 docdir = os.path.join(rootDir, 'pydocs')
1066 curDir = os.getcwd()
1067 os.chdir(buildDir)
1068 runCommand('make clean')
1069 if PYTHON_2:
1070 # Python 2 doc builds do not use blurb nor do they have a venv target.
1071 # Assume sphinx-build is on our PATH, checked in checkEnvironment
1072 runCommand('make html')
1073 else:
1074 # Create virtual environment for docs builds with blurb and sphinx
1075 runCommand('make venv')
1076 runCommand('make html PYTHON=venv/bin/python')
1077 os.chdir(curDir)
1078 if not os.path.exists(docdir):
1079 os.mkdir(docdir)
1080 os.rename(os.path.join(buildDir, 'build', 'html'), docdir)
1081
1082
1083 def buildPython():
1084 print("Building a universal python for %s architectures" % UNIVERSALARCHS)
1085
1086 buildDir = os.path.join(WORKDIR, '_bld', 'python')
1087 rootDir = os.path.join(WORKDIR, '_root')
1088
1089 if os.path.exists(buildDir):
1090 shutil.rmtree(buildDir)
1091 if os.path.exists(rootDir):
1092 shutil.rmtree(rootDir)
1093 os.makedirs(buildDir)
1094 os.makedirs(rootDir)
1095 os.makedirs(os.path.join(rootDir, 'empty-dir'))
1096 curdir = os.getcwd()
1097 os.chdir(buildDir)
1098
1099 # Extract the version from the configure file, needed to calculate
1100 # several paths.
1101 version = getVersion()
1102
1103 # Since the extra libs are not in their installed framework location
1104 # during the build, augment the library path so that the interpreter
1105 # will find them during its extension import sanity checks.
1106 os.environ['DYLD_LIBRARY_PATH'] = os.path.join(WORKDIR,
1107 'libraries', 'usr', 'local', 'lib')
1108 print("Running configure...")
1109 runCommand("%s -C --enable-framework --enable-universalsdk=/ "
1110 "--with-universal-archs=%s "
1111 "%s "
1112 "%s "
1113 "%s "
1114 "%s "
1115 "LDFLAGS='-g -L%s/libraries/usr/local/lib' "
1116 "CFLAGS='-g -I%s/libraries/usr/local/include' 2>&1"%(
1117 shellQuote(os.path.join(SRCDIR, 'configure')),
1118 UNIVERSALARCHS,
1119 (' ', '--with-computed-gotos ')[PYTHON_3],
1120 (' ', '--without-ensurepip ')[PYTHON_3],
1121 (' ', "--with-tcltk-includes='-I%s/libraries/usr/local/include'"%(
1122 shellQuote(WORKDIR)[1:-1],))[internalTk()],
1123 (' ', "--with-tcltk-libs='-L%s/libraries/usr/local/lib -ltcl8.6 -ltk8.6'"%(
1124 shellQuote(WORKDIR)[1:-1],))[internalTk()],
1125 shellQuote(WORKDIR)[1:-1],
1126 shellQuote(WORKDIR)[1:-1]))
1127
1128 # Look for environment value BUILDINSTALLER_BUILDPYTHON_MAKE_EXTRAS
1129 # and, if defined, append its value to the make command. This allows
1130 # us to pass in version control tags, like GITTAG, to a build from a
1131 # tarball rather than from a vcs checkout, thus eliminating the need
1132 # to have a working copy of the vcs program on the build machine.
1133 #
1134 # A typical use might be:
1135 # export BUILDINSTALLER_BUILDPYTHON_MAKE_EXTRAS=" \
1136 # GITVERSION='echo 123456789a' \
1137 # GITTAG='echo v3.6.0' \
1138 # GITBRANCH='echo 3.6'"
1139
1140 make_extras = os.getenv("BUILDINSTALLER_BUILDPYTHON_MAKE_EXTRAS")
1141 if make_extras:
1142 make_cmd = "make " + make_extras
1143 else:
1144 make_cmd = "make"
1145 print("Running " + make_cmd)
1146 runCommand(make_cmd)
1147
1148 print("Running make install")
1149 runCommand("make install DESTDIR=%s"%(
1150 shellQuote(rootDir)))
1151
1152 print("Running make frameworkinstallextras")
1153 runCommand("make frameworkinstallextras DESTDIR=%s"%(
1154 shellQuote(rootDir)))
1155
1156 del os.environ['DYLD_LIBRARY_PATH']
1157 print("Copying required shared libraries")
1158 if os.path.exists(os.path.join(WORKDIR, 'libraries', 'Library')):
1159 build_lib_dir = os.path.join(
1160 WORKDIR, 'libraries', 'Library', 'Frameworks',
1161 'Python.framework', 'Versions', getVersion(), 'lib')
1162 fw_lib_dir = os.path.join(
1163 WORKDIR, '_root', 'Library', 'Frameworks',
1164 'Python.framework', 'Versions', getVersion(), 'lib')
1165 if internalTk():
1166 # move Tcl and Tk pkgconfig files
1167 runCommand("mv %s/pkgconfig/* %s/pkgconfig"%(
1168 shellQuote(build_lib_dir),
1169 shellQuote(fw_lib_dir) ))
1170 runCommand("rm -r %s/pkgconfig"%(
1171 shellQuote(build_lib_dir), ))
1172 runCommand("mv %s/* %s"%(
1173 shellQuote(build_lib_dir),
1174 shellQuote(fw_lib_dir) ))
1175
1176 frmDir = os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework')
1177 frmDirVersioned = os.path.join(frmDir, 'Versions', version)
1178 path_to_lib = os.path.join(frmDirVersioned, 'lib', 'python%s'%(version,))
1179 # create directory for OpenSSL certificates
1180 sslDir = os.path.join(frmDirVersioned, 'etc', 'openssl')
1181 os.makedirs(sslDir)
1182
1183 print("Fix file modes")
1184 gid = grp.getgrnam('admin').gr_gid
1185
1186 shared_lib_error = False
1187 for dirpath, dirnames, filenames in os.walk(frmDir):
1188 for dn in dirnames:
1189 os.chmod(os.path.join(dirpath, dn), STAT_0o775)
1190 os.chown(os.path.join(dirpath, dn), -1, gid)
1191
1192 for fn in filenames:
1193 if os.path.islink(fn):
1194 continue
1195
1196 # "chmod g+w $fn"
1197 p = os.path.join(dirpath, fn)
1198 st = os.stat(p)
1199 os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IWGRP)
1200 os.chown(p, -1, gid)
1201
1202 if fn in EXPECTED_SHARED_LIBS:
1203 # check to see that this file was linked with the
1204 # expected library path and version
1205 data = captureCommand("otool -L %s" % shellQuote(p))
1206 for sl in EXPECTED_SHARED_LIBS[fn]:
1207 if ("\t%s " % sl) not in data:
1208 print("Expected shared lib %s was not linked with %s"
1209 % (sl, p))
1210 shared_lib_error = True
1211
1212 if shared_lib_error:
1213 fatal("Unexpected shared library errors.")
1214
1215 if PYTHON_3:
1216 LDVERSION=None
1217 VERSION=None
1218 ABIFLAGS=None
1219
1220 fp = open(os.path.join(buildDir, 'Makefile'), 'r')
1221 for ln in fp:
1222 if ln.startswith('VERSION='):
1223 VERSION=ln.split()[1]
1224 if ln.startswith('ABIFLAGS='):
1225 ABIFLAGS=ln.split()[1]
1226 if ln.startswith('LDVERSION='):
1227 LDVERSION=ln.split()[1]
1228 fp.close()
1229
1230 LDVERSION = LDVERSION.replace('$(VERSION)', VERSION)
1231 LDVERSION = LDVERSION.replace('$(ABIFLAGS)', ABIFLAGS)
1232 config_suffix = '-' + LDVERSION
1233 if getVersionMajorMinor() >= (3, 6):
1234 config_suffix = config_suffix + '-darwin'
1235 else:
1236 config_suffix = '' # Python 2.x
1237
1238 # We added some directories to the search path during the configure
1239 # phase. Remove those because those directories won't be there on
1240 # the end-users system. Also remove the directories from _sysconfigdata.py
1241 # (added in 3.3) if it exists.
1242
1243 include_path = '-I%s/libraries/usr/local/include' % (WORKDIR,)
1244 lib_path = '-L%s/libraries/usr/local/lib' % (WORKDIR,)
1245
1246 # fix Makefile
1247 path = os.path.join(path_to_lib, 'config' + config_suffix, 'Makefile')
1248 fp = open(path, 'r')
1249 data = fp.read()
1250 fp.close()
1251
1252 for p in (include_path, lib_path):
1253 data = data.replace(" " + p, '')
1254 data = data.replace(p + " ", '')
1255
1256 fp = open(path, 'w')
1257 fp.write(data)
1258 fp.close()
1259
1260 # fix _sysconfigdata
1261 #
1262 # TODO: make this more robust! test_sysconfig_module of
1263 # distutils.tests.test_sysconfig.SysconfigTestCase tests that
1264 # the output from get_config_var in both sysconfig and
1265 # distutils.sysconfig is exactly the same for both CFLAGS and
1266 # LDFLAGS. The fixing up is now complicated by the pretty
1267 # printing in _sysconfigdata.py. Also, we are using the
1268 # pprint from the Python running the installer build which
1269 # may not cosmetically format the same as the pprint in the Python
1270 # being built (and which is used to originally generate
1271 # _sysconfigdata.py).
1272
1273 import pprint
1274 if getVersionMajorMinor() >= (3, 6):
1275 # XXX this is extra-fragile
1276 path = os.path.join(path_to_lib, '_sysconfigdata_m_darwin_darwin.py')
1277 else:
1278 path = os.path.join(path_to_lib, '_sysconfigdata.py')
1279 fp = open(path, 'r')
1280 data = fp.read()
1281 fp.close()
1282 # create build_time_vars dict
1283 exec(data)
1284 vars = {}
1285 for k, v in build_time_vars.items():
1286 if type(v) == type(''):
1287 for p in (include_path, lib_path):
1288 v = v.replace(' ' + p, '')
1289 v = v.replace(p + ' ', '')
1290 vars[k] = v
1291
1292 fp = open(path, 'w')
1293 # duplicated from sysconfig._generate_posix_vars()
1294 fp.write('# system configuration generated and used by'
1295 ' the sysconfig module\n')
1296 fp.write('build_time_vars = ')
1297 pprint.pprint(vars, stream=fp)
1298 fp.close()
1299
1300 # Add symlinks in /usr/local/bin, using relative links
1301 usr_local_bin = os.path.join(rootDir, 'usr', 'local', 'bin')
1302 to_framework = os.path.join('..', '..', '..', 'Library', 'Frameworks',
1303 'Python.framework', 'Versions', version, 'bin')
1304 if os.path.exists(usr_local_bin):
1305 shutil.rmtree(usr_local_bin)
1306 os.makedirs(usr_local_bin)
1307 for fn in os.listdir(
1308 os.path.join(frmDir, 'Versions', version, 'bin')):
1309 os.symlink(os.path.join(to_framework, fn),
1310 os.path.join(usr_local_bin, fn))
1311
1312 os.chdir(curdir)
1313
1314 if PYTHON_3:
1315 # Remove the 'Current' link, that way we don't accidentally mess
1316 # with an already installed version of python 2
1317 os.unlink(os.path.join(rootDir, 'Library', 'Frameworks',
1318 'Python.framework', 'Versions', 'Current'))
1319
1320 def patchFile(inPath, outPath):
1321 data = fileContents(inPath)
1322 data = data.replace('$FULL_VERSION', getFullVersion())
1323 data = data.replace('$VERSION', getVersion())
1324 data = data.replace('$MACOSX_DEPLOYMENT_TARGET', ''.join((DEPTARGET, ' or later')))
1325 data = data.replace('$ARCHITECTURES', ", ".join(universal_opts_map[UNIVERSALARCHS]))
1326 data = data.replace('$INSTALL_SIZE', installSize())
1327 data = data.replace('$THIRD_PARTY_LIBS', "\\\n".join(THIRD_PARTY_LIBS))
1328
1329 # This one is not handy as a template variable
1330 data = data.replace('$PYTHONFRAMEWORKINSTALLDIR', '/Library/Frameworks/Python.framework')
1331 fp = open(outPath, 'w')
1332 fp.write(data)
1333 fp.close()
1334
1335 def patchScript(inPath, outPath):
1336 major, minor = getVersionMajorMinor()
1337 data = fileContents(inPath)
1338 data = data.replace('@PYMAJOR@', str(major))
1339 data = data.replace('@PYVER@', getVersion())
1340 fp = open(outPath, 'w')
1341 fp.write(data)
1342 fp.close()
1343 os.chmod(outPath, STAT_0o755)
1344
1345
1346
1347 def packageFromRecipe(targetDir, recipe):
1348 curdir = os.getcwd()
1349 try:
1350 # The major version (such as 2.5) is included in the package name
1351 # because having two version of python installed at the same time is
1352 # common.
1353 pkgname = '%s-%s'%(recipe['name'], getVersion())
1354 srcdir = recipe.get('source')
1355 pkgroot = recipe.get('topdir', srcdir)
1356 postflight = recipe.get('postflight')
1357 readme = textwrap.dedent(recipe['readme'])
1358 isRequired = recipe.get('required', True)
1359
1360 print("- building package %s"%(pkgname,))
1361
1362 # Substitute some variables
1363 textvars = dict(
1364 VER=getVersion(),
1365 FULLVER=getFullVersion(),
1366 )
1367 readme = readme % textvars
1368
1369 if pkgroot is not None:
1370 pkgroot = pkgroot % textvars
1371 else:
1372 pkgroot = '/'
1373
1374 if srcdir is not None:
1375 srcdir = os.path.join(WORKDIR, '_root', srcdir[1:])
1376 srcdir = srcdir % textvars
1377
1378 if postflight is not None:
1379 postflight = os.path.abspath(postflight)
1380
1381 packageContents = os.path.join(targetDir, pkgname + '.pkg', 'Contents')
1382 os.makedirs(packageContents)
1383
1384 if srcdir is not None:
1385 os.chdir(srcdir)
1386 runCommand("pax -wf %s . 2>&1"%(shellQuote(os.path.join(packageContents, 'Archive.pax')),))
1387 runCommand("gzip -9 %s 2>&1"%(shellQuote(os.path.join(packageContents, 'Archive.pax')),))
1388 runCommand("mkbom . %s 2>&1"%(shellQuote(os.path.join(packageContents, 'Archive.bom')),))
1389
1390 fn = os.path.join(packageContents, 'PkgInfo')
1391 fp = open(fn, 'w')
1392 fp.write('pmkrpkg1')
1393 fp.close()
1394
1395 rsrcDir = os.path.join(packageContents, "Resources")
1396 os.mkdir(rsrcDir)
1397 fp = open(os.path.join(rsrcDir, 'ReadMe.txt'), 'w')
1398 fp.write(readme)
1399 fp.close()
1400
1401 if postflight is not None:
1402 patchScript(postflight, os.path.join(rsrcDir, 'postflight'))
1403
1404 vers = getFullVersion()
1405 major, minor = getVersionMajorMinor()
1406 pl = Plist(
1407 CFBundleGetInfoString="Python.%s %s"%(pkgname, vers,),
1408 CFBundleIdentifier='org.python.Python.%s'%(pkgname,),
1409 CFBundleName='Python.%s'%(pkgname,),
1410 CFBundleShortVersionString=vers,
1411 IFMajorVersion=major,
1412 IFMinorVersion=minor,
1413 IFPkgFormatVersion=0.10000000149011612,
1414 IFPkgFlagAllowBackRev=False,
1415 IFPkgFlagAuthorizationAction="RootAuthorization",
1416 IFPkgFlagDefaultLocation=pkgroot,
1417 IFPkgFlagFollowLinks=True,
1418 IFPkgFlagInstallFat=True,
1419 IFPkgFlagIsRequired=isRequired,
1420 IFPkgFlagOverwritePermissions=False,
1421 IFPkgFlagRelocatable=False,
1422 IFPkgFlagRestartAction="NoRestart",
1423 IFPkgFlagRootVolumeOnly=True,
1424 IFPkgFlagUpdateInstalledLangauges=False,
1425 )
1426 writePlist(pl, os.path.join(packageContents, 'Info.plist'))
1427
1428 pl = Plist(
1429 IFPkgDescriptionDescription=readme,
1430 IFPkgDescriptionTitle=recipe.get('long_name', "Python.%s"%(pkgname,)),
1431 IFPkgDescriptionVersion=vers,
1432 )
1433 writePlist(pl, os.path.join(packageContents, 'Resources', 'Description.plist'))
1434
1435 finally:
1436 os.chdir(curdir)
1437
1438
1439 def makeMpkgPlist(path):
1440
1441 vers = getFullVersion()
1442 major, minor = getVersionMajorMinor()
1443
1444 pl = Plist(
1445 CFBundleGetInfoString="Python %s"%(vers,),
1446 CFBundleIdentifier='org.python.Python',
1447 CFBundleName='Python',
1448 CFBundleShortVersionString=vers,
1449 IFMajorVersion=major,
1450 IFMinorVersion=minor,
1451 IFPkgFlagComponentDirectory="Contents/Packages",
1452 IFPkgFlagPackageList=[
1453 dict(
1454 IFPkgFlagPackageLocation='%s-%s.pkg'%(item['name'], getVersion()),
1455 IFPkgFlagPackageSelection=item.get('selected', 'selected'),
1456 )
1457 for item in pkg_recipes()
1458 ],
1459 IFPkgFormatVersion=0.10000000149011612,
1460 IFPkgFlagBackgroundScaling="proportional",
1461 IFPkgFlagBackgroundAlignment="left",
1462 IFPkgFlagAuthorizationAction="RootAuthorization",
1463 )
1464
1465 writePlist(pl, path)
1466
1467
1468 def buildInstaller():
1469
1470 # Zap all compiled files
1471 for dirpath, _, filenames in os.walk(os.path.join(WORKDIR, '_root')):
1472 for fn in filenames:
1473 if fn.endswith('.pyc') or fn.endswith('.pyo'):
1474 os.unlink(os.path.join(dirpath, fn))
1475
1476 outdir = os.path.join(WORKDIR, 'installer')
1477 if os.path.exists(outdir):
1478 shutil.rmtree(outdir)
1479 os.mkdir(outdir)
1480
1481 pkgroot = os.path.join(outdir, 'Python.mpkg', 'Contents')
1482 pkgcontents = os.path.join(pkgroot, 'Packages')
1483 os.makedirs(pkgcontents)
1484 for recipe in pkg_recipes():
1485 packageFromRecipe(pkgcontents, recipe)
1486
1487 rsrcDir = os.path.join(pkgroot, 'Resources')
1488
1489 fn = os.path.join(pkgroot, 'PkgInfo')
1490 fp = open(fn, 'w')
1491 fp.write('pmkrpkg1')
1492 fp.close()
1493
1494 os.mkdir(rsrcDir)
1495
1496 makeMpkgPlist(os.path.join(pkgroot, 'Info.plist'))
1497 pl = Plist(
1498 IFPkgDescriptionTitle="Python",
1499 IFPkgDescriptionVersion=getVersion(),
1500 )
1501
1502 writePlist(pl, os.path.join(pkgroot, 'Resources', 'Description.plist'))
1503 for fn in os.listdir('resources'):
1504 if fn == '.svn': continue
1505 if fn.endswith('.jpg'):
1506 shutil.copy(os.path.join('resources', fn), os.path.join(rsrcDir, fn))
1507 else:
1508 patchFile(os.path.join('resources', fn), os.path.join(rsrcDir, fn))
1509
1510
1511 def installSize(clear=False, _saved=[]):
1512 if clear:
1513 del _saved[:]
1514 if not _saved:
1515 data = captureCommand("du -ks %s"%(
1516 shellQuote(os.path.join(WORKDIR, '_root'))))
1517 _saved.append("%d"%((0.5 + (int(data.split()[0]) / 1024.0)),))
1518 return _saved[0]
1519
1520
1521 def buildDMG():
1522 """
1523 Create DMG containing the rootDir.
1524 """
1525 outdir = os.path.join(WORKDIR, 'diskimage')
1526 if os.path.exists(outdir):
1527 shutil.rmtree(outdir)
1528
1529 imagepath = os.path.join(outdir,
1530 'python-%s-macosx%s'%(getFullVersion(),DEPTARGET))
1531 if INCLUDE_TIMESTAMP:
1532 imagepath = imagepath + '-%04d-%02d-%02d'%(time.localtime()[:3])
1533 imagepath = imagepath + '.dmg'
1534
1535 os.mkdir(outdir)
1536
1537 # Try to mitigate race condition in certain versions of macOS, e.g. 10.9,
1538 # when hdiutil create fails with "Resource busy". For now, just retry
1539 # the create a few times and hope that it eventually works.
1540
1541 volname='Python %s'%(getFullVersion())
1542 cmd = ("hdiutil create -format UDRW -volname %s -srcfolder %s -size 100m %s"%(
1543 shellQuote(volname),
1544 shellQuote(os.path.join(WORKDIR, 'installer')),
1545 shellQuote(imagepath + ".tmp.dmg" )))
1546 for i in range(5):
1547 fd = os.popen(cmd, 'r')
1548 data = fd.read()
1549 xit = fd.close()
1550 if not xit:
1551 break
1552 sys.stdout.write(data)
1553 print(" -- retrying hdiutil create")
1554 time.sleep(5)
1555 else:
1556 raise RuntimeError("command failed: %s"%(cmd,))
1557
1558 if not os.path.exists(os.path.join(WORKDIR, "mnt")):
1559 os.mkdir(os.path.join(WORKDIR, "mnt"))
1560 runCommand("hdiutil attach %s -mountroot %s"%(
1561 shellQuote(imagepath + ".tmp.dmg"), shellQuote(os.path.join(WORKDIR, "mnt"))))
1562
1563 # Custom icon for the DMG, shown when the DMG is mounted.
1564 shutil.copy("../Icons/Disk Image.icns",
1565 os.path.join(WORKDIR, "mnt", volname, ".VolumeIcon.icns"))
1566 runCommand("SetFile -a C %s/"%(
1567 shellQuote(os.path.join(WORKDIR, "mnt", volname)),))
1568
1569 runCommand("hdiutil detach %s"%(shellQuote(os.path.join(WORKDIR, "mnt", volname))))
1570
1571 setIcon(imagepath + ".tmp.dmg", "../Icons/Disk Image.icns")
1572 runCommand("hdiutil convert %s -format UDZO -o %s"%(
1573 shellQuote(imagepath + ".tmp.dmg"), shellQuote(imagepath)))
1574 setIcon(imagepath, "../Icons/Disk Image.icns")
1575
1576 os.unlink(imagepath + ".tmp.dmg")
1577
1578 return imagepath
1579
1580
1581 def setIcon(filePath, icnsPath):
1582 """
1583 Set the custom icon for the specified file or directory.
1584 """
1585
1586 dirPath = os.path.normpath(os.path.dirname(__file__))
1587 toolPath = os.path.join(dirPath, "seticon.app/Contents/MacOS/seticon")
1588 if not os.path.exists(toolPath) or os.stat(toolPath).st_mtime < os.stat(dirPath + '/seticon.m').st_mtime:
1589 # NOTE: The tool is created inside an .app bundle, otherwise it won't work due
1590 # to connections to the window server.
1591 appPath = os.path.join(dirPath, "seticon.app/Contents/MacOS")
1592 if not os.path.exists(appPath):
1593 os.makedirs(appPath)
1594 runCommand("cc -o %s %s/seticon.m -framework Cocoa"%(
1595 shellQuote(toolPath), shellQuote(dirPath)))
1596
1597 runCommand("%s %s %s"%(shellQuote(os.path.abspath(toolPath)), shellQuote(icnsPath),
1598 shellQuote(filePath)))
1599
1600 def main():
1601 # First parse options and check if we can perform our work
1602 parseOptions()
1603 checkEnvironment()
1604
1605 os.environ['MACOSX_DEPLOYMENT_TARGET'] = DEPTARGET
1606 os.environ['CC'] = CC
1607 os.environ['CXX'] = CXX
1608
1609 if os.path.exists(WORKDIR):
1610 shutil.rmtree(WORKDIR)
1611 os.mkdir(WORKDIR)
1612
1613 os.environ['LC_ALL'] = 'C'
1614
1615 # Then build third-party libraries such as sleepycat DB4.
1616 buildLibraries()
1617
1618 # Now build python itself
1619 buildPython()
1620
1621 # And then build the documentation
1622 # Remove the Deployment Target from the shell
1623 # environment, it's no longer needed and
1624 # an unexpected build target can cause problems
1625 # when Sphinx and its dependencies need to
1626 # be (re-)installed.
1627 del os.environ['MACOSX_DEPLOYMENT_TARGET']
1628 buildPythonDocs()
1629
1630
1631 # Prepare the applications folder
1632 folder = os.path.join(WORKDIR, "_root", "Applications", "Python %s"%(
1633 getVersion(),))
1634 fn = os.path.join(folder, "License.rtf")
1635 patchFile("resources/License.rtf", fn)
1636 fn = os.path.join(folder, "ReadMe.rtf")
1637 patchFile("resources/ReadMe.rtf", fn)
1638 fn = os.path.join(folder, "Update Shell Profile.command")
1639 patchScript("scripts/postflight.patch-profile", fn)
1640 fn = os.path.join(folder, "Install Certificates.command")
1641 patchScript("resources/install_certificates.command", fn)
1642 os.chmod(folder, STAT_0o755)
1643 setIcon(folder, "../Icons/Python Folder.icns")
1644
1645 # Create the installer
1646 buildInstaller()
1647
1648 # And copy the readme into the directory containing the installer
1649 patchFile('resources/ReadMe.rtf',
1650 os.path.join(WORKDIR, 'installer', 'ReadMe.rtf'))
1651
1652 # Ditto for the license file.
1653 patchFile('resources/License.rtf',
1654 os.path.join(WORKDIR, 'installer', 'License.rtf'))
1655
1656 fp = open(os.path.join(WORKDIR, 'installer', 'Build.txt'), 'w')
1657 fp.write("# BUILD INFO\n")
1658 fp.write("# Date: %s\n" % time.ctime())
1659 fp.write("# By: %s\n" % pwd.getpwuid(os.getuid()).pw_gecos)
1660 fp.close()
1661
1662 # And copy it to a DMG
1663 buildDMG()
1664
1665 if __name__ == "__main__":
1666 main()