blob: 9d50f9116f5066a0b5ff2aa857701e04d093fc39 [file] [log] [blame]
Just van Rossumad33d722002-11-21 10:23:04 +00001#! /usr/bin/env python
2
3"""\
4bundlebuilder.py -- Tools to assemble MacOS X (application) bundles.
5
Just van Rossumceeb9622002-11-21 23:19:37 +00006This module contains two classes to build so called "bundles" for
Just van Rossumad33d722002-11-21 10:23:04 +00007MacOS X. BundleBuilder is a general tool, AppBuilder is a subclass
Just van Rossumceeb9622002-11-21 23:19:37 +00008specialized in building application bundles.
Just van Rossumad33d722002-11-21 10:23:04 +00009
Just van Rossumceeb9622002-11-21 23:19:37 +000010[Bundle|App]Builder objects are instantiated with a bunch of keyword
11arguments, and have a build() method that will do all the work. See
12the class doc strings for a description of the constructor arguments.
13
14The module contains a main program that can be used in two ways:
15
16 % python bundlebuilder.py [options] build
17 % python buildapp.py [options] build
18
19Where "buildapp.py" is a user-supplied setup.py-like script following
20this model:
21
22 from bundlebuilder import buildapp
23 buildapp(<lots-of-keyword-args>)
Just van Rossumad33d722002-11-21 10:23:04 +000024
25"""
26
Just van Rossumad33d722002-11-21 10:23:04 +000027
Just van Rossumcef32882002-11-26 00:34:52 +000028__all__ = ["BundleBuilder", "BundleBuilderError", "AppBuilder", "buildapp"]
Just van Rossumad33d722002-11-21 10:23:04 +000029
30
31import sys
32import os, errno, shutil
Just van Rossumcef32882002-11-26 00:34:52 +000033import imp, marshal
34import re
Just van Rossumda302da2002-11-23 22:26:44 +000035from copy import deepcopy
Just van Rossumceeb9622002-11-21 23:19:37 +000036import getopt
Just van Rossumad33d722002-11-21 10:23:04 +000037from plistlib import Plist
Just van Rossumda302da2002-11-23 22:26:44 +000038from types import FunctionType as function
Jack Jansen946c1942003-02-17 16:47:12 +000039import macresource
Just van Rossumad33d722002-11-21 10:23:04 +000040
41
Just van Rossumcef32882002-11-26 00:34:52 +000042class BundleBuilderError(Exception): pass
43
44
Just van Rossumda302da2002-11-23 22:26:44 +000045class Defaults:
46
47 """Class attributes that don't start with an underscore and are
48 not functions or classmethods are (deep)copied to self.__dict__.
49 This allows for mutable default values.
50 """
51
52 def __init__(self, **kwargs):
53 defaults = self._getDefaults()
54 defaults.update(kwargs)
55 self.__dict__.update(defaults)
56
57 def _getDefaults(cls):
58 defaults = {}
59 for name, value in cls.__dict__.items():
60 if name[0] != "_" and not isinstance(value,
61 (function, classmethod)):
62 defaults[name] = deepcopy(value)
63 for base in cls.__bases__:
64 if hasattr(base, "_getDefaults"):
65 defaults.update(base._getDefaults())
66 return defaults
67 _getDefaults = classmethod(_getDefaults)
Just van Rossumad33d722002-11-21 10:23:04 +000068
69
Just van Rossumda302da2002-11-23 22:26:44 +000070class BundleBuilder(Defaults):
Just van Rossumad33d722002-11-21 10:23:04 +000071
72 """BundleBuilder is a barebones class for assembling bundles. It
73 knows nothing about executables or icons, it only copies files
74 and creates the PkgInfo and Info.plist files.
Just van Rossumad33d722002-11-21 10:23:04 +000075 """
76
Just van Rossumda302da2002-11-23 22:26:44 +000077 # (Note that Defaults.__init__ (deep)copies these values to
78 # instance variables. Mutable defaults are therefore safe.)
79
80 # Name of the bundle, with or without extension.
81 name = None
82
83 # The property list ("plist")
84 plist = Plist(CFBundleDevelopmentRegion = "English",
85 CFBundleInfoDictionaryVersion = "6.0")
86
87 # The type of the bundle.
88 type = "APPL"
89 # The creator code of the bundle.
Just van Rossume6b49022002-11-24 01:23:45 +000090 creator = None
Just van Rossumda302da2002-11-23 22:26:44 +000091
92 # List of files that have to be copied to <bundle>/Contents/Resources.
93 resources = []
94
95 # List of (src, dest) tuples; dest should be a path relative to the bundle
96 # (eg. "Contents/Resources/MyStuff/SomeFile.ext).
97 files = []
98
99 # Directory where the bundle will be assembled.
100 builddir = "build"
101
102 # platform, name of the subfolder of Contents that contains the executable.
103 platform = "MacOS"
104
105 # Make symlinks instead copying files. This is handy during debugging, but
106 # makes the bundle non-distributable.
107 symlink = 0
108
109 # Verbosity level.
110 verbosity = 1
Just van Rossumad33d722002-11-21 10:23:04 +0000111
Just van Rossumceeb9622002-11-21 23:19:37 +0000112 def setup(self):
Just van Rossumda302da2002-11-23 22:26:44 +0000113 # XXX rethink self.name munging, this is brittle.
Just van Rossumceeb9622002-11-21 23:19:37 +0000114 self.name, ext = os.path.splitext(self.name)
115 if not ext:
116 ext = ".bundle"
Just van Rossumda302da2002-11-23 22:26:44 +0000117 bundleextension = ext
Just van Rossumceeb9622002-11-21 23:19:37 +0000118 # misc (derived) attributes
Just van Rossumda302da2002-11-23 22:26:44 +0000119 self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
Just van Rossumceeb9622002-11-21 23:19:37 +0000120 self.execdir = pathjoin("Contents", self.platform)
121
Just van Rossumda302da2002-11-23 22:26:44 +0000122 plist = self.plist
Just van Rossumceeb9622002-11-21 23:19:37 +0000123 plist.CFBundleName = self.name
124 plist.CFBundlePackageType = self.type
Just van Rossume6b49022002-11-24 01:23:45 +0000125 if self.creator is None:
126 if hasattr(plist, "CFBundleSignature"):
127 self.creator = plist.CFBundleSignature
128 else:
129 self.creator = "????"
Just van Rossumceeb9622002-11-21 23:19:37 +0000130 plist.CFBundleSignature = self.creator
Just van Rossum9896ea22003-01-13 23:30:04 +0000131 if not hasattr(plist, "CFBundleIdentifier"):
132 plist.CFBundleIdentifier = self.name
Just van Rossumceeb9622002-11-21 23:19:37 +0000133
Just van Rossumad33d722002-11-21 10:23:04 +0000134 def build(self):
135 """Build the bundle."""
136 builddir = self.builddir
137 if builddir and not os.path.exists(builddir):
138 os.mkdir(builddir)
139 self.message("Building %s" % repr(self.bundlepath), 1)
140 if os.path.exists(self.bundlepath):
141 shutil.rmtree(self.bundlepath)
142 os.mkdir(self.bundlepath)
143 self.preProcess()
144 self._copyFiles()
145 self._addMetaFiles()
146 self.postProcess()
Just van Rossum535ffa22002-11-29 20:06:52 +0000147 self.message("Done.", 1)
Just van Rossumad33d722002-11-21 10:23:04 +0000148
149 def preProcess(self):
150 """Hook for subclasses."""
151 pass
152 def postProcess(self):
153 """Hook for subclasses."""
154 pass
155
156 def _addMetaFiles(self):
157 contents = pathjoin(self.bundlepath, "Contents")
158 makedirs(contents)
159 #
160 # Write Contents/PkgInfo
161 assert len(self.type) == len(self.creator) == 4, \
162 "type and creator must be 4-byte strings."
163 pkginfo = pathjoin(contents, "PkgInfo")
164 f = open(pkginfo, "wb")
165 f.write(self.type + self.creator)
166 f.close()
167 #
168 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000169 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000170 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000171
172 def _copyFiles(self):
173 files = self.files[:]
174 for path in self.resources:
175 files.append((path, pathjoin("Contents", "Resources",
176 os.path.basename(path))))
177 if self.symlink:
178 self.message("Making symbolic links", 1)
179 msg = "Making symlink from"
180 else:
181 self.message("Copying files", 1)
182 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000183 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000184 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000185 if os.path.isdir(src):
186 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
187 else:
188 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000189 dst = pathjoin(self.bundlepath, dst)
190 if self.symlink:
191 symlink(src, dst, mkdirs=1)
Jack Jansen946c1942003-02-17 16:47:12 +0000192 elif os.path.splitext(src)[1] == '.rsrc':
193 macresource.install(src, dst, mkdirs=1)
Just van Rossumad33d722002-11-21 10:23:04 +0000194 else:
195 copy(src, dst, mkdirs=1)
196
197 def message(self, msg, level=0):
198 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000199 indent = ""
200 if level > 1:
201 indent = (level - 1) * " "
202 sys.stderr.write(indent + msg + "\n")
203
204 def report(self):
205 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000206 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000207
208
Just van Rossumcef32882002-11-26 00:34:52 +0000209if __debug__:
210 PYC_EXT = ".pyc"
211else:
212 PYC_EXT = ".pyo"
213
214MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000215USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000216
217# For standalone apps, we have our own minimal site.py. We don't need
218# all the cruft of the real site.py.
219SITE_PY = """\
220import sys
221del sys.path[1:] # sys.path[0] is Contents/Resources/
222"""
223
Just van Rossum109ecbf2003-01-02 13:13:01 +0000224if USE_ZIPIMPORT:
225 ZIP_ARCHIVE = "Modules.zip"
226 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
227 def getPycData(fullname, code, ispkg):
228 if ispkg:
229 fullname += ".__init__"
230 path = fullname.replace(".", os.sep) + PYC_EXT
231 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000232
Just van Rossum74bdca82002-11-28 11:30:56 +0000233SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossumcef32882002-11-26 00:34:52 +0000234
Just van Rossum535ffa22002-11-29 20:06:52 +0000235EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000236def __load():
237 import imp, sys, os
238 for p in sys.path:
239 path = os.path.join(p, "%(filename)s")
240 if os.path.exists(path):
241 break
242 else:
243 assert 0, "file not found: %(filename)s"
244 mod = imp.load_dynamic("%(name)s", path)
245
246__load()
247del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000248"""
249
Just van Rossumcef32882002-11-26 00:34:52 +0000250MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
251 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
252 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
253]
254
255STRIP_EXEC = "/usr/bin/strip"
256
Just van Rossum74bdca82002-11-28 11:30:56 +0000257BOOTSTRAP_SCRIPT = """\
258#!/bin/sh
Just van Rossumad33d722002-11-21 10:23:04 +0000259
Just van Rossum9af69682003-02-02 18:56:37 +0000260execdir=$(dirname "${0}")
Just van Rossumc96d6ce2003-02-12 16:19:39 +0000261executable="${execdir}/%(executable)s"
Just van Rossum9af69682003-02-02 18:56:37 +0000262resdir=$(dirname "${execdir}")/Resources
Just van Rossumc96d6ce2003-02-12 16:19:39 +0000263main="${resdir}/%(mainprogram)s"
264PYTHONPATH="$resdir"
Just van Rossum74bdca82002-11-28 11:30:56 +0000265export PYTHONPATH
Just van Rossum9af69682003-02-02 18:56:37 +0000266exec "${executable}" "${main}" "${1}"
Just van Rossumad33d722002-11-21 10:23:04 +0000267"""
268
Just van Rossumcef32882002-11-26 00:34:52 +0000269
Just van Rossumad33d722002-11-21 10:23:04 +0000270class AppBuilder(BundleBuilder):
271
Just van Rossumda302da2002-11-23 22:26:44 +0000272 # A Python main program. If this argument is given, the main
273 # executable in the bundle will be a small wrapper that invokes
274 # the main program. (XXX Discuss why.)
275 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000276
Just van Rossumda302da2002-11-23 22:26:44 +0000277 # The main executable. If a Python main program is specified
278 # the executable will be copied to Resources and be invoked
279 # by the wrapper program mentioned above. Otherwise it will
280 # simply be used as the main executable.
281 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000282
Just van Rossumda302da2002-11-23 22:26:44 +0000283 # The name of the main nib, for Cocoa apps. *Must* be specified
284 # when building a Cocoa app.
285 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000286
Just van Rossum2aa09562003-02-01 08:34:46 +0000287 # The name of the icon file to be copied to Resources and used for
288 # the Finder icon.
289 iconfile = None
290
Just van Rossumda302da2002-11-23 22:26:44 +0000291 # Symlink the executable instead of copying it.
292 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000293
Just van Rossumcef32882002-11-26 00:34:52 +0000294 # If True, build standalone app.
295 standalone = 0
296
297 # The following attributes are only used when building a standalone app.
298
299 # Exclude these modules.
300 excludeModules = []
301
302 # Include these modules.
303 includeModules = []
304
305 # Include these packages.
306 includePackages = []
307
308 # Strip binaries.
309 strip = 0
310
Just van Rossumcef32882002-11-26 00:34:52 +0000311 # Found Python modules: [(name, codeobject, ispkg), ...]
312 pymodules = []
313
314 # Modules that modulefinder couldn't find:
315 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000316 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000317
318 # List of all binaries (executables or shared libs), for stripping purposes
319 binaries = []
320
Just van Rossumceeb9622002-11-21 23:19:37 +0000321 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000322 if self.standalone and self.mainprogram is None:
323 raise BundleBuilderError, ("must specify 'mainprogram' when "
324 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000325 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000326 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000327 "'executable' and 'mainprogram'")
328
329 if self.name is not None:
330 pass
331 elif self.mainprogram is not None:
332 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
333 elif executable is not None:
334 self.name = os.path.splitext(os.path.basename(self.executable))[0]
335 if self.name[-4:] != ".app":
336 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000337
Just van Rossum74bdca82002-11-28 11:30:56 +0000338 if self.executable is None:
339 if not self.standalone:
340 self.symlink_exec = 1
341 self.executable = sys.executable
342
Just van Rossumceeb9622002-11-21 23:19:37 +0000343 if self.nibname:
344 self.plist.NSMainNibFile = self.nibname
345 if not hasattr(self.plist, "NSPrincipalClass"):
346 self.plist.NSPrincipalClass = "NSApplication"
347
348 BundleBuilder.setup(self)
349
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000350 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000351
Just van Rossumcef32882002-11-26 00:34:52 +0000352 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000353 self.findDependencies()
354
Just van Rossumf7aba232002-11-22 00:31:50 +0000355 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000356 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000357 if self.executable is not None:
358 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000359 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000360 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000361 execname = os.path.basename(self.executable)
362 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000363 if not self.symlink_exec:
364 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000365 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000366 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000367
368 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000369 mainprogram = os.path.basename(self.mainprogram)
370 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
371 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000372 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000373 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000374 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000375 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000376 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
377 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000378
Just van Rossum2aa09562003-02-01 08:34:46 +0000379 if self.iconfile is not None:
380 iconbase = os.path.basename(self.iconfile)
381 self.plist.CFBundleIconFile = iconbase
382 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
383
Just van Rossum16aebf72002-11-22 11:43:10 +0000384 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000385 if self.standalone:
386 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000387 if self.strip and not self.symlink:
388 self.stripBinaries()
389
Just van Rossum16aebf72002-11-22 11:43:10 +0000390 if self.symlink_exec and self.executable:
391 self.message("Symlinking executable %s to %s" % (self.executable,
392 self.execpath), 2)
393 dst = pathjoin(self.bundlepath, self.execpath)
394 makedirs(os.path.dirname(dst))
395 os.symlink(os.path.abspath(self.executable), dst)
396
Just van Rossum74bdca82002-11-28 11:30:56 +0000397 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000398 self.reportMissing()
399
400 def addPythonModules(self):
401 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000402
Just van Rossum109ecbf2003-01-02 13:13:01 +0000403 if USE_ZIPIMPORT:
404 # Create a zip file containing all modules as pyc.
405 import zipfile
406 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000407 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000408 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
409 for name, code, ispkg in self.pymodules:
410 self.message("Adding Python module %s" % name, 2)
411 path, pyc = getPycData(name, code, ispkg)
412 zf.writestr(path, pyc)
413 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000414 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000415 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
416 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000417 writePyc(SITE_CO, sitepath)
418 else:
419 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000420 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000421 if ispkg:
422 name += ".__init__"
423 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000424 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000425
426 if ispkg:
427 self.message("Adding Python package %s" % path, 2)
428 else:
429 self.message("Adding Python module %s" % path, 2)
430
431 abspath = pathjoin(self.bundlepath, path)
432 makedirs(os.path.dirname(abspath))
433 writePyc(code, abspath)
434
435 def stripBinaries(self):
436 if not os.path.exists(STRIP_EXEC):
437 self.message("Error: can't strip binaries: no strip program at "
438 "%s" % STRIP_EXEC, 0)
439 else:
440 self.message("Stripping binaries", 1)
441 for relpath in self.binaries:
442 self.message("Stripping %s" % relpath, 2)
443 abspath = pathjoin(self.bundlepath, relpath)
444 assert not os.path.islink(abspath)
445 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
446
447 def findDependencies(self):
448 self.message("Finding module dependencies", 1)
449 import modulefinder
450 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000451 if USE_ZIPIMPORT:
452 # zipimport imports zlib, must add it manually
453 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000454 # manually add our own site.py
455 site = mf.add_module("site")
456 site.__code__ = SITE_CO
457 mf.scan_code(SITE_CO, site)
458
459 includeModules = self.includeModules[:]
460 for name in self.includePackages:
461 includeModules.extend(findPackageContents(name).keys())
462 for name in includeModules:
463 try:
464 mf.import_hook(name)
465 except ImportError:
466 self.missingModules.append(name)
467
Just van Rossumcef32882002-11-26 00:34:52 +0000468 mf.run_script(self.mainprogram)
469 modules = mf.modules.items()
470 modules.sort()
471 for name, mod in modules:
472 if mod.__file__ and mod.__code__ is None:
473 # C extension
474 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000475 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000476 if USE_ZIPIMPORT:
477 # Python modules are stored in a Zip archive, but put
478 # extensions in Contents/Resources/.a and add a tiny "loader"
479 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000480 dstpath = pathjoin("Contents", "Resources", filename)
481 source = EXT_LOADER % {"name": name, "filename": filename}
482 code = compile(source, "<dynloader for %s>" % name, "exec")
483 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000484 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000485 # just copy the file
486 dstpath = name.split(".")[:-1] + [filename]
487 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000488 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000489 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000490 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000491 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000492 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000493 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000494 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000495 self.pymodules.append((name, mod.__code__, ispkg))
496
Just van Rossum74bdca82002-11-28 11:30:56 +0000497 if hasattr(mf, "any_missing_maybe"):
498 missing, maybe = mf.any_missing_maybe()
499 else:
500 missing = mf.any_missing()
501 maybe = []
502 self.missingModules.extend(missing)
503 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000504
505 def reportMissing(self):
506 missing = [name for name in self.missingModules
507 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000508 if self.maybeMissingModules:
509 maybe = self.maybeMissingModules
510 else:
511 maybe = [name for name in missing if "." in name]
512 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000513 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000514 maybe.sort()
515 if maybe:
516 self.message("Warning: couldn't find the following submodules:", 1)
517 self.message(" (Note that these could be false alarms -- "
518 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000519 self.message(" possible to distinguish between \"from package "
520 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000521 self.message(" and \"from package import name\")", 1)
522 for name in maybe:
523 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000524 if missing:
525 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000526 for name in missing:
527 self.message(" ? " + name, 1)
528
529 def report(self):
530 # XXX something decent
531 import pprint
532 pprint.pprint(self.__dict__)
533 if self.standalone:
534 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000535
536#
537# Utilities.
538#
539
540SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
541identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
542
543def findPackageContents(name, searchpath=None):
544 head = name.split(".")[-1]
545 if identifierRE.match(head) is None:
546 return {}
547 try:
548 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
549 except ImportError:
550 return {}
551 modules = {name: None}
552 if tp == imp.PKG_DIRECTORY and path:
553 files = os.listdir(path)
554 for sub in files:
555 sub, ext = os.path.splitext(sub)
556 fullname = name + "." + sub
557 if sub != "__init__" and fullname not in modules:
558 modules.update(findPackageContents(fullname, [path]))
559 return modules
560
561def writePyc(code, path):
562 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000563 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000564 f.write("\0" * 4) # don't bother about a time stamp
565 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000566 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000567
Just van Rossumad33d722002-11-21 10:23:04 +0000568def copy(src, dst, mkdirs=0):
569 """Copy a file or a directory."""
570 if mkdirs:
571 makedirs(os.path.dirname(dst))
572 if os.path.isdir(src):
573 shutil.copytree(src, dst)
574 else:
575 shutil.copy2(src, dst)
576
577def copytodir(src, dstdir):
578 """Copy a file or a directory to an existing directory."""
579 dst = pathjoin(dstdir, os.path.basename(src))
580 copy(src, dst)
581
582def makedirs(dir):
583 """Make all directories leading up to 'dir' including the leaf
584 directory. Don't moan if any path element already exists."""
585 try:
586 os.makedirs(dir)
587 except OSError, why:
588 if why.errno != errno.EEXIST:
589 raise
590
591def symlink(src, dst, mkdirs=0):
592 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000593 if not os.path.exists(src):
594 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000595 if mkdirs:
596 makedirs(os.path.dirname(dst))
597 os.symlink(os.path.abspath(src), dst)
598
599def pathjoin(*args):
600 """Safe wrapper for os.path.join: asserts that all but the first
601 argument are relative paths."""
602 for seg in args[1:]:
603 assert seg[0] != "/"
604 return os.path.join(*args)
605
606
Just van Rossumceeb9622002-11-21 23:19:37 +0000607cmdline_doc = """\
608Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000609 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000610 python mybuildscript.py [options] command
611
612Commands:
613 build build the application
614 report print a report
615
616Options:
617 -b, --builddir=DIR the build directory; defaults to "build"
618 -n, --name=NAME application name
619 -r, --resource=FILE extra file or folder to be copied to Resources
620 -e, --executable=FILE the executable to be used
621 -m, --mainprogram=FILE the Python main program
622 -p, --plist=FILE .plist file (default: generate one)
623 --nib=NAME main nib name
624 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000625 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000626 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000627 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000628 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000629 --standalone build a standalone application, which is fully
630 independent of a Python installation
631 -x, --exclude=MODULE exclude module (with --standalone)
632 -i, --include=MODULE include module (with --standalone)
633 --package=PACKAGE include a whole package (with --standalone)
634 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000635 -v, --verbose increase verbosity level
636 -q, --quiet decrease verbosity level
637 -h, --help print this message
638"""
639
640def usage(msg=None):
641 if msg:
642 print msg
643 print cmdline_doc
644 sys.exit(1)
645
646def main(builder=None):
647 if builder is None:
648 builder = AppBuilder(verbosity=1)
649
Just van Rossumcef32882002-11-26 00:34:52 +0000650 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000651 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000652 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000653 "link-exec", "help", "verbose", "quiet", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000654 "exclude=", "include=", "package=", "strip", "iconfile=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000655
656 try:
657 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
658 except getopt.error:
659 usage()
660
661 for opt, arg in options:
662 if opt in ('-b', '--builddir'):
663 builder.builddir = arg
664 elif opt in ('-n', '--name'):
665 builder.name = arg
666 elif opt in ('-r', '--resource'):
667 builder.resources.append(arg)
668 elif opt in ('-e', '--executable'):
669 builder.executable = arg
670 elif opt in ('-m', '--mainprogram'):
671 builder.mainprogram = arg
672 elif opt in ('-c', '--creator'):
673 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000674 elif opt == '--iconfile':
675 builder.iconfile = arg
Just van Rossumceeb9622002-11-21 23:19:37 +0000676 elif opt == "--nib":
677 builder.nibname = arg
678 elif opt in ('-p', '--plist'):
679 builder.plist = Plist.fromFile(arg)
680 elif opt in ('-l', '--link'):
681 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000682 elif opt == '--link-exec':
683 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000684 elif opt in ('-h', '--help'):
685 usage()
686 elif opt in ('-v', '--verbose'):
687 builder.verbosity += 1
688 elif opt in ('-q', '--quiet'):
689 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000690 elif opt == '--standalone':
691 builder.standalone = 1
692 elif opt in ('-x', '--exclude'):
693 builder.excludeModules.append(arg)
694 elif opt in ('-i', '--include'):
695 builder.includeModules.append(arg)
696 elif opt == '--package':
697 builder.includePackages.append(arg)
698 elif opt == '--strip':
699 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000700
701 if len(args) != 1:
702 usage("Must specify one command ('build', 'report' or 'help')")
703 command = args[0]
704
705 if command == "build":
706 builder.setup()
707 builder.build()
708 elif command == "report":
709 builder.setup()
710 builder.report()
711 elif command == "help":
712 usage()
713 else:
714 usage("Unknown command '%s'" % command)
715
716
Just van Rossumad33d722002-11-21 10:23:04 +0000717def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000718 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000719 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000720
721
722if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000723 main()