blob: 86f5e49aafdc0826fff5ebac0fd900ccf70e795b [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
Just van Rossum15624d82003-03-21 09:26:59 +000097 # List of shared libraries (dylibs, Frameworks) to bundle with the app
98 # will be placed in Contents/Frameworks
99 libs = []
100
Just van Rossumda302da2002-11-23 22:26:44 +0000101 # Directory where the bundle will be assembled.
102 builddir = "build"
103
Just van Rossumda302da2002-11-23 22:26:44 +0000104 # Make symlinks instead copying files. This is handy during debugging, but
105 # makes the bundle non-distributable.
106 symlink = 0
107
108 # Verbosity level.
109 verbosity = 1
Just van Rossumad33d722002-11-21 10:23:04 +0000110
Just van Rossumceeb9622002-11-21 23:19:37 +0000111 def setup(self):
Just van Rossumda302da2002-11-23 22:26:44 +0000112 # XXX rethink self.name munging, this is brittle.
Just van Rossumceeb9622002-11-21 23:19:37 +0000113 self.name, ext = os.path.splitext(self.name)
114 if not ext:
115 ext = ".bundle"
Just van Rossumda302da2002-11-23 22:26:44 +0000116 bundleextension = ext
Just van Rossumceeb9622002-11-21 23:19:37 +0000117 # misc (derived) attributes
Just van Rossumda302da2002-11-23 22:26:44 +0000118 self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
Just van Rossumceeb9622002-11-21 23:19:37 +0000119
Just van Rossumda302da2002-11-23 22:26:44 +0000120 plist = self.plist
Just van Rossumceeb9622002-11-21 23:19:37 +0000121 plist.CFBundleName = self.name
122 plist.CFBundlePackageType = self.type
Just van Rossume6b49022002-11-24 01:23:45 +0000123 if self.creator is None:
124 if hasattr(plist, "CFBundleSignature"):
125 self.creator = plist.CFBundleSignature
126 else:
127 self.creator = "????"
Just van Rossumceeb9622002-11-21 23:19:37 +0000128 plist.CFBundleSignature = self.creator
Just van Rossum9896ea22003-01-13 23:30:04 +0000129 if not hasattr(plist, "CFBundleIdentifier"):
130 plist.CFBundleIdentifier = self.name
Just van Rossumceeb9622002-11-21 23:19:37 +0000131
Just van Rossumad33d722002-11-21 10:23:04 +0000132 def build(self):
133 """Build the bundle."""
134 builddir = self.builddir
135 if builddir and not os.path.exists(builddir):
136 os.mkdir(builddir)
137 self.message("Building %s" % repr(self.bundlepath), 1)
138 if os.path.exists(self.bundlepath):
139 shutil.rmtree(self.bundlepath)
140 os.mkdir(self.bundlepath)
141 self.preProcess()
142 self._copyFiles()
143 self._addMetaFiles()
144 self.postProcess()
Just van Rossum535ffa22002-11-29 20:06:52 +0000145 self.message("Done.", 1)
Just van Rossumad33d722002-11-21 10:23:04 +0000146
147 def preProcess(self):
148 """Hook for subclasses."""
149 pass
150 def postProcess(self):
151 """Hook for subclasses."""
152 pass
153
154 def _addMetaFiles(self):
155 contents = pathjoin(self.bundlepath, "Contents")
156 makedirs(contents)
157 #
158 # Write Contents/PkgInfo
159 assert len(self.type) == len(self.creator) == 4, \
160 "type and creator must be 4-byte strings."
161 pkginfo = pathjoin(contents, "PkgInfo")
162 f = open(pkginfo, "wb")
163 f.write(self.type + self.creator)
164 f.close()
165 #
166 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000167 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000168 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000169
170 def _copyFiles(self):
171 files = self.files[:]
172 for path in self.resources:
173 files.append((path, pathjoin("Contents", "Resources",
174 os.path.basename(path))))
Just van Rossum15624d82003-03-21 09:26:59 +0000175 for path in self.libs:
176 files.append((path, pathjoin("Contents", "Frameworks",
177 os.path.basename(path))))
Just van Rossumad33d722002-11-21 10:23:04 +0000178 if self.symlink:
179 self.message("Making symbolic links", 1)
180 msg = "Making symlink from"
181 else:
182 self.message("Copying files", 1)
183 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000184 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000185 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000186 if os.path.isdir(src):
187 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
188 else:
189 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000190 dst = pathjoin(self.bundlepath, dst)
191 if self.symlink:
192 symlink(src, dst, mkdirs=1)
193 else:
194 copy(src, dst, mkdirs=1)
195
196 def message(self, msg, level=0):
197 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000198 indent = ""
199 if level > 1:
200 indent = (level - 1) * " "
201 sys.stderr.write(indent + msg + "\n")
202
203 def report(self):
204 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000205 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000206
207
Just van Rossumcef32882002-11-26 00:34:52 +0000208if __debug__:
209 PYC_EXT = ".pyc"
210else:
211 PYC_EXT = ".pyo"
212
213MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000214USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000215
216# For standalone apps, we have our own minimal site.py. We don't need
217# all the cruft of the real site.py.
218SITE_PY = """\
219import sys
220del sys.path[1:] # sys.path[0] is Contents/Resources/
221"""
222
Just van Rossum109ecbf2003-01-02 13:13:01 +0000223if USE_ZIPIMPORT:
224 ZIP_ARCHIVE = "Modules.zip"
225 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
226 def getPycData(fullname, code, ispkg):
227 if ispkg:
228 fullname += ".__init__"
229 path = fullname.replace(".", os.sep) + PYC_EXT
230 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000231
Just van Rossum74bdca82002-11-28 11:30:56 +0000232SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossum7322b1a2003-02-25 20:15:40 +0000233
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000234#
235# Extension modules can't be in the modules zip archive, so a placeholder
236# is added instead, that loads the extension from a specified location.
237#
Just van Rossum535ffa22002-11-29 20:06:52 +0000238EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000239def __load():
240 import imp, sys, os
241 for p in sys.path:
242 path = os.path.join(p, "%(filename)s")
243 if os.path.exists(path):
244 break
245 else:
246 assert 0, "file not found: %(filename)s"
247 mod = imp.load_dynamic("%(name)s", path)
248
249__load()
250del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000251"""
252
Just van Rossumcef32882002-11-26 00:34:52 +0000253MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
254 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
255 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
256]
257
258STRIP_EXEC = "/usr/bin/strip"
259
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000260#
261# We're using a stock interpreter to run the app, yet we need
262# a way to pass the Python main program to the interpreter. The
263# bootstrapping script fires up the interpreter with the right
264# arguments. os.execve() is used as OSX doesn't like us to
265# start a real new process. Also, the executable name must match
266# the CFBundleExecutable value in the Info.plist, so we lie
267# deliberately with argv[0]. The actual Python executable is
268# passed in an environment variable so we can "repair"
269# sys.executable later.
270#
Just van Rossum74bdca82002-11-28 11:30:56 +0000271BOOTSTRAP_SCRIPT = """\
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000272#!%(hashbang)s
Just van Rossumad33d722002-11-21 10:23:04 +0000273
Just van Rossum7322b1a2003-02-25 20:15:40 +0000274import sys, os
275execdir = os.path.dirname(sys.argv[0])
276executable = os.path.join(execdir, "%(executable)s")
277resdir = os.path.join(os.path.dirname(execdir), "Resources")
Just van Rossum15624d82003-03-21 09:26:59 +0000278libdir = os.path.join(os.path.dirname(execdir), "Frameworks")
Just van Rossum7322b1a2003-02-25 20:15:40 +0000279mainprogram = os.path.join(resdir, "%(mainprogram)s")
280
281sys.argv.insert(1, mainprogram)
282os.environ["PYTHONPATH"] = resdir
Just van Rossum82ad32e2003-03-21 11:32:37 +0000283if %(standalone)s:
284 os.environ["PYTHONHOME"] = resdir
Just van Rossum7322b1a2003-02-25 20:15:40 +0000285os.environ["PYTHONEXECUTABLE"] = executable
Just van Rossum15624d82003-03-21 09:26:59 +0000286os.environ["DYLD_LIBRARY_PATH"] = libdir
Just van Rossum7322b1a2003-02-25 20:15:40 +0000287os.execve(executable, sys.argv, os.environ)
Just van Rossumad33d722002-11-21 10:23:04 +0000288"""
289
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000290
291#
292# Optional wrapper that converts "dropped files" into sys.argv values.
293#
294ARGV_EMULATOR = """\
Jack Jansena03adde2003-02-18 23:29:46 +0000295import argvemulator, os
296
297argvemulator.ArgvCollector().mainloop()
298execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
299"""
Just van Rossumcef32882002-11-26 00:34:52 +0000300
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000301
Just van Rossumad33d722002-11-21 10:23:04 +0000302class AppBuilder(BundleBuilder):
303
Jack Jansencc81b802003-03-05 14:42:18 +0000304 # Override type of the bundle.
Jack Jansen620c0832003-03-05 14:44:54 +0000305 type = "APPL"
Jack Jansencc81b802003-03-05 14:42:18 +0000306
307 # platform, name of the subfolder of Contents that contains the executable.
308 platform = "MacOS"
309
Just van Rossumda302da2002-11-23 22:26:44 +0000310 # A Python main program. If this argument is given, the main
311 # executable in the bundle will be a small wrapper that invokes
312 # the main program. (XXX Discuss why.)
313 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000314
Just van Rossumda302da2002-11-23 22:26:44 +0000315 # The main executable. If a Python main program is specified
316 # the executable will be copied to Resources and be invoked
317 # by the wrapper program mentioned above. Otherwise it will
318 # simply be used as the main executable.
319 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000320
Just van Rossumda302da2002-11-23 22:26:44 +0000321 # The name of the main nib, for Cocoa apps. *Must* be specified
322 # when building a Cocoa app.
323 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000324
Just van Rossum2aa09562003-02-01 08:34:46 +0000325 # The name of the icon file to be copied to Resources and used for
326 # the Finder icon.
327 iconfile = None
328
Just van Rossumda302da2002-11-23 22:26:44 +0000329 # Symlink the executable instead of copying it.
330 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000331
Just van Rossumcef32882002-11-26 00:34:52 +0000332 # If True, build standalone app.
333 standalone = 0
Jack Jansena03adde2003-02-18 23:29:46 +0000334
335 # If True, add a real main program that emulates sys.argv before calling
336 # mainprogram
337 argv_emulation = 0
Just van Rossumcef32882002-11-26 00:34:52 +0000338
339 # The following attributes are only used when building a standalone app.
340
341 # Exclude these modules.
342 excludeModules = []
343
344 # Include these modules.
345 includeModules = []
346
347 # Include these packages.
348 includePackages = []
349
350 # Strip binaries.
351 strip = 0
352
Just van Rossumcef32882002-11-26 00:34:52 +0000353 # Found Python modules: [(name, codeobject, ispkg), ...]
354 pymodules = []
355
356 # Modules that modulefinder couldn't find:
357 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000358 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000359
360 # List of all binaries (executables or shared libs), for stripping purposes
361 binaries = []
362
Just van Rossumceeb9622002-11-21 23:19:37 +0000363 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000364 if self.standalone and self.mainprogram is None:
365 raise BundleBuilderError, ("must specify 'mainprogram' when "
366 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000367 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000368 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000369 "'executable' and 'mainprogram'")
370
Jack Jansencc81b802003-03-05 14:42:18 +0000371 self.execdir = pathjoin("Contents", self.platform)
372
Just van Rossumceeb9622002-11-21 23:19:37 +0000373 if self.name is not None:
374 pass
375 elif self.mainprogram is not None:
376 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
377 elif executable is not None:
378 self.name = os.path.splitext(os.path.basename(self.executable))[0]
379 if self.name[-4:] != ".app":
380 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000381
Just van Rossum74bdca82002-11-28 11:30:56 +0000382 if self.executable is None:
383 if not self.standalone:
384 self.symlink_exec = 1
385 self.executable = sys.executable
386
Just van Rossumceeb9622002-11-21 23:19:37 +0000387 if self.nibname:
388 self.plist.NSMainNibFile = self.nibname
389 if not hasattr(self.plist, "NSPrincipalClass"):
390 self.plist.NSPrincipalClass = "NSApplication"
391
392 BundleBuilder.setup(self)
393
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000394 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000395
Just van Rossumcef32882002-11-26 00:34:52 +0000396 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000397 self.findDependencies()
398
Just van Rossumf7aba232002-11-22 00:31:50 +0000399 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000400 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000401 if self.executable is not None:
402 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000403 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000404 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000405 execname = os.path.basename(self.executable)
406 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000407 if not self.symlink_exec:
408 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000409 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000410 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000411
412 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000413 mainprogram = os.path.basename(self.mainprogram)
414 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
Jack Jansena03adde2003-02-18 23:29:46 +0000415 if self.argv_emulation:
416 # Change the main program, and create the helper main program (which
417 # does argv collection and then calls the real main).
418 # Also update the included modules (if we're creating a standalone
419 # program) and the plist
420 realmainprogram = mainprogram
421 mainprogram = '__argvemulator_' + mainprogram
422 resdirpath = pathjoin(self.bundlepath, resdir)
423 mainprogrampath = pathjoin(resdirpath, mainprogram)
424 makedirs(resdirpath)
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000425 open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
Jack Jansena03adde2003-02-18 23:29:46 +0000426 if self.standalone:
427 self.includeModules.append("argvemulator")
428 self.includeModules.append("os")
429 if not self.plist.has_key("CFBundleDocumentTypes"):
430 self.plist["CFBundleDocumentTypes"] = [
431 { "CFBundleTypeOSTypes" : [
432 "****",
433 "fold",
434 "disk"],
435 "CFBundleTypeRole": "Viewer"}]
Just van Rossum24884f72002-11-29 21:22:33 +0000436 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000437 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000438 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000439 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000440 makedirs(execdir)
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000441 if self.standalone:
442 # XXX we're screwed when the end user has deleted
443 # /usr/bin/python
444 hashbang = "/usr/bin/python"
445 else:
446 hashbang = sys.executable
447 while os.path.islink(hashbang):
448 hashbang = os.readlink(hashbang)
Just van Rossum82ad32e2003-03-21 11:32:37 +0000449 standalone = self.standalone
Just van Rossum24884f72002-11-29 21:22:33 +0000450 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
451 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000452
Just van Rossum2aa09562003-02-01 08:34:46 +0000453 if self.iconfile is not None:
454 iconbase = os.path.basename(self.iconfile)
455 self.plist.CFBundleIconFile = iconbase
456 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
457
Just van Rossum16aebf72002-11-22 11:43:10 +0000458 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000459 if self.standalone:
460 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000461 if self.strip and not self.symlink:
462 self.stripBinaries()
463
Just van Rossum16aebf72002-11-22 11:43:10 +0000464 if self.symlink_exec and self.executable:
465 self.message("Symlinking executable %s to %s" % (self.executable,
466 self.execpath), 2)
467 dst = pathjoin(self.bundlepath, self.execpath)
468 makedirs(os.path.dirname(dst))
469 os.symlink(os.path.abspath(self.executable), dst)
470
Just van Rossum74bdca82002-11-28 11:30:56 +0000471 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000472 self.reportMissing()
473
474 def addPythonModules(self):
475 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000476
Just van Rossum109ecbf2003-01-02 13:13:01 +0000477 if USE_ZIPIMPORT:
478 # Create a zip file containing all modules as pyc.
479 import zipfile
480 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000481 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000482 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
483 for name, code, ispkg in self.pymodules:
484 self.message("Adding Python module %s" % name, 2)
485 path, pyc = getPycData(name, code, ispkg)
486 zf.writestr(path, pyc)
487 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000488 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000489 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
490 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000491 writePyc(SITE_CO, sitepath)
492 else:
493 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000494 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000495 if ispkg:
496 name += ".__init__"
497 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000498 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000499
500 if ispkg:
501 self.message("Adding Python package %s" % path, 2)
502 else:
503 self.message("Adding Python module %s" % path, 2)
504
505 abspath = pathjoin(self.bundlepath, path)
506 makedirs(os.path.dirname(abspath))
507 writePyc(code, abspath)
508
509 def stripBinaries(self):
510 if not os.path.exists(STRIP_EXEC):
511 self.message("Error: can't strip binaries: no strip program at "
512 "%s" % STRIP_EXEC, 0)
513 else:
514 self.message("Stripping binaries", 1)
515 for relpath in self.binaries:
516 self.message("Stripping %s" % relpath, 2)
517 abspath = pathjoin(self.bundlepath, relpath)
518 assert not os.path.islink(abspath)
519 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
520
521 def findDependencies(self):
522 self.message("Finding module dependencies", 1)
523 import modulefinder
524 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000525 if USE_ZIPIMPORT:
526 # zipimport imports zlib, must add it manually
527 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000528 # manually add our own site.py
529 site = mf.add_module("site")
530 site.__code__ = SITE_CO
531 mf.scan_code(SITE_CO, site)
532
Just van Rossum7322b1a2003-02-25 20:15:40 +0000533 # warnings.py gets imported implicitly from C
534 mf.import_hook("warnings")
535
Just van Rossumcef32882002-11-26 00:34:52 +0000536 includeModules = self.includeModules[:]
537 for name in self.includePackages:
538 includeModules.extend(findPackageContents(name).keys())
539 for name in includeModules:
540 try:
541 mf.import_hook(name)
542 except ImportError:
543 self.missingModules.append(name)
544
Just van Rossumcef32882002-11-26 00:34:52 +0000545 mf.run_script(self.mainprogram)
546 modules = mf.modules.items()
547 modules.sort()
548 for name, mod in modules:
549 if mod.__file__ and mod.__code__ is None:
550 # C extension
551 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000552 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000553 if USE_ZIPIMPORT:
554 # Python modules are stored in a Zip archive, but put
555 # extensions in Contents/Resources/.a and add a tiny "loader"
556 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000557 dstpath = pathjoin("Contents", "Resources", filename)
558 source = EXT_LOADER % {"name": name, "filename": filename}
559 code = compile(source, "<dynloader for %s>" % name, "exec")
560 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000561 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000562 # just copy the file
563 dstpath = name.split(".")[:-1] + [filename]
564 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000565 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000566 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000567 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000568 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000569 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000570 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000571 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000572 self.pymodules.append((name, mod.__code__, ispkg))
573
Just van Rossum74bdca82002-11-28 11:30:56 +0000574 if hasattr(mf, "any_missing_maybe"):
575 missing, maybe = mf.any_missing_maybe()
576 else:
577 missing = mf.any_missing()
578 maybe = []
579 self.missingModules.extend(missing)
580 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000581
582 def reportMissing(self):
583 missing = [name for name in self.missingModules
584 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000585 if self.maybeMissingModules:
586 maybe = self.maybeMissingModules
587 else:
588 maybe = [name for name in missing if "." in name]
589 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000590 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000591 maybe.sort()
592 if maybe:
593 self.message("Warning: couldn't find the following submodules:", 1)
594 self.message(" (Note that these could be false alarms -- "
595 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000596 self.message(" possible to distinguish between \"from package "
597 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000598 self.message(" and \"from package import name\")", 1)
599 for name in maybe:
600 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000601 if missing:
602 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000603 for name in missing:
604 self.message(" ? " + name, 1)
605
606 def report(self):
607 # XXX something decent
608 import pprint
609 pprint.pprint(self.__dict__)
610 if self.standalone:
611 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000612
613#
614# Utilities.
615#
616
617SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
618identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
619
620def findPackageContents(name, searchpath=None):
621 head = name.split(".")[-1]
622 if identifierRE.match(head) is None:
623 return {}
624 try:
625 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
626 except ImportError:
627 return {}
628 modules = {name: None}
629 if tp == imp.PKG_DIRECTORY and path:
630 files = os.listdir(path)
631 for sub in files:
632 sub, ext = os.path.splitext(sub)
633 fullname = name + "." + sub
634 if sub != "__init__" and fullname not in modules:
635 modules.update(findPackageContents(fullname, [path]))
636 return modules
637
638def writePyc(code, path):
639 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000640 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000641 f.write("\0" * 4) # don't bother about a time stamp
642 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000643 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000644
Just van Rossumad33d722002-11-21 10:23:04 +0000645def copy(src, dst, mkdirs=0):
646 """Copy a file or a directory."""
647 if mkdirs:
648 makedirs(os.path.dirname(dst))
649 if os.path.isdir(src):
650 shutil.copytree(src, dst)
651 else:
652 shutil.copy2(src, dst)
653
654def copytodir(src, dstdir):
655 """Copy a file or a directory to an existing directory."""
656 dst = pathjoin(dstdir, os.path.basename(src))
657 copy(src, dst)
658
659def makedirs(dir):
660 """Make all directories leading up to 'dir' including the leaf
661 directory. Don't moan if any path element already exists."""
662 try:
663 os.makedirs(dir)
664 except OSError, why:
665 if why.errno != errno.EEXIST:
666 raise
667
668def symlink(src, dst, mkdirs=0):
669 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000670 if not os.path.exists(src):
671 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000672 if mkdirs:
673 makedirs(os.path.dirname(dst))
674 os.symlink(os.path.abspath(src), dst)
675
676def pathjoin(*args):
677 """Safe wrapper for os.path.join: asserts that all but the first
678 argument are relative paths."""
679 for seg in args[1:]:
680 assert seg[0] != "/"
681 return os.path.join(*args)
682
683
Just van Rossumceeb9622002-11-21 23:19:37 +0000684cmdline_doc = """\
685Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000686 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000687 python mybuildscript.py [options] command
688
689Commands:
690 build build the application
691 report print a report
692
693Options:
694 -b, --builddir=DIR the build directory; defaults to "build"
695 -n, --name=NAME application name
696 -r, --resource=FILE extra file or folder to be copied to Resources
Just van Rossum7215e082003-02-25 21:00:55 +0000697 -f, --file=SRC:DST extra file or folder to be copied into the bundle;
698 DST must be a path relative to the bundle root
Just van Rossumceeb9622002-11-21 23:19:37 +0000699 -e, --executable=FILE the executable to be used
700 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000701 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000702 -p, --plist=FILE .plist file (default: generate one)
703 --nib=NAME main nib name
704 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000705 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000706 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000707 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000708 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000709 --standalone build a standalone application, which is fully
710 independent of a Python installation
Just van Rossum15624d82003-03-21 09:26:59 +0000711 --lib=FILE shared library or framework to be copied into
712 the bundle
Just van Rossumcef32882002-11-26 00:34:52 +0000713 -x, --exclude=MODULE exclude module (with --standalone)
714 -i, --include=MODULE include module (with --standalone)
715 --package=PACKAGE include a whole package (with --standalone)
716 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000717 -v, --verbose increase verbosity level
718 -q, --quiet decrease verbosity level
719 -h, --help print this message
720"""
721
722def usage(msg=None):
723 if msg:
724 print msg
725 print cmdline_doc
726 sys.exit(1)
727
728def main(builder=None):
729 if builder is None:
730 builder = AppBuilder(verbosity=1)
731
Jack Jansen00cbf072003-02-24 16:27:08 +0000732 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
Just van Rossum7215e082003-02-25 21:00:55 +0000733 longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000734 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000735 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum15624d82003-03-21 09:26:59 +0000736 "exclude=", "include=", "package=", "strip", "iconfile=",
737 "lib=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000738
739 try:
740 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
741 except getopt.error:
742 usage()
743
744 for opt, arg in options:
745 if opt in ('-b', '--builddir'):
746 builder.builddir = arg
747 elif opt in ('-n', '--name'):
748 builder.name = arg
749 elif opt in ('-r', '--resource'):
750 builder.resources.append(arg)
Just van Rossum7215e082003-02-25 21:00:55 +0000751 elif opt in ('-f', '--file'):
Jack Jansen00cbf072003-02-24 16:27:08 +0000752 srcdst = arg.split(':')
753 if len(srcdst) != 2:
Just van Rossum49833312003-02-25 21:08:12 +0000754 usage("-f or --file argument must be two paths, "
755 "separated by a colon")
Jack Jansen00cbf072003-02-24 16:27:08 +0000756 builder.files.append(srcdst)
Just van Rossumceeb9622002-11-21 23:19:37 +0000757 elif opt in ('-e', '--executable'):
758 builder.executable = arg
759 elif opt in ('-m', '--mainprogram'):
760 builder.mainprogram = arg
Jack Jansena03adde2003-02-18 23:29:46 +0000761 elif opt in ('-a', '--argv'):
762 builder.argv_emulation = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000763 elif opt in ('-c', '--creator'):
764 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000765 elif opt == '--iconfile':
766 builder.iconfile = arg
Just van Rossum15624d82003-03-21 09:26:59 +0000767 elif opt == "--lib":
768 builder.libs.append(arg)
Just van Rossumceeb9622002-11-21 23:19:37 +0000769 elif opt == "--nib":
770 builder.nibname = arg
771 elif opt in ('-p', '--plist'):
772 builder.plist = Plist.fromFile(arg)
773 elif opt in ('-l', '--link'):
774 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000775 elif opt == '--link-exec':
776 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000777 elif opt in ('-h', '--help'):
778 usage()
779 elif opt in ('-v', '--verbose'):
780 builder.verbosity += 1
781 elif opt in ('-q', '--quiet'):
782 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000783 elif opt == '--standalone':
784 builder.standalone = 1
785 elif opt in ('-x', '--exclude'):
786 builder.excludeModules.append(arg)
787 elif opt in ('-i', '--include'):
788 builder.includeModules.append(arg)
789 elif opt == '--package':
790 builder.includePackages.append(arg)
791 elif opt == '--strip':
792 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000793
794 if len(args) != 1:
795 usage("Must specify one command ('build', 'report' or 'help')")
796 command = args[0]
797
798 if command == "build":
799 builder.setup()
800 builder.build()
801 elif command == "report":
802 builder.setup()
803 builder.report()
804 elif command == "help":
805 usage()
806 else:
807 usage("Unknown command '%s'" % command)
808
809
Just van Rossumad33d722002-11-21 10:23:04 +0000810def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000811 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000812 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000813
814
815if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000816 main()