blob: 8987ef0ecb3113bca04c516d7123fa0bacdcb859 [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 Rossum7322b1a2003-02-25 20:15:40 +0000269#!/usr/bin/env python
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 Rossum24884f72002-11-29 21:22:33 +0000426 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
427 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000428
Just van Rossum2aa09562003-02-01 08:34:46 +0000429 if self.iconfile is not None:
430 iconbase = os.path.basename(self.iconfile)
431 self.plist.CFBundleIconFile = iconbase
432 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
433
Just van Rossum16aebf72002-11-22 11:43:10 +0000434 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000435 if self.standalone:
436 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000437 if self.strip and not self.symlink:
438 self.stripBinaries()
439
Just van Rossum16aebf72002-11-22 11:43:10 +0000440 if self.symlink_exec and self.executable:
441 self.message("Symlinking executable %s to %s" % (self.executable,
442 self.execpath), 2)
443 dst = pathjoin(self.bundlepath, self.execpath)
444 makedirs(os.path.dirname(dst))
445 os.symlink(os.path.abspath(self.executable), dst)
446
Just van Rossum74bdca82002-11-28 11:30:56 +0000447 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000448 self.reportMissing()
449
450 def addPythonModules(self):
451 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000452
Just van Rossum109ecbf2003-01-02 13:13:01 +0000453 if USE_ZIPIMPORT:
454 # Create a zip file containing all modules as pyc.
455 import zipfile
456 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000457 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000458 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
459 for name, code, ispkg in self.pymodules:
460 self.message("Adding Python module %s" % name, 2)
461 path, pyc = getPycData(name, code, ispkg)
462 zf.writestr(path, pyc)
463 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000464 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000465 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
466 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000467 writePyc(SITE_CO, sitepath)
468 else:
469 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000470 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000471 if ispkg:
472 name += ".__init__"
473 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000474 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000475
476 if ispkg:
477 self.message("Adding Python package %s" % path, 2)
478 else:
479 self.message("Adding Python module %s" % path, 2)
480
481 abspath = pathjoin(self.bundlepath, path)
482 makedirs(os.path.dirname(abspath))
483 writePyc(code, abspath)
484
485 def stripBinaries(self):
486 if not os.path.exists(STRIP_EXEC):
487 self.message("Error: can't strip binaries: no strip program at "
488 "%s" % STRIP_EXEC, 0)
489 else:
490 self.message("Stripping binaries", 1)
491 for relpath in self.binaries:
492 self.message("Stripping %s" % relpath, 2)
493 abspath = pathjoin(self.bundlepath, relpath)
494 assert not os.path.islink(abspath)
495 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
496
497 def findDependencies(self):
498 self.message("Finding module dependencies", 1)
499 import modulefinder
500 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000501 if USE_ZIPIMPORT:
502 # zipimport imports zlib, must add it manually
503 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000504 # manually add our own site.py
505 site = mf.add_module("site")
506 site.__code__ = SITE_CO
507 mf.scan_code(SITE_CO, site)
508
Just van Rossum7322b1a2003-02-25 20:15:40 +0000509 # warnings.py gets imported implicitly from C
510 mf.import_hook("warnings")
511
Just van Rossumcef32882002-11-26 00:34:52 +0000512 includeModules = self.includeModules[:]
513 for name in self.includePackages:
514 includeModules.extend(findPackageContents(name).keys())
515 for name in includeModules:
516 try:
517 mf.import_hook(name)
518 except ImportError:
519 self.missingModules.append(name)
520
Just van Rossumcef32882002-11-26 00:34:52 +0000521 mf.run_script(self.mainprogram)
522 modules = mf.modules.items()
523 modules.sort()
524 for name, mod in modules:
525 if mod.__file__ and mod.__code__ is None:
526 # C extension
527 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000528 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000529 if USE_ZIPIMPORT:
530 # Python modules are stored in a Zip archive, but put
531 # extensions in Contents/Resources/.a and add a tiny "loader"
532 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000533 dstpath = pathjoin("Contents", "Resources", filename)
534 source = EXT_LOADER % {"name": name, "filename": filename}
535 code = compile(source, "<dynloader for %s>" % name, "exec")
536 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000537 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000538 # just copy the file
539 dstpath = name.split(".")[:-1] + [filename]
540 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000541 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000542 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000543 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000544 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000545 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000546 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000547 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000548 self.pymodules.append((name, mod.__code__, ispkg))
549
Just van Rossum74bdca82002-11-28 11:30:56 +0000550 if hasattr(mf, "any_missing_maybe"):
551 missing, maybe = mf.any_missing_maybe()
552 else:
553 missing = mf.any_missing()
554 maybe = []
555 self.missingModules.extend(missing)
556 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000557
558 def reportMissing(self):
559 missing = [name for name in self.missingModules
560 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000561 if self.maybeMissingModules:
562 maybe = self.maybeMissingModules
563 else:
564 maybe = [name for name in missing if "." in name]
565 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000566 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000567 maybe.sort()
568 if maybe:
569 self.message("Warning: couldn't find the following submodules:", 1)
570 self.message(" (Note that these could be false alarms -- "
571 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000572 self.message(" possible to distinguish between \"from package "
573 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000574 self.message(" and \"from package import name\")", 1)
575 for name in maybe:
576 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000577 if missing:
578 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000579 for name in missing:
580 self.message(" ? " + name, 1)
581
582 def report(self):
583 # XXX something decent
584 import pprint
585 pprint.pprint(self.__dict__)
586 if self.standalone:
587 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000588
589#
590# Utilities.
591#
592
593SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
594identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
595
596def findPackageContents(name, searchpath=None):
597 head = name.split(".")[-1]
598 if identifierRE.match(head) is None:
599 return {}
600 try:
601 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
602 except ImportError:
603 return {}
604 modules = {name: None}
605 if tp == imp.PKG_DIRECTORY and path:
606 files = os.listdir(path)
607 for sub in files:
608 sub, ext = os.path.splitext(sub)
609 fullname = name + "." + sub
610 if sub != "__init__" and fullname not in modules:
611 modules.update(findPackageContents(fullname, [path]))
612 return modules
613
614def writePyc(code, path):
615 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000616 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000617 f.write("\0" * 4) # don't bother about a time stamp
618 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000619 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000620
Just van Rossumad33d722002-11-21 10:23:04 +0000621def copy(src, dst, mkdirs=0):
622 """Copy a file or a directory."""
623 if mkdirs:
624 makedirs(os.path.dirname(dst))
625 if os.path.isdir(src):
626 shutil.copytree(src, dst)
627 else:
628 shutil.copy2(src, dst)
629
630def copytodir(src, dstdir):
631 """Copy a file or a directory to an existing directory."""
632 dst = pathjoin(dstdir, os.path.basename(src))
633 copy(src, dst)
634
635def makedirs(dir):
636 """Make all directories leading up to 'dir' including the leaf
637 directory. Don't moan if any path element already exists."""
638 try:
639 os.makedirs(dir)
640 except OSError, why:
641 if why.errno != errno.EEXIST:
642 raise
643
644def symlink(src, dst, mkdirs=0):
645 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000646 if not os.path.exists(src):
647 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000648 if mkdirs:
649 makedirs(os.path.dirname(dst))
650 os.symlink(os.path.abspath(src), dst)
651
652def pathjoin(*args):
653 """Safe wrapper for os.path.join: asserts that all but the first
654 argument are relative paths."""
655 for seg in args[1:]:
656 assert seg[0] != "/"
657 return os.path.join(*args)
658
659
Just van Rossumceeb9622002-11-21 23:19:37 +0000660cmdline_doc = """\
661Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000662 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000663 python mybuildscript.py [options] command
664
665Commands:
666 build build the application
667 report print a report
668
669Options:
670 -b, --builddir=DIR the build directory; defaults to "build"
671 -n, --name=NAME application name
672 -r, --resource=FILE extra file or folder to be copied to Resources
Just van Rossum7215e082003-02-25 21:00:55 +0000673 -f, --file=SRC:DST extra file or folder to be copied into the bundle;
674 DST must be a path relative to the bundle root
Just van Rossumceeb9622002-11-21 23:19:37 +0000675 -e, --executable=FILE the executable to be used
676 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000677 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000678 -p, --plist=FILE .plist file (default: generate one)
679 --nib=NAME main nib name
680 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000681 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000682 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000683 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000684 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000685 --standalone build a standalone application, which is fully
686 independent of a Python installation
687 -x, --exclude=MODULE exclude module (with --standalone)
688 -i, --include=MODULE include module (with --standalone)
689 --package=PACKAGE include a whole package (with --standalone)
690 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000691 -v, --verbose increase verbosity level
692 -q, --quiet decrease verbosity level
693 -h, --help print this message
694"""
695
696def usage(msg=None):
697 if msg:
698 print msg
699 print cmdline_doc
700 sys.exit(1)
701
702def main(builder=None):
703 if builder is None:
704 builder = AppBuilder(verbosity=1)
705
Jack Jansen00cbf072003-02-24 16:27:08 +0000706 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
Just van Rossum7215e082003-02-25 21:00:55 +0000707 longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000708 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000709 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000710 "exclude=", "include=", "package=", "strip", "iconfile=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000711
712 try:
713 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
714 except getopt.error:
715 usage()
716
717 for opt, arg in options:
718 if opt in ('-b', '--builddir'):
719 builder.builddir = arg
720 elif opt in ('-n', '--name'):
721 builder.name = arg
722 elif opt in ('-r', '--resource'):
723 builder.resources.append(arg)
Just van Rossum7215e082003-02-25 21:00:55 +0000724 elif opt in ('-f', '--file'):
Jack Jansen00cbf072003-02-24 16:27:08 +0000725 srcdst = arg.split(':')
726 if len(srcdst) != 2:
Just van Rossum49833312003-02-25 21:08:12 +0000727 usage("-f or --file argument must be two paths, "
728 "separated by a colon")
Jack Jansen00cbf072003-02-24 16:27:08 +0000729 builder.files.append(srcdst)
Just van Rossumceeb9622002-11-21 23:19:37 +0000730 elif opt in ('-e', '--executable'):
731 builder.executable = arg
732 elif opt in ('-m', '--mainprogram'):
733 builder.mainprogram = arg
Jack Jansena03adde2003-02-18 23:29:46 +0000734 elif opt in ('-a', '--argv'):
735 builder.argv_emulation = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000736 elif opt in ('-c', '--creator'):
737 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000738 elif opt == '--iconfile':
739 builder.iconfile = arg
Just van Rossumceeb9622002-11-21 23:19:37 +0000740 elif opt == "--nib":
741 builder.nibname = arg
742 elif opt in ('-p', '--plist'):
743 builder.plist = Plist.fromFile(arg)
744 elif opt in ('-l', '--link'):
745 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000746 elif opt == '--link-exec':
747 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000748 elif opt in ('-h', '--help'):
749 usage()
750 elif opt in ('-v', '--verbose'):
751 builder.verbosity += 1
752 elif opt in ('-q', '--quiet'):
753 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000754 elif opt == '--standalone':
755 builder.standalone = 1
756 elif opt in ('-x', '--exclude'):
757 builder.excludeModules.append(arg)
758 elif opt in ('-i', '--include'):
759 builder.includeModules.append(arg)
760 elif opt == '--package':
761 builder.includePackages.append(arg)
762 elif opt == '--strip':
763 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000764
765 if len(args) != 1:
766 usage("Must specify one command ('build', 'report' or 'help')")
767 command = args[0]
768
769 if command == "build":
770 builder.setup()
771 builder.build()
772 elif command == "report":
773 builder.setup()
774 builder.report()
775 elif command == "help":
776 usage()
777 else:
778 usage("Unknown command '%s'" % command)
779
780
Just van Rossumad33d722002-11-21 10:23:04 +0000781def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000782 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000783 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000784
785
786if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000787 main()