blob: 2a324993edf5ffecddfa4557ef62feed62d7ac11 [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 Rossuma87e4472003-03-20 21:37:05 +0000283os.environ["PYTHONHOME"] = resdir
Just van Rossum7322b1a2003-02-25 20:15:40 +0000284os.environ["PYTHONEXECUTABLE"] = executable
Just van Rossum15624d82003-03-21 09:26:59 +0000285os.environ["DYLD_LIBRARY_PATH"] = libdir
Just van Rossum7322b1a2003-02-25 20:15:40 +0000286os.execve(executable, sys.argv, os.environ)
Just van Rossumad33d722002-11-21 10:23:04 +0000287"""
288
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000289
290#
291# Optional wrapper that converts "dropped files" into sys.argv values.
292#
293ARGV_EMULATOR = """\
Jack Jansena03adde2003-02-18 23:29:46 +0000294import argvemulator, os
295
296argvemulator.ArgvCollector().mainloop()
297execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
298"""
Just van Rossumcef32882002-11-26 00:34:52 +0000299
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000300
Just van Rossumad33d722002-11-21 10:23:04 +0000301class AppBuilder(BundleBuilder):
302
Jack Jansencc81b802003-03-05 14:42:18 +0000303 # Override type of the bundle.
Jack Jansen620c0832003-03-05 14:44:54 +0000304 type = "APPL"
Jack Jansencc81b802003-03-05 14:42:18 +0000305
306 # platform, name of the subfolder of Contents that contains the executable.
307 platform = "MacOS"
308
Just van Rossumda302da2002-11-23 22:26:44 +0000309 # A Python main program. If this argument is given, the main
310 # executable in the bundle will be a small wrapper that invokes
311 # the main program. (XXX Discuss why.)
312 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000313
Just van Rossumda302da2002-11-23 22:26:44 +0000314 # The main executable. If a Python main program is specified
315 # the executable will be copied to Resources and be invoked
316 # by the wrapper program mentioned above. Otherwise it will
317 # simply be used as the main executable.
318 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000319
Just van Rossumda302da2002-11-23 22:26:44 +0000320 # The name of the main nib, for Cocoa apps. *Must* be specified
321 # when building a Cocoa app.
322 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000323
Just van Rossum2aa09562003-02-01 08:34:46 +0000324 # The name of the icon file to be copied to Resources and used for
325 # the Finder icon.
326 iconfile = None
327
Just van Rossumda302da2002-11-23 22:26:44 +0000328 # Symlink the executable instead of copying it.
329 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000330
Just van Rossumcef32882002-11-26 00:34:52 +0000331 # If True, build standalone app.
332 standalone = 0
Jack Jansena03adde2003-02-18 23:29:46 +0000333
334 # If True, add a real main program that emulates sys.argv before calling
335 # mainprogram
336 argv_emulation = 0
Just van Rossumcef32882002-11-26 00:34:52 +0000337
338 # The following attributes are only used when building a standalone app.
339
340 # Exclude these modules.
341 excludeModules = []
342
343 # Include these modules.
344 includeModules = []
345
346 # Include these packages.
347 includePackages = []
348
349 # Strip binaries.
350 strip = 0
351
Just van Rossumcef32882002-11-26 00:34:52 +0000352 # Found Python modules: [(name, codeobject, ispkg), ...]
353 pymodules = []
354
355 # Modules that modulefinder couldn't find:
356 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000357 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000358
359 # List of all binaries (executables or shared libs), for stripping purposes
360 binaries = []
361
Just van Rossumceeb9622002-11-21 23:19:37 +0000362 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000363 if self.standalone and self.mainprogram is None:
364 raise BundleBuilderError, ("must specify 'mainprogram' when "
365 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000366 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000367 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000368 "'executable' and 'mainprogram'")
369
Jack Jansencc81b802003-03-05 14:42:18 +0000370 self.execdir = pathjoin("Contents", self.platform)
371
Just van Rossumceeb9622002-11-21 23:19:37 +0000372 if self.name is not None:
373 pass
374 elif self.mainprogram is not None:
375 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
376 elif executable is not None:
377 self.name = os.path.splitext(os.path.basename(self.executable))[0]
378 if self.name[-4:] != ".app":
379 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000380
Just van Rossum74bdca82002-11-28 11:30:56 +0000381 if self.executable is None:
382 if not self.standalone:
383 self.symlink_exec = 1
384 self.executable = sys.executable
385
Just van Rossumceeb9622002-11-21 23:19:37 +0000386 if self.nibname:
387 self.plist.NSMainNibFile = self.nibname
388 if not hasattr(self.plist, "NSPrincipalClass"):
389 self.plist.NSPrincipalClass = "NSApplication"
390
391 BundleBuilder.setup(self)
392
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000393 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000394
Just van Rossumcef32882002-11-26 00:34:52 +0000395 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000396 self.findDependencies()
397
Just van Rossumf7aba232002-11-22 00:31:50 +0000398 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000399 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000400 if self.executable is not None:
401 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000402 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000403 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000404 execname = os.path.basename(self.executable)
405 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000406 if not self.symlink_exec:
407 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000408 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000409 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000410
411 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000412 mainprogram = os.path.basename(self.mainprogram)
413 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
Jack Jansena03adde2003-02-18 23:29:46 +0000414 if self.argv_emulation:
415 # Change the main program, and create the helper main program (which
416 # does argv collection and then calls the real main).
417 # Also update the included modules (if we're creating a standalone
418 # program) and the plist
419 realmainprogram = mainprogram
420 mainprogram = '__argvemulator_' + mainprogram
421 resdirpath = pathjoin(self.bundlepath, resdir)
422 mainprogrampath = pathjoin(resdirpath, mainprogram)
423 makedirs(resdirpath)
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000424 open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
Jack Jansena03adde2003-02-18 23:29:46 +0000425 if self.standalone:
426 self.includeModules.append("argvemulator")
427 self.includeModules.append("os")
428 if not self.plist.has_key("CFBundleDocumentTypes"):
429 self.plist["CFBundleDocumentTypes"] = [
430 { "CFBundleTypeOSTypes" : [
431 "****",
432 "fold",
433 "disk"],
434 "CFBundleTypeRole": "Viewer"}]
Just van Rossum24884f72002-11-29 21:22:33 +0000435 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000436 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000437 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000438 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000439 makedirs(execdir)
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000440 if self.standalone:
441 # XXX we're screwed when the end user has deleted
442 # /usr/bin/python
443 hashbang = "/usr/bin/python"
444 else:
445 hashbang = sys.executable
446 while os.path.islink(hashbang):
447 hashbang = os.readlink(hashbang)
Just van Rossum24884f72002-11-29 21:22:33 +0000448 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
449 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000450
Just van Rossum2aa09562003-02-01 08:34:46 +0000451 if self.iconfile is not None:
452 iconbase = os.path.basename(self.iconfile)
453 self.plist.CFBundleIconFile = iconbase
454 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
455
Just van Rossum16aebf72002-11-22 11:43:10 +0000456 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000457 if self.standalone:
458 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000459 if self.strip and not self.symlink:
460 self.stripBinaries()
461
Just van Rossum16aebf72002-11-22 11:43:10 +0000462 if self.symlink_exec and self.executable:
463 self.message("Symlinking executable %s to %s" % (self.executable,
464 self.execpath), 2)
465 dst = pathjoin(self.bundlepath, self.execpath)
466 makedirs(os.path.dirname(dst))
467 os.symlink(os.path.abspath(self.executable), dst)
468
Just van Rossum74bdca82002-11-28 11:30:56 +0000469 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000470 self.reportMissing()
471
472 def addPythonModules(self):
473 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000474
Just van Rossum109ecbf2003-01-02 13:13:01 +0000475 if USE_ZIPIMPORT:
476 # Create a zip file containing all modules as pyc.
477 import zipfile
478 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000479 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000480 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
481 for name, code, ispkg in self.pymodules:
482 self.message("Adding Python module %s" % name, 2)
483 path, pyc = getPycData(name, code, ispkg)
484 zf.writestr(path, pyc)
485 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000486 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000487 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
488 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000489 writePyc(SITE_CO, sitepath)
490 else:
491 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000492 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000493 if ispkg:
494 name += ".__init__"
495 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000496 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000497
498 if ispkg:
499 self.message("Adding Python package %s" % path, 2)
500 else:
501 self.message("Adding Python module %s" % path, 2)
502
503 abspath = pathjoin(self.bundlepath, path)
504 makedirs(os.path.dirname(abspath))
505 writePyc(code, abspath)
506
507 def stripBinaries(self):
508 if not os.path.exists(STRIP_EXEC):
509 self.message("Error: can't strip binaries: no strip program at "
510 "%s" % STRIP_EXEC, 0)
511 else:
512 self.message("Stripping binaries", 1)
513 for relpath in self.binaries:
514 self.message("Stripping %s" % relpath, 2)
515 abspath = pathjoin(self.bundlepath, relpath)
516 assert not os.path.islink(abspath)
517 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
518
519 def findDependencies(self):
520 self.message("Finding module dependencies", 1)
521 import modulefinder
522 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000523 if USE_ZIPIMPORT:
524 # zipimport imports zlib, must add it manually
525 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000526 # manually add our own site.py
527 site = mf.add_module("site")
528 site.__code__ = SITE_CO
529 mf.scan_code(SITE_CO, site)
530
Just van Rossum7322b1a2003-02-25 20:15:40 +0000531 # warnings.py gets imported implicitly from C
532 mf.import_hook("warnings")
533
Just van Rossumcef32882002-11-26 00:34:52 +0000534 includeModules = self.includeModules[:]
535 for name in self.includePackages:
536 includeModules.extend(findPackageContents(name).keys())
537 for name in includeModules:
538 try:
539 mf.import_hook(name)
540 except ImportError:
541 self.missingModules.append(name)
542
Just van Rossumcef32882002-11-26 00:34:52 +0000543 mf.run_script(self.mainprogram)
544 modules = mf.modules.items()
545 modules.sort()
546 for name, mod in modules:
547 if mod.__file__ and mod.__code__ is None:
548 # C extension
549 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000550 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000551 if USE_ZIPIMPORT:
552 # Python modules are stored in a Zip archive, but put
553 # extensions in Contents/Resources/.a and add a tiny "loader"
554 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000555 dstpath = pathjoin("Contents", "Resources", filename)
556 source = EXT_LOADER % {"name": name, "filename": filename}
557 code = compile(source, "<dynloader for %s>" % name, "exec")
558 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000559 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000560 # just copy the file
561 dstpath = name.split(".")[:-1] + [filename]
562 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000563 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000564 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000565 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000566 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000567 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000568 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000569 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000570 self.pymodules.append((name, mod.__code__, ispkg))
571
Just van Rossum74bdca82002-11-28 11:30:56 +0000572 if hasattr(mf, "any_missing_maybe"):
573 missing, maybe = mf.any_missing_maybe()
574 else:
575 missing = mf.any_missing()
576 maybe = []
577 self.missingModules.extend(missing)
578 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000579
580 def reportMissing(self):
581 missing = [name for name in self.missingModules
582 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000583 if self.maybeMissingModules:
584 maybe = self.maybeMissingModules
585 else:
586 maybe = [name for name in missing if "." in name]
587 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000588 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000589 maybe.sort()
590 if maybe:
591 self.message("Warning: couldn't find the following submodules:", 1)
592 self.message(" (Note that these could be false alarms -- "
593 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000594 self.message(" possible to distinguish between \"from package "
595 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000596 self.message(" and \"from package import name\")", 1)
597 for name in maybe:
598 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000599 if missing:
600 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000601 for name in missing:
602 self.message(" ? " + name, 1)
603
604 def report(self):
605 # XXX something decent
606 import pprint
607 pprint.pprint(self.__dict__)
608 if self.standalone:
609 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000610
611#
612# Utilities.
613#
614
615SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
616identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
617
618def findPackageContents(name, searchpath=None):
619 head = name.split(".")[-1]
620 if identifierRE.match(head) is None:
621 return {}
622 try:
623 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
624 except ImportError:
625 return {}
626 modules = {name: None}
627 if tp == imp.PKG_DIRECTORY and path:
628 files = os.listdir(path)
629 for sub in files:
630 sub, ext = os.path.splitext(sub)
631 fullname = name + "." + sub
632 if sub != "__init__" and fullname not in modules:
633 modules.update(findPackageContents(fullname, [path]))
634 return modules
635
636def writePyc(code, path):
637 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000638 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000639 f.write("\0" * 4) # don't bother about a time stamp
640 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000641 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000642
Just van Rossumad33d722002-11-21 10:23:04 +0000643def copy(src, dst, mkdirs=0):
644 """Copy a file or a directory."""
645 if mkdirs:
646 makedirs(os.path.dirname(dst))
647 if os.path.isdir(src):
648 shutil.copytree(src, dst)
649 else:
650 shutil.copy2(src, dst)
651
652def copytodir(src, dstdir):
653 """Copy a file or a directory to an existing directory."""
654 dst = pathjoin(dstdir, os.path.basename(src))
655 copy(src, dst)
656
657def makedirs(dir):
658 """Make all directories leading up to 'dir' including the leaf
659 directory. Don't moan if any path element already exists."""
660 try:
661 os.makedirs(dir)
662 except OSError, why:
663 if why.errno != errno.EEXIST:
664 raise
665
666def symlink(src, dst, mkdirs=0):
667 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000668 if not os.path.exists(src):
669 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000670 if mkdirs:
671 makedirs(os.path.dirname(dst))
672 os.symlink(os.path.abspath(src), dst)
673
674def pathjoin(*args):
675 """Safe wrapper for os.path.join: asserts that all but the first
676 argument are relative paths."""
677 for seg in args[1:]:
678 assert seg[0] != "/"
679 return os.path.join(*args)
680
681
Just van Rossumceeb9622002-11-21 23:19:37 +0000682cmdline_doc = """\
683Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000684 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000685 python mybuildscript.py [options] command
686
687Commands:
688 build build the application
689 report print a report
690
691Options:
692 -b, --builddir=DIR the build directory; defaults to "build"
693 -n, --name=NAME application name
694 -r, --resource=FILE extra file or folder to be copied to Resources
Just van Rossum7215e082003-02-25 21:00:55 +0000695 -f, --file=SRC:DST extra file or folder to be copied into the bundle;
696 DST must be a path relative to the bundle root
Just van Rossumceeb9622002-11-21 23:19:37 +0000697 -e, --executable=FILE the executable to be used
698 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000699 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000700 -p, --plist=FILE .plist file (default: generate one)
701 --nib=NAME main nib name
702 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000703 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000704 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000705 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000706 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000707 --standalone build a standalone application, which is fully
708 independent of a Python installation
Just van Rossum15624d82003-03-21 09:26:59 +0000709 --lib=FILE shared library or framework to be copied into
710 the bundle
Just van Rossumcef32882002-11-26 00:34:52 +0000711 -x, --exclude=MODULE exclude module (with --standalone)
712 -i, --include=MODULE include module (with --standalone)
713 --package=PACKAGE include a whole package (with --standalone)
714 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000715 -v, --verbose increase verbosity level
716 -q, --quiet decrease verbosity level
717 -h, --help print this message
718"""
719
720def usage(msg=None):
721 if msg:
722 print msg
723 print cmdline_doc
724 sys.exit(1)
725
726def main(builder=None):
727 if builder is None:
728 builder = AppBuilder(verbosity=1)
729
Jack Jansen00cbf072003-02-24 16:27:08 +0000730 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
Just van Rossum7215e082003-02-25 21:00:55 +0000731 longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000732 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000733 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum15624d82003-03-21 09:26:59 +0000734 "exclude=", "include=", "package=", "strip", "iconfile=",
735 "lib=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000736
737 try:
738 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
739 except getopt.error:
740 usage()
741
742 for opt, arg in options:
743 if opt in ('-b', '--builddir'):
744 builder.builddir = arg
745 elif opt in ('-n', '--name'):
746 builder.name = arg
747 elif opt in ('-r', '--resource'):
748 builder.resources.append(arg)
Just van Rossum7215e082003-02-25 21:00:55 +0000749 elif opt in ('-f', '--file'):
Jack Jansen00cbf072003-02-24 16:27:08 +0000750 srcdst = arg.split(':')
751 if len(srcdst) != 2:
Just van Rossum49833312003-02-25 21:08:12 +0000752 usage("-f or --file argument must be two paths, "
753 "separated by a colon")
Jack Jansen00cbf072003-02-24 16:27:08 +0000754 builder.files.append(srcdst)
Just van Rossumceeb9622002-11-21 23:19:37 +0000755 elif opt in ('-e', '--executable'):
756 builder.executable = arg
757 elif opt in ('-m', '--mainprogram'):
758 builder.mainprogram = arg
Jack Jansena03adde2003-02-18 23:29:46 +0000759 elif opt in ('-a', '--argv'):
760 builder.argv_emulation = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000761 elif opt in ('-c', '--creator'):
762 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000763 elif opt == '--iconfile':
764 builder.iconfile = arg
Just van Rossum15624d82003-03-21 09:26:59 +0000765 elif opt == "--lib":
766 builder.libs.append(arg)
Just van Rossumceeb9622002-11-21 23:19:37 +0000767 elif opt == "--nib":
768 builder.nibname = arg
769 elif opt in ('-p', '--plist'):
770 builder.plist = Plist.fromFile(arg)
771 elif opt in ('-l', '--link'):
772 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000773 elif opt == '--link-exec':
774 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000775 elif opt in ('-h', '--help'):
776 usage()
777 elif opt in ('-v', '--verbose'):
778 builder.verbosity += 1
779 elif opt in ('-q', '--quiet'):
780 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000781 elif opt == '--standalone':
782 builder.standalone = 1
783 elif opt in ('-x', '--exclude'):
784 builder.excludeModules.append(arg)
785 elif opt in ('-i', '--include'):
786 builder.includeModules.append(arg)
787 elif opt == '--package':
788 builder.includePackages.append(arg)
789 elif opt == '--strip':
790 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000791
792 if len(args) != 1:
793 usage("Must specify one command ('build', 'report' or 'help')")
794 command = args[0]
795
796 if command == "build":
797 builder.setup()
798 builder.build()
799 elif command == "report":
800 builder.setup()
801 builder.report()
802 elif command == "help":
803 usage()
804 else:
805 usage("Unknown command '%s'" % command)
806
807
Just van Rossumad33d722002-11-21 10:23:04 +0000808def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000809 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000810 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000811
812
813if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000814 main()