blob: 8502f81c903edde7defaf759ae0856b57297bd4e [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.
86 type = "APPL"
87 # 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
100 # platform, name of the subfolder of Contents that contains the executable.
101 platform = "MacOS"
102
103 # Make symlinks instead copying files. This is handy during debugging, but
104 # makes the bundle non-distributable.
105 symlink = 0
106
107 # Verbosity level.
108 verbosity = 1
Just van Rossumad33d722002-11-21 10:23:04 +0000109
Just van Rossumceeb9622002-11-21 23:19:37 +0000110 def setup(self):
Just van Rossumda302da2002-11-23 22:26:44 +0000111 # XXX rethink self.name munging, this is brittle.
Just van Rossumceeb9622002-11-21 23:19:37 +0000112 self.name, ext = os.path.splitext(self.name)
113 if not ext:
114 ext = ".bundle"
Just van Rossumda302da2002-11-23 22:26:44 +0000115 bundleextension = ext
Just van Rossumceeb9622002-11-21 23:19:37 +0000116 # misc (derived) attributes
Just van Rossumda302da2002-11-23 22:26:44 +0000117 self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
Just van Rossumceeb9622002-11-21 23:19:37 +0000118 self.execdir = pathjoin("Contents", self.platform)
119
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))))
175 if self.symlink:
176 self.message("Making symbolic links", 1)
177 msg = "Making symlink from"
178 else:
179 self.message("Copying files", 1)
180 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000181 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000182 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000183 if os.path.isdir(src):
184 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
185 else:
186 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000187 dst = pathjoin(self.bundlepath, dst)
188 if self.symlink:
189 symlink(src, dst, mkdirs=1)
190 else:
191 copy(src, dst, mkdirs=1)
192
193 def message(self, msg, level=0):
194 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000195 indent = ""
196 if level > 1:
197 indent = (level - 1) * " "
198 sys.stderr.write(indent + msg + "\n")
199
200 def report(self):
201 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000202 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000203
204
Just van Rossumcef32882002-11-26 00:34:52 +0000205if __debug__:
206 PYC_EXT = ".pyc"
207else:
208 PYC_EXT = ".pyo"
209
210MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000211USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000212
213# For standalone apps, we have our own minimal site.py. We don't need
214# all the cruft of the real site.py.
215SITE_PY = """\
216import sys
217del sys.path[1:] # sys.path[0] is Contents/Resources/
218"""
219
Just van Rossum109ecbf2003-01-02 13:13:01 +0000220if USE_ZIPIMPORT:
221 ZIP_ARCHIVE = "Modules.zip"
222 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
223 def getPycData(fullname, code, ispkg):
224 if ispkg:
225 fullname += ".__init__"
226 path = fullname.replace(".", os.sep) + PYC_EXT
227 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000228
Just van Rossum74bdca82002-11-28 11:30:56 +0000229SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossum7322b1a2003-02-25 20:15:40 +0000230
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000231#
232# Extension modules can't be in the modules zip archive, so a placeholder
233# is added instead, that loads the extension from a specified location.
234#
Just van Rossum535ffa22002-11-29 20:06:52 +0000235EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000236def __load():
237 import imp, sys, os
238 for p in sys.path:
239 path = os.path.join(p, "%(filename)s")
240 if os.path.exists(path):
241 break
242 else:
243 assert 0, "file not found: %(filename)s"
244 mod = imp.load_dynamic("%(name)s", path)
245
246__load()
247del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000248"""
249
Just van Rossumcef32882002-11-26 00:34:52 +0000250MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
251 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
252 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
253]
254
255STRIP_EXEC = "/usr/bin/strip"
256
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000257#
258# We're using a stock interpreter to run the app, yet we need
259# a way to pass the Python main program to the interpreter. The
260# bootstrapping script fires up the interpreter with the right
261# arguments. os.execve() is used as OSX doesn't like us to
262# start a real new process. Also, the executable name must match
263# the CFBundleExecutable value in the Info.plist, so we lie
264# deliberately with argv[0]. The actual Python executable is
265# passed in an environment variable so we can "repair"
266# sys.executable later.
267#
Just van Rossum74bdca82002-11-28 11:30:56 +0000268BOOTSTRAP_SCRIPT = """\
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000269#!%(hashbang)s
Just van Rossumad33d722002-11-21 10:23:04 +0000270
Just van Rossum7322b1a2003-02-25 20:15:40 +0000271import sys, os
272execdir = os.path.dirname(sys.argv[0])
273executable = os.path.join(execdir, "%(executable)s")
274resdir = os.path.join(os.path.dirname(execdir), "Resources")
275mainprogram = os.path.join(resdir, "%(mainprogram)s")
276
277sys.argv.insert(1, mainprogram)
278os.environ["PYTHONPATH"] = resdir
279os.environ["PYTHONEXECUTABLE"] = executable
280os.execve(executable, sys.argv, os.environ)
Just van Rossumad33d722002-11-21 10:23:04 +0000281"""
282
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000283
284#
285# Optional wrapper that converts "dropped files" into sys.argv values.
286#
287ARGV_EMULATOR = """\
Jack Jansena03adde2003-02-18 23:29:46 +0000288import argvemulator, os
289
290argvemulator.ArgvCollector().mainloop()
291execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
292"""
Just van Rossumcef32882002-11-26 00:34:52 +0000293
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000294
Just van Rossumad33d722002-11-21 10:23:04 +0000295class AppBuilder(BundleBuilder):
296
Just van Rossumda302da2002-11-23 22:26:44 +0000297 # A Python main program. If this argument is given, the main
298 # executable in the bundle will be a small wrapper that invokes
299 # the main program. (XXX Discuss why.)
300 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000301
Just van Rossumda302da2002-11-23 22:26:44 +0000302 # The main executable. If a Python main program is specified
303 # the executable will be copied to Resources and be invoked
304 # by the wrapper program mentioned above. Otherwise it will
305 # simply be used as the main executable.
306 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000307
Just van Rossumda302da2002-11-23 22:26:44 +0000308 # The name of the main nib, for Cocoa apps. *Must* be specified
309 # when building a Cocoa app.
310 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000311
Just van Rossum2aa09562003-02-01 08:34:46 +0000312 # The name of the icon file to be copied to Resources and used for
313 # the Finder icon.
314 iconfile = None
315
Just van Rossumda302da2002-11-23 22:26:44 +0000316 # Symlink the executable instead of copying it.
317 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000318
Just van Rossumcef32882002-11-26 00:34:52 +0000319 # If True, build standalone app.
320 standalone = 0
Jack Jansena03adde2003-02-18 23:29:46 +0000321
322 # If True, add a real main program that emulates sys.argv before calling
323 # mainprogram
324 argv_emulation = 0
Just van Rossumcef32882002-11-26 00:34:52 +0000325
326 # The following attributes are only used when building a standalone app.
327
328 # Exclude these modules.
329 excludeModules = []
330
331 # Include these modules.
332 includeModules = []
333
334 # Include these packages.
335 includePackages = []
336
337 # Strip binaries.
338 strip = 0
339
Just van Rossumcef32882002-11-26 00:34:52 +0000340 # Found Python modules: [(name, codeobject, ispkg), ...]
341 pymodules = []
342
343 # Modules that modulefinder couldn't find:
344 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000345 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000346
347 # List of all binaries (executables or shared libs), for stripping purposes
348 binaries = []
349
Just van Rossumceeb9622002-11-21 23:19:37 +0000350 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000351 if self.standalone and self.mainprogram is None:
352 raise BundleBuilderError, ("must specify 'mainprogram' when "
353 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000354 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000355 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000356 "'executable' and 'mainprogram'")
357
358 if self.name is not None:
359 pass
360 elif self.mainprogram is not None:
361 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
362 elif executable is not None:
363 self.name = os.path.splitext(os.path.basename(self.executable))[0]
364 if self.name[-4:] != ".app":
365 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000366
Just van Rossum74bdca82002-11-28 11:30:56 +0000367 if self.executable is None:
368 if not self.standalone:
369 self.symlink_exec = 1
370 self.executable = sys.executable
371
Just van Rossumceeb9622002-11-21 23:19:37 +0000372 if self.nibname:
373 self.plist.NSMainNibFile = self.nibname
374 if not hasattr(self.plist, "NSPrincipalClass"):
375 self.plist.NSPrincipalClass = "NSApplication"
376
377 BundleBuilder.setup(self)
378
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000379 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000380
Just van Rossumcef32882002-11-26 00:34:52 +0000381 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000382 self.findDependencies()
383
Just van Rossumf7aba232002-11-22 00:31:50 +0000384 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000385 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000386 if self.executable is not None:
387 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000388 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000389 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000390 execname = os.path.basename(self.executable)
391 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000392 if not self.symlink_exec:
393 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000394 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000395 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000396
397 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000398 mainprogram = os.path.basename(self.mainprogram)
399 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
Jack Jansena03adde2003-02-18 23:29:46 +0000400 if self.argv_emulation:
401 # Change the main program, and create the helper main program (which
402 # does argv collection and then calls the real main).
403 # Also update the included modules (if we're creating a standalone
404 # program) and the plist
405 realmainprogram = mainprogram
406 mainprogram = '__argvemulator_' + mainprogram
407 resdirpath = pathjoin(self.bundlepath, resdir)
408 mainprogrampath = pathjoin(resdirpath, mainprogram)
409 makedirs(resdirpath)
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000410 open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
Jack Jansena03adde2003-02-18 23:29:46 +0000411 if self.standalone:
412 self.includeModules.append("argvemulator")
413 self.includeModules.append("os")
414 if not self.plist.has_key("CFBundleDocumentTypes"):
415 self.plist["CFBundleDocumentTypes"] = [
416 { "CFBundleTypeOSTypes" : [
417 "****",
418 "fold",
419 "disk"],
420 "CFBundleTypeRole": "Viewer"}]
Just van Rossum24884f72002-11-29 21:22:33 +0000421 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000422 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000423 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000424 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000425 makedirs(execdir)
Just van Rossum0ff7a4e2003-02-26 11:27:56 +0000426 if self.standalone:
427 # XXX we're screwed when the end user has deleted
428 # /usr/bin/python
429 hashbang = "/usr/bin/python"
430 else:
431 hashbang = sys.executable
432 while os.path.islink(hashbang):
433 hashbang = os.readlink(hashbang)
Just van Rossum24884f72002-11-29 21:22:33 +0000434 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
435 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000436
Just van Rossum2aa09562003-02-01 08:34:46 +0000437 if self.iconfile is not None:
438 iconbase = os.path.basename(self.iconfile)
439 self.plist.CFBundleIconFile = iconbase
440 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
441
Just van Rossum16aebf72002-11-22 11:43:10 +0000442 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000443 if self.standalone:
444 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000445 if self.strip and not self.symlink:
446 self.stripBinaries()
447
Just van Rossum16aebf72002-11-22 11:43:10 +0000448 if self.symlink_exec and self.executable:
449 self.message("Symlinking executable %s to %s" % (self.executable,
450 self.execpath), 2)
451 dst = pathjoin(self.bundlepath, self.execpath)
452 makedirs(os.path.dirname(dst))
453 os.symlink(os.path.abspath(self.executable), dst)
454
Just van Rossum74bdca82002-11-28 11:30:56 +0000455 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000456 self.reportMissing()
457
458 def addPythonModules(self):
459 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000460
Just van Rossum109ecbf2003-01-02 13:13:01 +0000461 if USE_ZIPIMPORT:
462 # Create a zip file containing all modules as pyc.
463 import zipfile
464 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000465 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000466 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
467 for name, code, ispkg in self.pymodules:
468 self.message("Adding Python module %s" % name, 2)
469 path, pyc = getPycData(name, code, ispkg)
470 zf.writestr(path, pyc)
471 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000472 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000473 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
474 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000475 writePyc(SITE_CO, sitepath)
476 else:
477 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000478 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000479 if ispkg:
480 name += ".__init__"
481 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000482 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000483
484 if ispkg:
485 self.message("Adding Python package %s" % path, 2)
486 else:
487 self.message("Adding Python module %s" % path, 2)
488
489 abspath = pathjoin(self.bundlepath, path)
490 makedirs(os.path.dirname(abspath))
491 writePyc(code, abspath)
492
493 def stripBinaries(self):
494 if not os.path.exists(STRIP_EXEC):
495 self.message("Error: can't strip binaries: no strip program at "
496 "%s" % STRIP_EXEC, 0)
497 else:
498 self.message("Stripping binaries", 1)
499 for relpath in self.binaries:
500 self.message("Stripping %s" % relpath, 2)
501 abspath = pathjoin(self.bundlepath, relpath)
502 assert not os.path.islink(abspath)
503 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
504
505 def findDependencies(self):
506 self.message("Finding module dependencies", 1)
507 import modulefinder
508 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000509 if USE_ZIPIMPORT:
510 # zipimport imports zlib, must add it manually
511 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000512 # manually add our own site.py
513 site = mf.add_module("site")
514 site.__code__ = SITE_CO
515 mf.scan_code(SITE_CO, site)
516
Just van Rossum7322b1a2003-02-25 20:15:40 +0000517 # warnings.py gets imported implicitly from C
518 mf.import_hook("warnings")
519
Just van Rossumcef32882002-11-26 00:34:52 +0000520 includeModules = self.includeModules[:]
521 for name in self.includePackages:
522 includeModules.extend(findPackageContents(name).keys())
523 for name in includeModules:
524 try:
525 mf.import_hook(name)
526 except ImportError:
527 self.missingModules.append(name)
528
Just van Rossumcef32882002-11-26 00:34:52 +0000529 mf.run_script(self.mainprogram)
530 modules = mf.modules.items()
531 modules.sort()
532 for name, mod in modules:
533 if mod.__file__ and mod.__code__ is None:
534 # C extension
535 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000536 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000537 if USE_ZIPIMPORT:
538 # Python modules are stored in a Zip archive, but put
539 # extensions in Contents/Resources/.a and add a tiny "loader"
540 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000541 dstpath = pathjoin("Contents", "Resources", filename)
542 source = EXT_LOADER % {"name": name, "filename": filename}
543 code = compile(source, "<dynloader for %s>" % name, "exec")
544 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000545 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000546 # just copy the file
547 dstpath = name.split(".")[:-1] + [filename]
548 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000549 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000550 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000551 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000552 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000553 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000554 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000555 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000556 self.pymodules.append((name, mod.__code__, ispkg))
557
Just van Rossum74bdca82002-11-28 11:30:56 +0000558 if hasattr(mf, "any_missing_maybe"):
559 missing, maybe = mf.any_missing_maybe()
560 else:
561 missing = mf.any_missing()
562 maybe = []
563 self.missingModules.extend(missing)
564 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000565
566 def reportMissing(self):
567 missing = [name for name in self.missingModules
568 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000569 if self.maybeMissingModules:
570 maybe = self.maybeMissingModules
571 else:
572 maybe = [name for name in missing if "." in name]
573 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000574 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000575 maybe.sort()
576 if maybe:
577 self.message("Warning: couldn't find the following submodules:", 1)
578 self.message(" (Note that these could be false alarms -- "
579 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000580 self.message(" possible to distinguish between \"from package "
581 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000582 self.message(" and \"from package import name\")", 1)
583 for name in maybe:
584 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000585 if missing:
586 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000587 for name in missing:
588 self.message(" ? " + name, 1)
589
590 def report(self):
591 # XXX something decent
592 import pprint
593 pprint.pprint(self.__dict__)
594 if self.standalone:
595 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000596
597#
598# Utilities.
599#
600
601SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
602identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
603
604def findPackageContents(name, searchpath=None):
605 head = name.split(".")[-1]
606 if identifierRE.match(head) is None:
607 return {}
608 try:
609 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
610 except ImportError:
611 return {}
612 modules = {name: None}
613 if tp == imp.PKG_DIRECTORY and path:
614 files = os.listdir(path)
615 for sub in files:
616 sub, ext = os.path.splitext(sub)
617 fullname = name + "." + sub
618 if sub != "__init__" and fullname not in modules:
619 modules.update(findPackageContents(fullname, [path]))
620 return modules
621
622def writePyc(code, path):
623 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000624 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000625 f.write("\0" * 4) # don't bother about a time stamp
626 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000627 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000628
Just van Rossumad33d722002-11-21 10:23:04 +0000629def copy(src, dst, mkdirs=0):
630 """Copy a file or a directory."""
631 if mkdirs:
632 makedirs(os.path.dirname(dst))
633 if os.path.isdir(src):
634 shutil.copytree(src, dst)
635 else:
636 shutil.copy2(src, dst)
637
638def copytodir(src, dstdir):
639 """Copy a file or a directory to an existing directory."""
640 dst = pathjoin(dstdir, os.path.basename(src))
641 copy(src, dst)
642
643def makedirs(dir):
644 """Make all directories leading up to 'dir' including the leaf
645 directory. Don't moan if any path element already exists."""
646 try:
647 os.makedirs(dir)
648 except OSError, why:
649 if why.errno != errno.EEXIST:
650 raise
651
652def symlink(src, dst, mkdirs=0):
653 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000654 if not os.path.exists(src):
655 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000656 if mkdirs:
657 makedirs(os.path.dirname(dst))
658 os.symlink(os.path.abspath(src), dst)
659
660def pathjoin(*args):
661 """Safe wrapper for os.path.join: asserts that all but the first
662 argument are relative paths."""
663 for seg in args[1:]:
664 assert seg[0] != "/"
665 return os.path.join(*args)
666
667
Just van Rossumceeb9622002-11-21 23:19:37 +0000668cmdline_doc = """\
669Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000670 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000671 python mybuildscript.py [options] command
672
673Commands:
674 build build the application
675 report print a report
676
677Options:
678 -b, --builddir=DIR the build directory; defaults to "build"
679 -n, --name=NAME application name
680 -r, --resource=FILE extra file or folder to be copied to Resources
Just van Rossum7215e082003-02-25 21:00:55 +0000681 -f, --file=SRC:DST extra file or folder to be copied into the bundle;
682 DST must be a path relative to the bundle root
Just van Rossumceeb9622002-11-21 23:19:37 +0000683 -e, --executable=FILE the executable to be used
684 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000685 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000686 -p, --plist=FILE .plist file (default: generate one)
687 --nib=NAME main nib name
688 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000689 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000690 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000691 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000692 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000693 --standalone build a standalone application, which is fully
694 independent of a Python installation
695 -x, --exclude=MODULE exclude module (with --standalone)
696 -i, --include=MODULE include module (with --standalone)
697 --package=PACKAGE include a whole package (with --standalone)
698 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000699 -v, --verbose increase verbosity level
700 -q, --quiet decrease verbosity level
701 -h, --help print this message
702"""
703
704def usage(msg=None):
705 if msg:
706 print msg
707 print cmdline_doc
708 sys.exit(1)
709
710def main(builder=None):
711 if builder is None:
712 builder = AppBuilder(verbosity=1)
713
Jack Jansen00cbf072003-02-24 16:27:08 +0000714 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
Just van Rossum7215e082003-02-25 21:00:55 +0000715 longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000716 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000717 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000718 "exclude=", "include=", "package=", "strip", "iconfile=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000719
720 try:
721 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
722 except getopt.error:
723 usage()
724
725 for opt, arg in options:
726 if opt in ('-b', '--builddir'):
727 builder.builddir = arg
728 elif opt in ('-n', '--name'):
729 builder.name = arg
730 elif opt in ('-r', '--resource'):
731 builder.resources.append(arg)
Just van Rossum7215e082003-02-25 21:00:55 +0000732 elif opt in ('-f', '--file'):
Jack Jansen00cbf072003-02-24 16:27:08 +0000733 srcdst = arg.split(':')
734 if len(srcdst) != 2:
Just van Rossum49833312003-02-25 21:08:12 +0000735 usage("-f or --file argument must be two paths, "
736 "separated by a colon")
Jack Jansen00cbf072003-02-24 16:27:08 +0000737 builder.files.append(srcdst)
Just van Rossumceeb9622002-11-21 23:19:37 +0000738 elif opt in ('-e', '--executable'):
739 builder.executable = arg
740 elif opt in ('-m', '--mainprogram'):
741 builder.mainprogram = arg
Jack Jansena03adde2003-02-18 23:29:46 +0000742 elif opt in ('-a', '--argv'):
743 builder.argv_emulation = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000744 elif opt in ('-c', '--creator'):
745 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000746 elif opt == '--iconfile':
747 builder.iconfile = arg
Just van Rossumceeb9622002-11-21 23:19:37 +0000748 elif opt == "--nib":
749 builder.nibname = arg
750 elif opt in ('-p', '--plist'):
751 builder.plist = Plist.fromFile(arg)
752 elif opt in ('-l', '--link'):
753 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000754 elif opt == '--link-exec':
755 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000756 elif opt in ('-h', '--help'):
757 usage()
758 elif opt in ('-v', '--verbose'):
759 builder.verbosity += 1
760 elif opt in ('-q', '--quiet'):
761 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000762 elif opt == '--standalone':
763 builder.standalone = 1
764 elif opt in ('-x', '--exclude'):
765 builder.excludeModules.append(arg)
766 elif opt in ('-i', '--include'):
767 builder.includeModules.append(arg)
768 elif opt == '--package':
769 builder.includePackages.append(arg)
770 elif opt == '--strip':
771 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000772
773 if len(args) != 1:
774 usage("Must specify one command ('build', 'report' or 'help')")
775 command = args[0]
776
777 if command == "build":
778 builder.setup()
779 builder.build()
780 elif command == "report":
781 builder.setup()
782 builder.report()
783 elif command == "help":
784 usage()
785 else:
786 usage("Unknown command '%s'" % command)
787
788
Just van Rossumad33d722002-11-21 10:23:04 +0000789def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000790 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000791 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000792
793
794if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000795 main()