blob: 5fe2c6001f0f3d7adc064f4fef16add1181aab2a [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
Just van Rossumad33d722002-11-21 10:23:04 +000039
Just van Rossumcef32882002-11-26 00:34:52 +000040class BundleBuilderError(Exception): pass
41
42
Just van Rossumda302da2002-11-23 22:26:44 +000043class Defaults:
44
45 """Class attributes that don't start with an underscore and are
46 not functions or classmethods are (deep)copied to self.__dict__.
47 This allows for mutable default values.
48 """
49
50 def __init__(self, **kwargs):
51 defaults = self._getDefaults()
52 defaults.update(kwargs)
53 self.__dict__.update(defaults)
54
55 def _getDefaults(cls):
56 defaults = {}
57 for name, value in cls.__dict__.items():
58 if name[0] != "_" and not isinstance(value,
59 (function, classmethod)):
60 defaults[name] = deepcopy(value)
61 for base in cls.__bases__:
62 if hasattr(base, "_getDefaults"):
63 defaults.update(base._getDefaults())
64 return defaults
65 _getDefaults = classmethod(_getDefaults)
Just van Rossumad33d722002-11-21 10:23:04 +000066
67
Just van Rossumda302da2002-11-23 22:26:44 +000068class BundleBuilder(Defaults):
Just van Rossumad33d722002-11-21 10:23:04 +000069
70 """BundleBuilder is a barebones class for assembling bundles. It
71 knows nothing about executables or icons, it only copies files
72 and creates the PkgInfo and Info.plist files.
Just van Rossumad33d722002-11-21 10:23:04 +000073 """
74
Just van Rossumda302da2002-11-23 22:26:44 +000075 # (Note that Defaults.__init__ (deep)copies these values to
76 # instance variables. Mutable defaults are therefore safe.)
77
78 # Name of the bundle, with or without extension.
79 name = None
80
81 # The property list ("plist")
82 plist = Plist(CFBundleDevelopmentRegion = "English",
83 CFBundleInfoDictionaryVersion = "6.0")
84
85 # The type of the bundle.
Jack Jansencc81b802003-03-05 14:42:18 +000086 type = "BNDL"
Just van Rossumda302da2002-11-23 22:26:44 +000087 # The creator code of the bundle.
Just van Rossume6b49022002-11-24 01:23:45 +000088 creator = None
Just van Rossumda302da2002-11-23 22:26:44 +000089
90 # List of files that have to be copied to <bundle>/Contents/Resources.
91 resources = []
92
93 # List of (src, dest) tuples; dest should be a path relative to the bundle
94 # (eg. "Contents/Resources/MyStuff/SomeFile.ext).
95 files = []
96
97 # Directory where the bundle will be assembled.
98 builddir = "build"
99
Just van Rossumda302da2002-11-23 22:26:44 +0000100 # Make symlinks instead copying files. This is handy during debugging, but
101 # makes the bundle non-distributable.
102 symlink = 0
103
104 # Verbosity level.
105 verbosity = 1
Just van Rossumad33d722002-11-21 10:23:04 +0000106
Just van Rossumceeb9622002-11-21 23:19:37 +0000107 def setup(self):
Just van Rossumda302da2002-11-23 22:26:44 +0000108 # XXX rethink self.name munging, this is brittle.
Just van Rossumceeb9622002-11-21 23:19:37 +0000109 self.name, ext = os.path.splitext(self.name)
110 if not ext:
111 ext = ".bundle"
Just van Rossumda302da2002-11-23 22:26:44 +0000112 bundleextension = ext
Just van Rossumceeb9622002-11-21 23:19:37 +0000113 # misc (derived) attributes
Just van Rossumda302da2002-11-23 22:26:44 +0000114 self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
Just van Rossumceeb9622002-11-21 23:19:37 +0000115
Just van Rossumda302da2002-11-23 22:26:44 +0000116 plist = self.plist
Just van Rossumceeb9622002-11-21 23:19:37 +0000117 plist.CFBundleName = self.name
118 plist.CFBundlePackageType = self.type
Just van Rossume6b49022002-11-24 01:23:45 +0000119 if self.creator is None:
120 if hasattr(plist, "CFBundleSignature"):
121 self.creator = plist.CFBundleSignature
122 else:
123 self.creator = "????"
Just van Rossumceeb9622002-11-21 23:19:37 +0000124 plist.CFBundleSignature = self.creator
Just van Rossum9896ea22003-01-13 23:30:04 +0000125 if not hasattr(plist, "CFBundleIdentifier"):
126 plist.CFBundleIdentifier = self.name
Just van Rossumceeb9622002-11-21 23:19:37 +0000127
Just van Rossumad33d722002-11-21 10:23:04 +0000128 def build(self):
129 """Build the bundle."""
130 builddir = self.builddir
131 if builddir and not os.path.exists(builddir):
132 os.mkdir(builddir)
133 self.message("Building %s" % repr(self.bundlepath), 1)
134 if os.path.exists(self.bundlepath):
135 shutil.rmtree(self.bundlepath)
136 os.mkdir(self.bundlepath)
137 self.preProcess()
138 self._copyFiles()
139 self._addMetaFiles()
140 self.postProcess()
Just van Rossum535ffa22002-11-29 20:06:52 +0000141 self.message("Done.", 1)
Just van Rossumad33d722002-11-21 10:23:04 +0000142
143 def preProcess(self):
144 """Hook for subclasses."""
145 pass
146 def postProcess(self):
147 """Hook for subclasses."""
148 pass
149
150 def _addMetaFiles(self):
151 contents = pathjoin(self.bundlepath, "Contents")
152 makedirs(contents)
153 #
154 # Write Contents/PkgInfo
155 assert len(self.type) == len(self.creator) == 4, \
156 "type and creator must be 4-byte strings."
157 pkginfo = pathjoin(contents, "PkgInfo")
158 f = open(pkginfo, "wb")
159 f.write(self.type + self.creator)
160 f.close()
161 #
162 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000163 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000164 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000165
166 def _copyFiles(self):
167 files = self.files[:]
168 for path in self.resources:
169 files.append((path, pathjoin("Contents", "Resources",
170 os.path.basename(path))))
171 if self.symlink:
172 self.message("Making symbolic links", 1)
173 msg = "Making symlink from"
174 else:
175 self.message("Copying files", 1)
176 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000177 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000178 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000179 if os.path.isdir(src):
180 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
181 else:
182 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000183 dst = pathjoin(self.bundlepath, dst)
184 if self.symlink:
185 symlink(src, dst, mkdirs=1)
186 else:
187 copy(src, dst, mkdirs=1)
188
189 def message(self, msg, level=0):
190 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000191 indent = ""
192 if level > 1:
193 indent = (level - 1) * " "
194 sys.stderr.write(indent + msg + "\n")
195
196 def report(self):
197 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000198 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000199
200
Just van Rossumcef32882002-11-26 00:34:52 +0000201if __debug__:
202 PYC_EXT = ".pyc"
203else:
204 PYC_EXT = ".pyo"
205
206MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000207USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000208
209# For standalone apps, we have our own minimal site.py. We don't need
210# all the cruft of the real site.py.
211SITE_PY = """\
212import sys
213del sys.path[1:] # sys.path[0] is Contents/Resources/
214"""
215
Just van Rossum109ecbf2003-01-02 13:13:01 +0000216if USE_ZIPIMPORT:
217 ZIP_ARCHIVE = "Modules.zip"
218 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
219 def getPycData(fullname, code, ispkg):
220 if ispkg:
221 fullname += ".__init__"
222 path = fullname.replace(".", os.sep) + PYC_EXT
223 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000224
Just van Rossum74bdca82002-11-28 11:30:56 +0000225SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossum7322b1a2003-02-25 20:15:40 +0000226
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000227#
228# Extension modules can't be in the modules zip archive, so a placeholder
229# is added instead, that loads the extension from a specified location.
230#
Just van Rossum535ffa22002-11-29 20:06:52 +0000231EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000232def __load():
233 import imp, sys, os
234 for p in sys.path:
235 path = os.path.join(p, "%(filename)s")
236 if os.path.exists(path):
237 break
238 else:
239 assert 0, "file not found: %(filename)s"
240 mod = imp.load_dynamic("%(name)s", path)
241
242__load()
243del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000244"""
245
Just van Rossumcef32882002-11-26 00:34:52 +0000246MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
247 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
248 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
249]
250
251STRIP_EXEC = "/usr/bin/strip"
252
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000253#
254# We're using a stock interpreter to run the app, yet we need
255# a way to pass the Python main program to the interpreter. The
256# bootstrapping script fires up the interpreter with the right
257# arguments. os.execve() is used as OSX doesn't like us to
258# start a real new process. Also, the executable name must match
259# the CFBundleExecutable value in the Info.plist, so we lie
260# deliberately with argv[0]. The actual Python executable is
261# passed in an environment variable so we can "repair"
262# sys.executable later.
263#
Just van Rossum74bdca82002-11-28 11:30:56 +0000264BOOTSTRAP_SCRIPT = """\
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000265#!%(hashbang)s
Just van Rossumad33d722002-11-21 10:23:04 +0000266
Just van Rossum7322b1a2003-02-25 20:15:40 +0000267import sys, os
268execdir = os.path.dirname(sys.argv[0])
269executable = os.path.join(execdir, "%(executable)s")
270resdir = os.path.join(os.path.dirname(execdir), "Resources")
271mainprogram = os.path.join(resdir, "%(mainprogram)s")
272
273sys.argv.insert(1, mainprogram)
274os.environ["PYTHONPATH"] = resdir
Just van Rossuma87e4472003-03-20 21:37:05 +0000275os.environ["PYTHONHOME"] = resdir
Just van Rossum7322b1a2003-02-25 20:15:40 +0000276os.environ["PYTHONEXECUTABLE"] = executable
277os.execve(executable, sys.argv, os.environ)
Just van Rossumad33d722002-11-21 10:23:04 +0000278"""
279
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000280
281#
282# Optional wrapper that converts "dropped files" into sys.argv values.
283#
284ARGV_EMULATOR = """\
Jack Jansena03adde2003-02-18 23:29:46 +0000285import argvemulator, os
286
287argvemulator.ArgvCollector().mainloop()
288execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
289"""
Just van Rossumcef32882002-11-26 00:34:52 +0000290
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000291
Just van Rossumad33d722002-11-21 10:23:04 +0000292class AppBuilder(BundleBuilder):
293
Jack Jansencc81b802003-03-05 14:42:18 +0000294 # Override type of the bundle.
Jack Jansen620c0832003-03-05 14:44:54 +0000295 type = "APPL"
Jack Jansencc81b802003-03-05 14:42:18 +0000296
297 # platform, name of the subfolder of Contents that contains the executable.
298 platform = "MacOS"
299
Just van Rossumda302da2002-11-23 22:26:44 +0000300 # A Python main program. If this argument is given, the main
301 # executable in the bundle will be a small wrapper that invokes
302 # the main program. (XXX Discuss why.)
303 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000304
Just van Rossumda302da2002-11-23 22:26:44 +0000305 # The main executable. If a Python main program is specified
306 # the executable will be copied to Resources and be invoked
307 # by the wrapper program mentioned above. Otherwise it will
308 # simply be used as the main executable.
309 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000310
Just van Rossumda302da2002-11-23 22:26:44 +0000311 # The name of the main nib, for Cocoa apps. *Must* be specified
312 # when building a Cocoa app.
313 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000314
Just van Rossum2aa09562003-02-01 08:34:46 +0000315 # The name of the icon file to be copied to Resources and used for
316 # the Finder icon.
317 iconfile = None
318
Just van Rossumda302da2002-11-23 22:26:44 +0000319 # Symlink the executable instead of copying it.
320 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000321
Just van Rossumcef32882002-11-26 00:34:52 +0000322 # If True, build standalone app.
323 standalone = 0
Jack Jansena03adde2003-02-18 23:29:46 +0000324
325 # If True, add a real main program that emulates sys.argv before calling
326 # mainprogram
327 argv_emulation = 0
Just van Rossumcef32882002-11-26 00:34:52 +0000328
329 # The following attributes are only used when building a standalone app.
330
331 # Exclude these modules.
332 excludeModules = []
333
334 # Include these modules.
335 includeModules = []
336
337 # Include these packages.
338 includePackages = []
339
340 # Strip binaries.
341 strip = 0
342
Just van Rossumcef32882002-11-26 00:34:52 +0000343 # Found Python modules: [(name, codeobject, ispkg), ...]
344 pymodules = []
345
346 # Modules that modulefinder couldn't find:
347 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000348 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000349
350 # List of all binaries (executables or shared libs), for stripping purposes
351 binaries = []
352
Just van Rossumceeb9622002-11-21 23:19:37 +0000353 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000354 if self.standalone and self.mainprogram is None:
355 raise BundleBuilderError, ("must specify 'mainprogram' when "
356 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000357 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000358 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000359 "'executable' and 'mainprogram'")
360
Jack Jansencc81b802003-03-05 14:42:18 +0000361 self.execdir = pathjoin("Contents", self.platform)
362
Just van Rossumceeb9622002-11-21 23:19:37 +0000363 if self.name is not None:
364 pass
365 elif self.mainprogram is not None:
366 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
367 elif executable is not None:
368 self.name = os.path.splitext(os.path.basename(self.executable))[0]
369 if self.name[-4:] != ".app":
370 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000371
Just van Rossum74bdca82002-11-28 11:30:56 +0000372 if self.executable is None:
373 if not self.standalone:
374 self.symlink_exec = 1
375 self.executable = sys.executable
376
Just van Rossumceeb9622002-11-21 23:19:37 +0000377 if self.nibname:
378 self.plist.NSMainNibFile = self.nibname
379 if not hasattr(self.plist, "NSPrincipalClass"):
380 self.plist.NSPrincipalClass = "NSApplication"
381
382 BundleBuilder.setup(self)
383
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000384 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000385
Just van Rossumcef32882002-11-26 00:34:52 +0000386 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000387 self.findDependencies()
388
Just van Rossumf7aba232002-11-22 00:31:50 +0000389 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000390 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000391 if self.executable is not None:
392 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000393 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000394 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000395 execname = os.path.basename(self.executable)
396 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000397 if not self.symlink_exec:
398 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000399 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000400 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000401
402 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000403 mainprogram = os.path.basename(self.mainprogram)
404 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
Jack Jansena03adde2003-02-18 23:29:46 +0000405 if self.argv_emulation:
406 # Change the main program, and create the helper main program (which
407 # does argv collection and then calls the real main).
408 # Also update the included modules (if we're creating a standalone
409 # program) and the plist
410 realmainprogram = mainprogram
411 mainprogram = '__argvemulator_' + mainprogram
412 resdirpath = pathjoin(self.bundlepath, resdir)
413 mainprogrampath = pathjoin(resdirpath, mainprogram)
414 makedirs(resdirpath)
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000415 open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
Jack Jansena03adde2003-02-18 23:29:46 +0000416 if self.standalone:
417 self.includeModules.append("argvemulator")
418 self.includeModules.append("os")
419 if not self.plist.has_key("CFBundleDocumentTypes"):
420 self.plist["CFBundleDocumentTypes"] = [
421 { "CFBundleTypeOSTypes" : [
422 "****",
423 "fold",
424 "disk"],
425 "CFBundleTypeRole": "Viewer"}]
Just van Rossum24884f72002-11-29 21:22:33 +0000426 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000427 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000428 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000429 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000430 makedirs(execdir)
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000431 if self.standalone:
432 # XXX we're screwed when the end user has deleted
433 # /usr/bin/python
434 hashbang = "/usr/bin/python"
435 else:
436 hashbang = sys.executable
437 while os.path.islink(hashbang):
438 hashbang = os.readlink(hashbang)
Just van Rossum24884f72002-11-29 21:22:33 +0000439 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
440 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000441
Just van Rossum2aa09562003-02-01 08:34:46 +0000442 if self.iconfile is not None:
443 iconbase = os.path.basename(self.iconfile)
444 self.plist.CFBundleIconFile = iconbase
445 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
446
Just van Rossum16aebf72002-11-22 11:43:10 +0000447 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000448 if self.standalone:
449 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000450 if self.strip and not self.symlink:
451 self.stripBinaries()
452
Just van Rossum16aebf72002-11-22 11:43:10 +0000453 if self.symlink_exec and self.executable:
454 self.message("Symlinking executable %s to %s" % (self.executable,
455 self.execpath), 2)
456 dst = pathjoin(self.bundlepath, self.execpath)
457 makedirs(os.path.dirname(dst))
458 os.symlink(os.path.abspath(self.executable), dst)
459
Just van Rossum74bdca82002-11-28 11:30:56 +0000460 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000461 self.reportMissing()
462
463 def addPythonModules(self):
464 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000465
Just van Rossum109ecbf2003-01-02 13:13:01 +0000466 if USE_ZIPIMPORT:
467 # Create a zip file containing all modules as pyc.
468 import zipfile
469 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000470 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000471 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
472 for name, code, ispkg in self.pymodules:
473 self.message("Adding Python module %s" % name, 2)
474 path, pyc = getPycData(name, code, ispkg)
475 zf.writestr(path, pyc)
476 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000477 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000478 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
479 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000480 writePyc(SITE_CO, sitepath)
481 else:
482 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000483 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000484 if ispkg:
485 name += ".__init__"
486 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000487 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000488
489 if ispkg:
490 self.message("Adding Python package %s" % path, 2)
491 else:
492 self.message("Adding Python module %s" % path, 2)
493
494 abspath = pathjoin(self.bundlepath, path)
495 makedirs(os.path.dirname(abspath))
496 writePyc(code, abspath)
497
498 def stripBinaries(self):
499 if not os.path.exists(STRIP_EXEC):
500 self.message("Error: can't strip binaries: no strip program at "
501 "%s" % STRIP_EXEC, 0)
502 else:
503 self.message("Stripping binaries", 1)
504 for relpath in self.binaries:
505 self.message("Stripping %s" % relpath, 2)
506 abspath = pathjoin(self.bundlepath, relpath)
507 assert not os.path.islink(abspath)
508 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
509
510 def findDependencies(self):
511 self.message("Finding module dependencies", 1)
512 import modulefinder
513 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000514 if USE_ZIPIMPORT:
515 # zipimport imports zlib, must add it manually
516 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000517 # manually add our own site.py
518 site = mf.add_module("site")
519 site.__code__ = SITE_CO
520 mf.scan_code(SITE_CO, site)
521
Just van Rossum7322b1a2003-02-25 20:15:40 +0000522 # warnings.py gets imported implicitly from C
523 mf.import_hook("warnings")
524
Just van Rossumcef32882002-11-26 00:34:52 +0000525 includeModules = self.includeModules[:]
526 for name in self.includePackages:
527 includeModules.extend(findPackageContents(name).keys())
528 for name in includeModules:
529 try:
530 mf.import_hook(name)
531 except ImportError:
532 self.missingModules.append(name)
533
Just van Rossumcef32882002-11-26 00:34:52 +0000534 mf.run_script(self.mainprogram)
535 modules = mf.modules.items()
536 modules.sort()
537 for name, mod in modules:
538 if mod.__file__ and mod.__code__ is None:
539 # C extension
540 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000541 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000542 if USE_ZIPIMPORT:
543 # Python modules are stored in a Zip archive, but put
544 # extensions in Contents/Resources/.a and add a tiny "loader"
545 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000546 dstpath = pathjoin("Contents", "Resources", filename)
547 source = EXT_LOADER % {"name": name, "filename": filename}
548 code = compile(source, "<dynloader for %s>" % name, "exec")
549 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000550 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000551 # just copy the file
552 dstpath = name.split(".")[:-1] + [filename]
553 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000554 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000555 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000556 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000557 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000558 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000559 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000560 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000561 self.pymodules.append((name, mod.__code__, ispkg))
562
Just van Rossum74bdca82002-11-28 11:30:56 +0000563 if hasattr(mf, "any_missing_maybe"):
564 missing, maybe = mf.any_missing_maybe()
565 else:
566 missing = mf.any_missing()
567 maybe = []
568 self.missingModules.extend(missing)
569 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000570
571 def reportMissing(self):
572 missing = [name for name in self.missingModules
573 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000574 if self.maybeMissingModules:
575 maybe = self.maybeMissingModules
576 else:
577 maybe = [name for name in missing if "." in name]
578 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000579 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000580 maybe.sort()
581 if maybe:
582 self.message("Warning: couldn't find the following submodules:", 1)
583 self.message(" (Note that these could be false alarms -- "
584 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000585 self.message(" possible to distinguish between \"from package "
586 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000587 self.message(" and \"from package import name\")", 1)
588 for name in maybe:
589 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000590 if missing:
591 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000592 for name in missing:
593 self.message(" ? " + name, 1)
594
595 def report(self):
596 # XXX something decent
597 import pprint
598 pprint.pprint(self.__dict__)
599 if self.standalone:
600 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000601
602#
603# Utilities.
604#
605
606SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
607identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
608
609def findPackageContents(name, searchpath=None):
610 head = name.split(".")[-1]
611 if identifierRE.match(head) is None:
612 return {}
613 try:
614 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
615 except ImportError:
616 return {}
617 modules = {name: None}
618 if tp == imp.PKG_DIRECTORY and path:
619 files = os.listdir(path)
620 for sub in files:
621 sub, ext = os.path.splitext(sub)
622 fullname = name + "." + sub
623 if sub != "__init__" and fullname not in modules:
624 modules.update(findPackageContents(fullname, [path]))
625 return modules
626
627def writePyc(code, path):
628 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000629 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000630 f.write("\0" * 4) # don't bother about a time stamp
631 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000632 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000633
Just van Rossumad33d722002-11-21 10:23:04 +0000634def copy(src, dst, mkdirs=0):
635 """Copy a file or a directory."""
636 if mkdirs:
637 makedirs(os.path.dirname(dst))
638 if os.path.isdir(src):
639 shutil.copytree(src, dst)
640 else:
641 shutil.copy2(src, dst)
642
643def copytodir(src, dstdir):
644 """Copy a file or a directory to an existing directory."""
645 dst = pathjoin(dstdir, os.path.basename(src))
646 copy(src, dst)
647
648def makedirs(dir):
649 """Make all directories leading up to 'dir' including the leaf
650 directory. Don't moan if any path element already exists."""
651 try:
652 os.makedirs(dir)
653 except OSError, why:
654 if why.errno != errno.EEXIST:
655 raise
656
657def symlink(src, dst, mkdirs=0):
658 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000659 if not os.path.exists(src):
660 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000661 if mkdirs:
662 makedirs(os.path.dirname(dst))
663 os.symlink(os.path.abspath(src), dst)
664
665def pathjoin(*args):
666 """Safe wrapper for os.path.join: asserts that all but the first
667 argument are relative paths."""
668 for seg in args[1:]:
669 assert seg[0] != "/"
670 return os.path.join(*args)
671
672
Just van Rossumceeb9622002-11-21 23:19:37 +0000673cmdline_doc = """\
674Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000675 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000676 python mybuildscript.py [options] command
677
678Commands:
679 build build the application
680 report print a report
681
682Options:
683 -b, --builddir=DIR the build directory; defaults to "build"
684 -n, --name=NAME application name
685 -r, --resource=FILE extra file or folder to be copied to Resources
Just van Rossum7215e082003-02-25 21:00:55 +0000686 -f, --file=SRC:DST extra file or folder to be copied into the bundle;
687 DST must be a path relative to the bundle root
Just van Rossumceeb9622002-11-21 23:19:37 +0000688 -e, --executable=FILE the executable to be used
689 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000690 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000691 -p, --plist=FILE .plist file (default: generate one)
692 --nib=NAME main nib name
693 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000694 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000695 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000696 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000697 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000698 --standalone build a standalone application, which is fully
699 independent of a Python installation
700 -x, --exclude=MODULE exclude module (with --standalone)
701 -i, --include=MODULE include module (with --standalone)
702 --package=PACKAGE include a whole package (with --standalone)
703 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000704 -v, --verbose increase verbosity level
705 -q, --quiet decrease verbosity level
706 -h, --help print this message
707"""
708
709def usage(msg=None):
710 if msg:
711 print msg
712 print cmdline_doc
713 sys.exit(1)
714
715def main(builder=None):
716 if builder is None:
717 builder = AppBuilder(verbosity=1)
718
Jack Jansen00cbf072003-02-24 16:27:08 +0000719 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
Just van Rossum7215e082003-02-25 21:00:55 +0000720 longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000721 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000722 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000723 "exclude=", "include=", "package=", "strip", "iconfile=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000724
725 try:
726 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
727 except getopt.error:
728 usage()
729
730 for opt, arg in options:
731 if opt in ('-b', '--builddir'):
732 builder.builddir = arg
733 elif opt in ('-n', '--name'):
734 builder.name = arg
735 elif opt in ('-r', '--resource'):
736 builder.resources.append(arg)
Just van Rossum7215e082003-02-25 21:00:55 +0000737 elif opt in ('-f', '--file'):
Jack Jansen00cbf072003-02-24 16:27:08 +0000738 srcdst = arg.split(':')
739 if len(srcdst) != 2:
Just van Rossum49833312003-02-25 21:08:12 +0000740 usage("-f or --file argument must be two paths, "
741 "separated by a colon")
Jack Jansen00cbf072003-02-24 16:27:08 +0000742 builder.files.append(srcdst)
Just van Rossumceeb9622002-11-21 23:19:37 +0000743 elif opt in ('-e', '--executable'):
744 builder.executable = arg
745 elif opt in ('-m', '--mainprogram'):
746 builder.mainprogram = arg
Jack Jansena03adde2003-02-18 23:29:46 +0000747 elif opt in ('-a', '--argv'):
748 builder.argv_emulation = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000749 elif opt in ('-c', '--creator'):
750 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000751 elif opt == '--iconfile':
752 builder.iconfile = arg
Just van Rossumceeb9622002-11-21 23:19:37 +0000753 elif opt == "--nib":
754 builder.nibname = arg
755 elif opt in ('-p', '--plist'):
756 builder.plist = Plist.fromFile(arg)
757 elif opt in ('-l', '--link'):
758 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000759 elif opt == '--link-exec':
760 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000761 elif opt in ('-h', '--help'):
762 usage()
763 elif opt in ('-v', '--verbose'):
764 builder.verbosity += 1
765 elif opt in ('-q', '--quiet'):
766 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000767 elif opt == '--standalone':
768 builder.standalone = 1
769 elif opt in ('-x', '--exclude'):
770 builder.excludeModules.append(arg)
771 elif opt in ('-i', '--include'):
772 builder.includeModules.append(arg)
773 elif opt == '--package':
774 builder.includePackages.append(arg)
775 elif opt == '--strip':
776 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000777
778 if len(args) != 1:
779 usage("Must specify one command ('build', 'report' or 'help')")
780 command = args[0]
781
782 if command == "build":
783 builder.setup()
784 builder.build()
785 elif command == "report":
786 builder.setup()
787 builder.report()
788 elif command == "help":
789 usage()
790 else:
791 usage("Unknown command '%s'" % command)
792
793
Just van Rossumad33d722002-11-21 10:23:04 +0000794def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000795 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000796 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000797
798
799if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000800 main()