/Mac/BuildScript/build-installer.py

http://unladen-swallow.googlecode.com/ · Python · 1114 lines · 927 code · 110 blank · 77 comment · 42 complexity · b3f165df34c8d533c4f8e7f0e452b33d MD5 · raw file

  1. #!/usr/bin/python
  2. """
  3. This script is used to build the "official unofficial" universal build on
  4. Mac OS X. It requires Mac OS X 10.4, Xcode 2.2 and the 10.4u SDK to do its
  5. work. 64-bit or four-way universal builds require at least OS X 10.5 and
  6. the 10.5 SDK.
  7. Please ensure that this script keeps working with Python 2.3, to avoid
  8. bootstrap issues (/usr/bin/python is Python 2.3 on OSX 10.4)
  9. Usage: see USAGE variable in the script.
  10. """
  11. import platform, os, sys, getopt, textwrap, shutil, urllib2, stat, time, pwd
  12. import grp
  13. INCLUDE_TIMESTAMP = 1
  14. VERBOSE = 1
  15. from plistlib import Plist
  16. import MacOS
  17. try:
  18. from plistlib import writePlist
  19. except ImportError:
  20. # We're run using python2.3
  21. def writePlist(plist, path):
  22. plist.write(path)
  23. def shellQuote(value):
  24. """
  25. Return the string value in a form that can safely be inserted into
  26. a shell command.
  27. """
  28. return "'%s'"%(value.replace("'", "'\"'\"'"))
  29. def grepValue(fn, variable):
  30. variable = variable + '='
  31. for ln in open(fn, 'r'):
  32. if ln.startswith(variable):
  33. value = ln[len(variable):].strip()
  34. return value[1:-1]
  35. def getVersion():
  36. return grepValue(os.path.join(SRCDIR, 'configure'), 'PACKAGE_VERSION')
  37. def getFullVersion():
  38. fn = os.path.join(SRCDIR, 'Include', 'patchlevel.h')
  39. for ln in open(fn):
  40. if 'PY_VERSION' in ln:
  41. return ln.split()[-1][1:-1]
  42. raise RuntimeError, "Cannot find full version??"
  43. # The directory we'll use to create the build (will be erased and recreated)
  44. WORKDIR = "/tmp/_py"
  45. # The directory we'll use to store third-party sources. Set this to something
  46. # else if you don't want to re-fetch required libraries every time.
  47. DEPSRC = os.path.join(WORKDIR, 'third-party')
  48. DEPSRC = os.path.expanduser('~/Universal/other-sources')
  49. # Location of the preferred SDK
  50. ### There are some issues with the SDK selection below here,
  51. ### The resulting binary doesn't work on all platforms that
  52. ### it should. Always default to the 10.4u SDK until that
  53. ### isue is resolved.
  54. ###
  55. ##if int(os.uname()[2].split('.')[0]) == 8:
  56. ## # Explicitly use the 10.4u (universal) SDK when
  57. ## # building on 10.4, the system headers are not
  58. ## # useable for a universal build
  59. ## SDKPATH = "/Developer/SDKs/MacOSX10.4u.sdk"
  60. ##else:
  61. ## SDKPATH = "/"
  62. SDKPATH = "/Developer/SDKs/MacOSX10.4u.sdk"
  63. universal_opts_map = { '32-bit': ('i386', 'ppc',),
  64. '64-bit': ('x86_64', 'ppc64',),
  65. 'intel': ('i386', 'x86_64'),
  66. '3-way': ('ppc', 'i386', 'x86_64'),
  67. 'all': ('i386', 'ppc', 'x86_64', 'ppc64',) }
  68. default_target_map = {
  69. '64-bit': '10.5',
  70. '3-way': '10.5',
  71. 'intel': '10.5',
  72. 'all': '10.5',
  73. }
  74. UNIVERSALOPTS = tuple(universal_opts_map.keys())
  75. UNIVERSALARCHS = '32-bit'
  76. ARCHLIST = universal_opts_map[UNIVERSALARCHS]
  77. # Source directory (asume we're in Mac/BuildScript)
  78. SRCDIR = os.path.dirname(
  79. os.path.dirname(
  80. os.path.dirname(
  81. os.path.abspath(__file__
  82. ))))
  83. # $MACOSX_DEPLOYMENT_TARGET -> minimum OS X level
  84. DEPTARGET = '10.3'
  85. target_cc_map = {
  86. '10.3': 'gcc-4.0',
  87. '10.4': 'gcc-4.0',
  88. '10.5': 'gcc-4.0',
  89. '10.6': 'gcc-4.2',
  90. }
  91. CC = target_cc_map[DEPTARGET]
  92. USAGE = textwrap.dedent("""\
  93. Usage: build_python [options]
  94. Options:
  95. -? or -h: Show this message
  96. -b DIR
  97. --build-dir=DIR: Create build here (default: %(WORKDIR)r)
  98. --third-party=DIR: Store third-party sources here (default: %(DEPSRC)r)
  99. --sdk-path=DIR: Location of the SDK (default: %(SDKPATH)r)
  100. --src-dir=DIR: Location of the Python sources (default: %(SRCDIR)r)
  101. --dep-target=10.n OS X deployment target (default: %(DEPTARGET)r)
  102. --universal-archs=x universal architectures (options: %(UNIVERSALOPTS)r, default: %(UNIVERSALARCHS)r)
  103. """)% globals()
  104. # Instructions for building libraries that are necessary for building a
  105. # batteries included python.
  106. # [The recipes are defined here for convenience but instantiated later after
  107. # command line options have been processed.]
  108. def library_recipes():
  109. result = []
  110. if DEPTARGET < '10.5':
  111. result.extend([
  112. dict(
  113. name="Bzip2 1.0.5",
  114. url="http://www.bzip.org/1.0.5/bzip2-1.0.5.tar.gz",
  115. checksum='3c15a0c8d1d3ee1c46a1634d00617b1a',
  116. configure=None,
  117. install='make install CC=%s PREFIX=%s/usr/local/ CFLAGS="-arch %s -isysroot %s"'%(
  118. CC,
  119. shellQuote(os.path.join(WORKDIR, 'libraries')),
  120. ' -arch '.join(ARCHLIST),
  121. SDKPATH,
  122. ),
  123. ),
  124. dict(
  125. name="ZLib 1.2.3",
  126. url="http://www.gzip.org/zlib/zlib-1.2.3.tar.gz",
  127. checksum='debc62758716a169df9f62e6ab2bc634',
  128. configure=None,
  129. install='make install CC=%s prefix=%s/usr/local/ CFLAGS="-arch %s -isysroot %s"'%(
  130. CC,
  131. shellQuote(os.path.join(WORKDIR, 'libraries')),
  132. ' -arch '.join(ARCHLIST),
  133. SDKPATH,
  134. ),
  135. ),
  136. dict(
  137. # Note that GNU readline is GPL'd software
  138. name="GNU Readline 5.1.4",
  139. url="http://ftp.gnu.org/pub/gnu/readline/readline-5.1.tar.gz" ,
  140. checksum='7ee5a692db88b30ca48927a13fd60e46',
  141. patchlevel='0',
  142. patches=[
  143. # The readline maintainers don't do actual micro releases, but
  144. # just ship a set of patches.
  145. 'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-001',
  146. 'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-002',
  147. 'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-003',
  148. 'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-004',
  149. ]
  150. ),
  151. dict(
  152. name="SQLite 3.6.11",
  153. url="http://www.sqlite.org/sqlite-3.6.11.tar.gz",
  154. checksum='7ebb099696ab76cc6ff65dd496d17858',
  155. configure_pre=[
  156. '--enable-threadsafe',
  157. '--enable-tempstore',
  158. '--enable-shared=no',
  159. '--enable-static=yes',
  160. '--disable-tcl',
  161. ]
  162. ),
  163. dict(
  164. name="NCurses 5.5",
  165. url="http://ftp.gnu.org/pub/gnu/ncurses/ncurses-5.5.tar.gz",
  166. checksum='e73c1ac10b4bfc46db43b2ddfd6244ef',
  167. configure_pre=[
  168. "--without-cxx",
  169. "--without-ada",
  170. "--without-progs",
  171. "--without-curses-h",
  172. "--enable-shared",
  173. "--with-shared",
  174. "--datadir=/usr/share",
  175. "--sysconfdir=/etc",
  176. "--sharedstatedir=/usr/com",
  177. "--with-terminfo-dirs=/usr/share/terminfo",
  178. "--with-default-terminfo-dir=/usr/share/terminfo",
  179. "--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib"%(getVersion(),),
  180. "--enable-termcap",
  181. ],
  182. patches=[
  183. "ncurses-5.5.patch",
  184. ],
  185. useLDFlags=False,
  186. install='make && make install DESTDIR=%s && cd %s/usr/local/lib && ln -fs ../../../Library/Frameworks/Python.framework/Versions/%s/lib/lib* .'%(
  187. shellQuote(os.path.join(WORKDIR, 'libraries')),
  188. shellQuote(os.path.join(WORKDIR, 'libraries')),
  189. getVersion(),
  190. ),
  191. ),
  192. ])
  193. result.extend([
  194. dict(
  195. name="Sleepycat DB 4.7.25",
  196. url="http://download.oracle.com/berkeley-db/db-4.7.25.tar.gz",
  197. checksum='ec2b87e833779681a0c3a814aa71359e',
  198. buildDir="build_unix",
  199. configure="../dist/configure",
  200. configure_pre=[
  201. '--includedir=/usr/local/include/db4',
  202. ]
  203. ),
  204. ])
  205. return result
  206. # Instructions for building packages inside the .mpkg.
  207. def pkg_recipes():
  208. result = [
  209. dict(
  210. name="PythonFramework",
  211. long_name="Python Framework",
  212. source="/Library/Frameworks/Python.framework",
  213. readme="""\
  214. This package installs Python.framework, that is the python
  215. interpreter and the standard library. This also includes Python
  216. wrappers for lots of Mac OS X API's.
  217. """,
  218. postflight="scripts/postflight.framework",
  219. ),
  220. dict(
  221. name="PythonApplications",
  222. long_name="GUI Applications",
  223. source="/Applications/Python %(VER)s",
  224. readme="""\
  225. This package installs IDLE (an interactive Python IDE),
  226. Python Launcher and Build Applet (create application bundles
  227. from python scripts).
  228. It also installs a number of examples and demos.
  229. """,
  230. required=False,
  231. ),
  232. dict(
  233. name="PythonUnixTools",
  234. long_name="UNIX command-line tools",
  235. source="/usr/local/bin",
  236. readme="""\
  237. This package installs the unix tools in /usr/local/bin for
  238. compatibility with older releases of Python. This package
  239. is not necessary to use Python.
  240. """,
  241. required=False,
  242. ),
  243. dict(
  244. name="PythonDocumentation",
  245. long_name="Python Documentation",
  246. topdir="/Library/Frameworks/Python.framework/Versions/%(VER)s/Resources/English.lproj/Documentation",
  247. source="/pydocs",
  248. readme="""\
  249. This package installs the python documentation at a location
  250. that is useable for pydoc and IDLE. If you have installed Xcode
  251. it will also install a link to the documentation in
  252. /Developer/Documentation/Python
  253. """,
  254. postflight="scripts/postflight.documentation",
  255. required=False,
  256. ),
  257. dict(
  258. name="PythonProfileChanges",
  259. long_name="Shell profile updater",
  260. readme="""\
  261. This packages updates your shell profile to make sure that
  262. the Python tools are found by your shell in preference of
  263. the system provided Python tools.
  264. If you don't install this package you'll have to add
  265. "/Library/Frameworks/Python.framework/Versions/%(VER)s/bin"
  266. to your PATH by hand.
  267. """,
  268. postflight="scripts/postflight.patch-profile",
  269. topdir="/Library/Frameworks/Python.framework",
  270. source="/empty-dir",
  271. required=False,
  272. ),
  273. ]
  274. if DEPTARGET < '10.4':
  275. result.append(
  276. dict(
  277. name="PythonSystemFixes",
  278. long_name="Fix system Python",
  279. readme="""\
  280. This package updates the system python installation on
  281. Mac OS X 10.3 to ensure that you can build new python extensions
  282. using that copy of python after installing this version.
  283. """,
  284. postflight="../Tools/fixapplepython23.py",
  285. topdir="/Library/Frameworks/Python.framework",
  286. source="/empty-dir",
  287. required=False,
  288. )
  289. )
  290. return result
  291. def fatal(msg):
  292. """
  293. A fatal error, bail out.
  294. """
  295. sys.stderr.write('FATAL: ')
  296. sys.stderr.write(msg)
  297. sys.stderr.write('\n')
  298. sys.exit(1)
  299. def fileContents(fn):
  300. """
  301. Return the contents of the named file
  302. """
  303. return open(fn, 'rb').read()
  304. def runCommand(commandline):
  305. """
  306. Run a command and raise RuntimeError if it fails. Output is surpressed
  307. unless the command fails.
  308. """
  309. fd = os.popen(commandline, 'r')
  310. data = fd.read()
  311. xit = fd.close()
  312. if xit is not None:
  313. sys.stdout.write(data)
  314. raise RuntimeError, "command failed: %s"%(commandline,)
  315. if VERBOSE:
  316. sys.stdout.write(data); sys.stdout.flush()
  317. def captureCommand(commandline):
  318. fd = os.popen(commandline, 'r')
  319. data = fd.read()
  320. xit = fd.close()
  321. if xit is not None:
  322. sys.stdout.write(data)
  323. raise RuntimeError, "command failed: %s"%(commandline,)
  324. return data
  325. def checkEnvironment():
  326. """
  327. Check that we're running on a supported system.
  328. """
  329. if platform.system() != 'Darwin':
  330. fatal("This script should be run on a Mac OS X 10.4 (or later) system")
  331. if int(platform.release().split('.')[0]) < 8:
  332. fatal("This script should be run on a Mac OS X 10.4 (or later) system")
  333. if not os.path.exists(SDKPATH):
  334. fatal("Please install the latest version of Xcode and the %s SDK"%(
  335. os.path.basename(SDKPATH[:-4])))
  336. def parseOptions(args=None):
  337. """
  338. Parse arguments and update global settings.
  339. """
  340. global WORKDIR, DEPSRC, SDKPATH, SRCDIR, DEPTARGET
  341. global UNIVERSALOPTS, UNIVERSALARCHS, ARCHLIST, CC
  342. if args is None:
  343. args = sys.argv[1:]
  344. try:
  345. options, args = getopt.getopt(args, '?hb',
  346. [ 'build-dir=', 'third-party=', 'sdk-path=' , 'src-dir=',
  347. 'dep-target=', 'universal-archs=', 'help' ])
  348. except getopt.error, msg:
  349. print msg
  350. sys.exit(1)
  351. if args:
  352. print "Additional arguments"
  353. sys.exit(1)
  354. deptarget = None
  355. for k, v in options:
  356. if k in ('-h', '-?', '--help'):
  357. print USAGE
  358. sys.exit(0)
  359. elif k in ('-d', '--build-dir'):
  360. WORKDIR=v
  361. elif k in ('--third-party',):
  362. DEPSRC=v
  363. elif k in ('--sdk-path',):
  364. SDKPATH=v
  365. elif k in ('--src-dir',):
  366. SRCDIR=v
  367. elif k in ('--dep-target', ):
  368. DEPTARGET=v
  369. deptarget=v
  370. elif k in ('--universal-archs', ):
  371. if v in UNIVERSALOPTS:
  372. UNIVERSALARCHS = v
  373. ARCHLIST = universal_opts_map[UNIVERSALARCHS]
  374. if deptarget is None:
  375. # Select alternate default deployment
  376. # target
  377. DEPTARGET = default_target_map.get(v, '10.3')
  378. else:
  379. raise NotImplementedError, v
  380. else:
  381. raise NotImplementedError, k
  382. SRCDIR=os.path.abspath(SRCDIR)
  383. WORKDIR=os.path.abspath(WORKDIR)
  384. SDKPATH=os.path.abspath(SDKPATH)
  385. DEPSRC=os.path.abspath(DEPSRC)
  386. CC=target_cc_map[DEPTARGET]
  387. print "Settings:"
  388. print " * Source directory:", SRCDIR
  389. print " * Build directory: ", WORKDIR
  390. print " * SDK location: ", SDKPATH
  391. print " * Third-party source:", DEPSRC
  392. print " * Deployment target:", DEPTARGET
  393. print " * Universal architectures:", ARCHLIST
  394. print " * C compiler:", CC
  395. print ""
  396. def extractArchive(builddir, archiveName):
  397. """
  398. Extract a source archive into 'builddir'. Returns the path of the
  399. extracted archive.
  400. XXX: This function assumes that archives contain a toplevel directory
  401. that is has the same name as the basename of the archive. This is
  402. save enough for anything we use.
  403. """
  404. curdir = os.getcwd()
  405. try:
  406. os.chdir(builddir)
  407. if archiveName.endswith('.tar.gz'):
  408. retval = os.path.basename(archiveName[:-7])
  409. if os.path.exists(retval):
  410. shutil.rmtree(retval)
  411. fp = os.popen("tar zxf %s 2>&1"%(shellQuote(archiveName),), 'r')
  412. elif archiveName.endswith('.tar.bz2'):
  413. retval = os.path.basename(archiveName[:-8])
  414. if os.path.exists(retval):
  415. shutil.rmtree(retval)
  416. fp = os.popen("tar jxf %s 2>&1"%(shellQuote(archiveName),), 'r')
  417. elif archiveName.endswith('.tar'):
  418. retval = os.path.basename(archiveName[:-4])
  419. if os.path.exists(retval):
  420. shutil.rmtree(retval)
  421. fp = os.popen("tar xf %s 2>&1"%(shellQuote(archiveName),), 'r')
  422. elif archiveName.endswith('.zip'):
  423. retval = os.path.basename(archiveName[:-4])
  424. if os.path.exists(retval):
  425. shutil.rmtree(retval)
  426. fp = os.popen("unzip %s 2>&1"%(shellQuote(archiveName),), 'r')
  427. data = fp.read()
  428. xit = fp.close()
  429. if xit is not None:
  430. sys.stdout.write(data)
  431. raise RuntimeError, "Cannot extract %s"%(archiveName,)
  432. return os.path.join(builddir, retval)
  433. finally:
  434. os.chdir(curdir)
  435. KNOWNSIZES = {
  436. "http://ftp.gnu.org/pub/gnu/readline/readline-5.1.tar.gz": 7952742,
  437. "http://downloads.sleepycat.com/db-4.4.20.tar.gz": 2030276,
  438. }
  439. def downloadURL(url, fname):
  440. """
  441. Download the contents of the url into the file.
  442. """
  443. try:
  444. size = os.path.getsize(fname)
  445. except OSError:
  446. pass
  447. else:
  448. if KNOWNSIZES.get(url) == size:
  449. print "Using existing file for", url
  450. return
  451. fpIn = urllib2.urlopen(url)
  452. fpOut = open(fname, 'wb')
  453. block = fpIn.read(10240)
  454. try:
  455. while block:
  456. fpOut.write(block)
  457. block = fpIn.read(10240)
  458. fpIn.close()
  459. fpOut.close()
  460. except:
  461. try:
  462. os.unlink(fname)
  463. except:
  464. pass
  465. def buildRecipe(recipe, basedir, archList):
  466. """
  467. Build software using a recipe. This function does the
  468. 'configure;make;make install' dance for C software, with a possibility
  469. to customize this process, basically a poor-mans DarwinPorts.
  470. """
  471. curdir = os.getcwd()
  472. name = recipe['name']
  473. url = recipe['url']
  474. configure = recipe.get('configure', './configure')
  475. install = recipe.get('install', 'make && make install DESTDIR=%s'%(
  476. shellQuote(basedir)))
  477. archiveName = os.path.split(url)[-1]
  478. sourceArchive = os.path.join(DEPSRC, archiveName)
  479. if not os.path.exists(DEPSRC):
  480. os.mkdir(DEPSRC)
  481. if os.path.exists(sourceArchive):
  482. print "Using local copy of %s"%(name,)
  483. else:
  484. print "Did not find local copy of %s"%(name,)
  485. print "Downloading %s"%(name,)
  486. downloadURL(url, sourceArchive)
  487. print "Archive for %s stored as %s"%(name, sourceArchive)
  488. print "Extracting archive for %s"%(name,)
  489. buildDir=os.path.join(WORKDIR, '_bld')
  490. if not os.path.exists(buildDir):
  491. os.mkdir(buildDir)
  492. workDir = extractArchive(buildDir, sourceArchive)
  493. os.chdir(workDir)
  494. if 'buildDir' in recipe:
  495. os.chdir(recipe['buildDir'])
  496. for fn in recipe.get('patches', ()):
  497. if fn.startswith('http://'):
  498. # Download the patch before applying it.
  499. path = os.path.join(DEPSRC, os.path.basename(fn))
  500. downloadURL(fn, path)
  501. fn = path
  502. fn = os.path.join(curdir, fn)
  503. runCommand('patch -p%s < %s'%(recipe.get('patchlevel', 1),
  504. shellQuote(fn),))
  505. if configure is not None:
  506. configure_args = [
  507. "--prefix=/usr/local",
  508. "--enable-static",
  509. "--disable-shared",
  510. #"CPP=gcc -arch %s -E"%(' -arch '.join(archList,),),
  511. ]
  512. if 'configure_pre' in recipe:
  513. args = list(recipe['configure_pre'])
  514. if '--disable-static' in args:
  515. configure_args.remove('--enable-static')
  516. if '--enable-shared' in args:
  517. configure_args.remove('--disable-shared')
  518. configure_args.extend(args)
  519. if recipe.get('useLDFlags', 1):
  520. configure_args.extend([
  521. "CFLAGS=-arch %s -isysroot %s -I%s/usr/local/include"%(
  522. ' -arch '.join(archList),
  523. shellQuote(SDKPATH)[1:-1],
  524. shellQuote(basedir)[1:-1],),
  525. "LDFLAGS=-syslibroot,%s -L%s/usr/local/lib -arch %s"%(
  526. shellQuote(SDKPATH)[1:-1],
  527. shellQuote(basedir)[1:-1],
  528. ' -arch '.join(archList)),
  529. ])
  530. else:
  531. configure_args.extend([
  532. "CFLAGS=-arch %s -isysroot %s -I%s/usr/local/include"%(
  533. ' -arch '.join(archList),
  534. shellQuote(SDKPATH)[1:-1],
  535. shellQuote(basedir)[1:-1],),
  536. ])
  537. if 'configure_post' in recipe:
  538. configure_args = configure_args = list(recipe['configure_post'])
  539. configure_args.insert(0, configure)
  540. configure_args = [ shellQuote(a) for a in configure_args ]
  541. print "Running configure for %s"%(name,)
  542. runCommand(' '.join(configure_args) + ' 2>&1')
  543. print "Running install for %s"%(name,)
  544. runCommand('{ ' + install + ' ;} 2>&1')
  545. print "Done %s"%(name,)
  546. print ""
  547. os.chdir(curdir)
  548. def buildLibraries():
  549. """
  550. Build our dependencies into $WORKDIR/libraries/usr/local
  551. """
  552. print ""
  553. print "Building required libraries"
  554. print ""
  555. universal = os.path.join(WORKDIR, 'libraries')
  556. os.mkdir(universal)
  557. os.makedirs(os.path.join(universal, 'usr', 'local', 'lib'))
  558. os.makedirs(os.path.join(universal, 'usr', 'local', 'include'))
  559. for recipe in library_recipes():
  560. buildRecipe(recipe, universal, ARCHLIST)
  561. def buildPythonDocs():
  562. # This stores the documentation as Resources/English.lproj/Documentation
  563. # inside the framwork. pydoc and IDLE will pick it up there.
  564. print "Install python documentation"
  565. rootDir = os.path.join(WORKDIR, '_root')
  566. buildDir = os.path.join('../../Doc')
  567. docdir = os.path.join(rootDir, 'pydocs')
  568. curDir = os.getcwd()
  569. os.chdir(buildDir)
  570. runCommand('make update')
  571. runCommand('make html')
  572. os.chdir(curDir)
  573. if not os.path.exists(docdir):
  574. os.mkdir(docdir)
  575. os.rename(os.path.join(buildDir, 'build', 'html'), docdir)
  576. def buildPython():
  577. print "Building a universal python for %s architectures" % UNIVERSALARCHS
  578. buildDir = os.path.join(WORKDIR, '_bld', 'python')
  579. rootDir = os.path.join(WORKDIR, '_root')
  580. if os.path.exists(buildDir):
  581. shutil.rmtree(buildDir)
  582. if os.path.exists(rootDir):
  583. shutil.rmtree(rootDir)
  584. os.mkdir(buildDir)
  585. os.mkdir(rootDir)
  586. os.mkdir(os.path.join(rootDir, 'empty-dir'))
  587. curdir = os.getcwd()
  588. os.chdir(buildDir)
  589. # Not sure if this is still needed, the original build script
  590. # claims that parts of the install assume python.exe exists.
  591. os.symlink('python', os.path.join(buildDir, 'python.exe'))
  592. # Extract the version from the configure file, needed to calculate
  593. # several paths.
  594. version = getVersion()
  595. # Since the extra libs are not in their installed framework location
  596. # during the build, augment the library path so that the interpreter
  597. # will find them during its extension import sanity checks.
  598. os.environ['DYLD_LIBRARY_PATH'] = os.path.join(WORKDIR,
  599. 'libraries', 'usr', 'local', 'lib')
  600. print "Running configure..."
  601. runCommand("%s -C --enable-framework --enable-universalsdk=%s "
  602. "--with-universal-archs=%s "
  603. "LDFLAGS='-g -L%s/libraries/usr/local/lib' "
  604. "OPT='-g -O3 -I%s/libraries/usr/local/include' 2>&1"%(
  605. shellQuote(os.path.join(SRCDIR, 'configure')), shellQuote(SDKPATH),
  606. UNIVERSALARCHS,
  607. shellQuote(WORKDIR)[1:-1],
  608. shellQuote(WORKDIR)[1:-1]))
  609. print "Running make"
  610. runCommand("make")
  611. print "Running make frameworkinstall"
  612. runCommand("make frameworkinstall DESTDIR=%s"%(
  613. shellQuote(rootDir)))
  614. print "Running make frameworkinstallextras"
  615. runCommand("make frameworkinstallextras DESTDIR=%s"%(
  616. shellQuote(rootDir)))
  617. del os.environ['DYLD_LIBRARY_PATH']
  618. print "Copying required shared libraries"
  619. if os.path.exists(os.path.join(WORKDIR, 'libraries', 'Library')):
  620. runCommand("mv %s/* %s"%(
  621. shellQuote(os.path.join(
  622. WORKDIR, 'libraries', 'Library', 'Frameworks',
  623. 'Python.framework', 'Versions', getVersion(),
  624. 'lib')),
  625. shellQuote(os.path.join(WORKDIR, '_root', 'Library', 'Frameworks',
  626. 'Python.framework', 'Versions', getVersion(),
  627. 'lib'))))
  628. print "Fix file modes"
  629. frmDir = os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework')
  630. gid = grp.getgrnam('admin').gr_gid
  631. for dirpath, dirnames, filenames in os.walk(frmDir):
  632. for dn in dirnames:
  633. os.chmod(os.path.join(dirpath, dn), 0775)
  634. os.chown(os.path.join(dirpath, dn), -1, gid)
  635. for fn in filenames:
  636. if os.path.islink(fn):
  637. continue
  638. # "chmod g+w $fn"
  639. p = os.path.join(dirpath, fn)
  640. st = os.stat(p)
  641. os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IWGRP)
  642. os.chown(p, -1, gid)
  643. # We added some directories to the search path during the configure
  644. # phase. Remove those because those directories won't be there on
  645. # the end-users system.
  646. path =os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework',
  647. 'Versions', version, 'lib', 'python%s'%(version,),
  648. 'config', 'Makefile')
  649. fp = open(path, 'r')
  650. data = fp.read()
  651. fp.close()
  652. data = data.replace('-L%s/libraries/usr/local/lib'%(WORKDIR,), '')
  653. data = data.replace('-I%s/libraries/usr/local/include'%(WORKDIR,), '')
  654. fp = open(path, 'w')
  655. fp.write(data)
  656. fp.close()
  657. # Add symlinks in /usr/local/bin, using relative links
  658. usr_local_bin = os.path.join(rootDir, 'usr', 'local', 'bin')
  659. to_framework = os.path.join('..', '..', '..', 'Library', 'Frameworks',
  660. 'Python.framework', 'Versions', version, 'bin')
  661. if os.path.exists(usr_local_bin):
  662. shutil.rmtree(usr_local_bin)
  663. os.makedirs(usr_local_bin)
  664. for fn in os.listdir(
  665. os.path.join(frmDir, 'Versions', version, 'bin')):
  666. os.symlink(os.path.join(to_framework, fn),
  667. os.path.join(usr_local_bin, fn))
  668. os.chdir(curdir)
  669. def patchFile(inPath, outPath):
  670. data = fileContents(inPath)
  671. data = data.replace('$FULL_VERSION', getFullVersion())
  672. data = data.replace('$VERSION', getVersion())
  673. data = data.replace('$MACOSX_DEPLOYMENT_TARGET', ''.join((DEPTARGET, ' or later')))
  674. data = data.replace('$ARCHITECTURES', "i386, ppc")
  675. data = data.replace('$INSTALL_SIZE', installSize())
  676. # This one is not handy as a template variable
  677. data = data.replace('$PYTHONFRAMEWORKINSTALLDIR', '/Library/Frameworks/Python.framework')
  678. fp = open(outPath, 'wb')
  679. fp.write(data)
  680. fp.close()
  681. def patchScript(inPath, outPath):
  682. data = fileContents(inPath)
  683. data = data.replace('@PYVER@', getVersion())
  684. fp = open(outPath, 'wb')
  685. fp.write(data)
  686. fp.close()
  687. os.chmod(outPath, 0755)
  688. def packageFromRecipe(targetDir, recipe):
  689. curdir = os.getcwd()
  690. try:
  691. # The major version (such as 2.5) is included in the package name
  692. # because having two version of python installed at the same time is
  693. # common.
  694. pkgname = '%s-%s'%(recipe['name'], getVersion())
  695. srcdir = recipe.get('source')
  696. pkgroot = recipe.get('topdir', srcdir)
  697. postflight = recipe.get('postflight')
  698. readme = textwrap.dedent(recipe['readme'])
  699. isRequired = recipe.get('required', True)
  700. print "- building package %s"%(pkgname,)
  701. # Substitute some variables
  702. textvars = dict(
  703. VER=getVersion(),
  704. FULLVER=getFullVersion(),
  705. )
  706. readme = readme % textvars
  707. if pkgroot is not None:
  708. pkgroot = pkgroot % textvars
  709. else:
  710. pkgroot = '/'
  711. if srcdir is not None:
  712. srcdir = os.path.join(WORKDIR, '_root', srcdir[1:])
  713. srcdir = srcdir % textvars
  714. if postflight is not None:
  715. postflight = os.path.abspath(postflight)
  716. packageContents = os.path.join(targetDir, pkgname + '.pkg', 'Contents')
  717. os.makedirs(packageContents)
  718. if srcdir is not None:
  719. os.chdir(srcdir)
  720. runCommand("pax -wf %s . 2>&1"%(shellQuote(os.path.join(packageContents, 'Archive.pax')),))
  721. runCommand("gzip -9 %s 2>&1"%(shellQuote(os.path.join(packageContents, 'Archive.pax')),))
  722. runCommand("mkbom . %s 2>&1"%(shellQuote(os.path.join(packageContents, 'Archive.bom')),))
  723. fn = os.path.join(packageContents, 'PkgInfo')
  724. fp = open(fn, 'w')
  725. fp.write('pmkrpkg1')
  726. fp.close()
  727. rsrcDir = os.path.join(packageContents, "Resources")
  728. os.mkdir(rsrcDir)
  729. fp = open(os.path.join(rsrcDir, 'ReadMe.txt'), 'w')
  730. fp.write(readme)
  731. fp.close()
  732. if postflight is not None:
  733. patchScript(postflight, os.path.join(rsrcDir, 'postflight'))
  734. vers = getFullVersion()
  735. major, minor = map(int, getVersion().split('.', 2))
  736. pl = Plist(
  737. CFBundleGetInfoString="Python.%s %s"%(pkgname, vers,),
  738. CFBundleIdentifier='org.python.Python.%s'%(pkgname,),
  739. CFBundleName='Python.%s'%(pkgname,),
  740. CFBundleShortVersionString=vers,
  741. IFMajorVersion=major,
  742. IFMinorVersion=minor,
  743. IFPkgFormatVersion=0.10000000149011612,
  744. IFPkgFlagAllowBackRev=False,
  745. IFPkgFlagAuthorizationAction="RootAuthorization",
  746. IFPkgFlagDefaultLocation=pkgroot,
  747. IFPkgFlagFollowLinks=True,
  748. IFPkgFlagInstallFat=True,
  749. IFPkgFlagIsRequired=isRequired,
  750. IFPkgFlagOverwritePermissions=False,
  751. IFPkgFlagRelocatable=False,
  752. IFPkgFlagRestartAction="NoRestart",
  753. IFPkgFlagRootVolumeOnly=True,
  754. IFPkgFlagUpdateInstalledLangauges=False,
  755. )
  756. writePlist(pl, os.path.join(packageContents, 'Info.plist'))
  757. pl = Plist(
  758. IFPkgDescriptionDescription=readme,
  759. IFPkgDescriptionTitle=recipe.get('long_name', "Python.%s"%(pkgname,)),
  760. IFPkgDescriptionVersion=vers,
  761. )
  762. writePlist(pl, os.path.join(packageContents, 'Resources', 'Description.plist'))
  763. finally:
  764. os.chdir(curdir)
  765. def makeMpkgPlist(path):
  766. vers = getFullVersion()
  767. major, minor = map(int, getVersion().split('.', 2))
  768. pl = Plist(
  769. CFBundleGetInfoString="Python %s"%(vers,),
  770. CFBundleIdentifier='org.python.Python',
  771. CFBundleName='Python',
  772. CFBundleShortVersionString=vers,
  773. IFMajorVersion=major,
  774. IFMinorVersion=minor,
  775. IFPkgFlagComponentDirectory="Contents/Packages",
  776. IFPkgFlagPackageList=[
  777. dict(
  778. IFPkgFlagPackageLocation='%s-%s.pkg'%(item['name'], getVersion()),
  779. IFPkgFlagPackageSelection='selected'
  780. )
  781. for item in pkg_recipes()
  782. ],
  783. IFPkgFormatVersion=0.10000000149011612,
  784. IFPkgFlagBackgroundScaling="proportional",
  785. IFPkgFlagBackgroundAlignment="left",
  786. IFPkgFlagAuthorizationAction="RootAuthorization",
  787. )
  788. writePlist(pl, path)
  789. def buildInstaller():
  790. # Zap all compiled files
  791. for dirpath, _, filenames in os.walk(os.path.join(WORKDIR, '_root')):
  792. for fn in filenames:
  793. if fn.endswith('.pyc') or fn.endswith('.pyo'):
  794. os.unlink(os.path.join(dirpath, fn))
  795. outdir = os.path.join(WORKDIR, 'installer')
  796. if os.path.exists(outdir):
  797. shutil.rmtree(outdir)
  798. os.mkdir(outdir)
  799. pkgroot = os.path.join(outdir, 'Python.mpkg', 'Contents')
  800. pkgcontents = os.path.join(pkgroot, 'Packages')
  801. os.makedirs(pkgcontents)
  802. for recipe in pkg_recipes():
  803. packageFromRecipe(pkgcontents, recipe)
  804. rsrcDir = os.path.join(pkgroot, 'Resources')
  805. fn = os.path.join(pkgroot, 'PkgInfo')
  806. fp = open(fn, 'w')
  807. fp.write('pmkrpkg1')
  808. fp.close()
  809. os.mkdir(rsrcDir)
  810. makeMpkgPlist(os.path.join(pkgroot, 'Info.plist'))
  811. pl = Plist(
  812. IFPkgDescriptionTitle="Python",
  813. IFPkgDescriptionVersion=getVersion(),
  814. )
  815. writePlist(pl, os.path.join(pkgroot, 'Resources', 'Description.plist'))
  816. for fn in os.listdir('resources'):
  817. if fn == '.svn': continue
  818. if fn.endswith('.jpg'):
  819. shutil.copy(os.path.join('resources', fn), os.path.join(rsrcDir, fn))
  820. else:
  821. patchFile(os.path.join('resources', fn), os.path.join(rsrcDir, fn))
  822. shutil.copy("../../LICENSE", os.path.join(rsrcDir, 'License.txt'))
  823. def installSize(clear=False, _saved=[]):
  824. if clear:
  825. del _saved[:]
  826. if not _saved:
  827. data = captureCommand("du -ks %s"%(
  828. shellQuote(os.path.join(WORKDIR, '_root'))))
  829. _saved.append("%d"%((0.5 + (int(data.split()[0]) / 1024.0)),))
  830. return _saved[0]
  831. def buildDMG():
  832. """
  833. Create DMG containing the rootDir.
  834. """
  835. outdir = os.path.join(WORKDIR, 'diskimage')
  836. if os.path.exists(outdir):
  837. shutil.rmtree(outdir)
  838. imagepath = os.path.join(outdir,
  839. 'python-%s-macosx%s'%(getFullVersion(),DEPTARGET))
  840. if INCLUDE_TIMESTAMP:
  841. imagepath = imagepath + '-%04d-%02d-%02d'%(time.localtime()[:3])
  842. imagepath = imagepath + '.dmg'
  843. os.mkdir(outdir)
  844. volname='Python %s'%(getFullVersion())
  845. runCommand("hdiutil create -format UDRW -volname %s -srcfolder %s %s"%(
  846. shellQuote(volname),
  847. shellQuote(os.path.join(WORKDIR, 'installer')),
  848. shellQuote(imagepath + ".tmp.dmg" )))
  849. if not os.path.exists(os.path.join(WORKDIR, "mnt")):
  850. os.mkdir(os.path.join(WORKDIR, "mnt"))
  851. runCommand("hdiutil attach %s -mountroot %s"%(
  852. shellQuote(imagepath + ".tmp.dmg"), shellQuote(os.path.join(WORKDIR, "mnt"))))
  853. # Custom icon for the DMG, shown when the DMG is mounted.
  854. shutil.copy("../Icons/Disk Image.icns",
  855. os.path.join(WORKDIR, "mnt", volname, ".VolumeIcon.icns"))
  856. runCommand("/Developer/Tools/SetFile -a C %s/"%(
  857. shellQuote(os.path.join(WORKDIR, "mnt", volname)),))
  858. runCommand("hdiutil detach %s"%(shellQuote(os.path.join(WORKDIR, "mnt", volname))))
  859. setIcon(imagepath + ".tmp.dmg", "../Icons/Disk Image.icns")
  860. runCommand("hdiutil convert %s -format UDZO -o %s"%(
  861. shellQuote(imagepath + ".tmp.dmg"), shellQuote(imagepath)))
  862. setIcon(imagepath, "../Icons/Disk Image.icns")
  863. os.unlink(imagepath + ".tmp.dmg")
  864. return imagepath
  865. def setIcon(filePath, icnsPath):
  866. """
  867. Set the custom icon for the specified file or directory.
  868. """
  869. toolPath = os.path.join(os.path.dirname(__file__), "seticon.app/Contents/MacOS/seticon")
  870. dirPath = os.path.dirname(__file__)
  871. if not os.path.exists(toolPath) or os.stat(toolPath).st_mtime < os.stat(dirPath + '/seticon.m').st_mtime:
  872. # NOTE: The tool is created inside an .app bundle, otherwise it won't work due
  873. # to connections to the window server.
  874. if not os.path.exists('seticon.app/Contents/MacOS'):
  875. os.makedirs('seticon.app/Contents/MacOS')
  876. runCommand("cc -o %s %s/seticon.m -framework Cocoa"%(
  877. shellQuote(toolPath), shellQuote(dirPath)))
  878. runCommand("%s %s %s"%(shellQuote(os.path.abspath(toolPath)), shellQuote(icnsPath),
  879. shellQuote(filePath)))
  880. def main():
  881. # First parse options and check if we can perform our work
  882. parseOptions()
  883. checkEnvironment()
  884. os.environ['MACOSX_DEPLOYMENT_TARGET'] = DEPTARGET
  885. os.environ['CC'] = CC
  886. if os.path.exists(WORKDIR):
  887. shutil.rmtree(WORKDIR)
  888. os.mkdir(WORKDIR)
  889. # Then build third-party libraries such as sleepycat DB4.
  890. buildLibraries()
  891. # Now build python itself
  892. buildPython()
  893. # And then build the documentation
  894. # Remove the Deployment Target from the shell
  895. # environment, it's no longer needed and
  896. # an unexpected build target can cause problems
  897. # when Sphinx and its dependencies need to
  898. # be (re-)installed.
  899. del os.environ['MACOSX_DEPLOYMENT_TARGET']
  900. buildPythonDocs()
  901. # Prepare the applications folder
  902. fn = os.path.join(WORKDIR, "_root", "Applications",
  903. "Python %s"%(getVersion(),), "Update Shell Profile.command")
  904. patchScript("scripts/postflight.patch-profile", fn)
  905. folder = os.path.join(WORKDIR, "_root", "Applications", "Python %s"%(
  906. getVersion(),))
  907. os.chmod(folder, 0755)
  908. setIcon(folder, "../Icons/Python Folder.icns")
  909. # Create the installer
  910. buildInstaller()
  911. # And copy the readme into the directory containing the installer
  912. patchFile('resources/ReadMe.txt', os.path.join(WORKDIR, 'installer', 'ReadMe.txt'))
  913. # Ditto for the license file.
  914. shutil.copy('../../LICENSE', os.path.join(WORKDIR, 'installer', 'License.txt'))
  915. fp = open(os.path.join(WORKDIR, 'installer', 'Build.txt'), 'w')
  916. print >> fp, "# BUILD INFO"
  917. print >> fp, "# Date:", time.ctime()
  918. print >> fp, "# By:", pwd.getpwuid(os.getuid()).pw_gecos
  919. fp.close()
  920. # And copy it to a DMG
  921. buildDMG()
  922. if __name__ == "__main__":
  923. main()