blob: a263e62e232a7a14e611b151df1b36f27d93e533 [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 Rossum8a3ed3f2003-02-25 20:53:12 +0000229#
230# The following snippet gets added as sitecustomize.py[co] to
231# non-standalone apps and appended to our custom site.py for
232# standalone apps. The bootstrap scripts calls os.execve() with
233# an argv[0] that's different from the actual executable: argv[0]
234# is the bootstrap script itself and matches the CFBundleExecutable
235# value in the Info.plist. This is needed to keep the Finder happy
236# and have the app work from the command line as well. However,
237# this causes sys.executable to also be that value, so we correct
238# that from the PYTHONEXECUTABLE environment variable that the
239# bootstrap script sets.
240#
Just van Rossum7322b1a2003-02-25 20:15:40 +0000241SITECUSTOMIZE_PY = """\
242import sys, os
243executable = os.getenv("PYTHONEXECUTABLE")
244if executable is not None:
245 sys.executable = executable
246"""
247
248SITE_PY += SITECUSTOMIZE_PY
Just van Rossum74bdca82002-11-28 11:30:56 +0000249SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossum7322b1a2003-02-25 20:15:40 +0000250SITECUSTOMIZE_CO = compile(SITECUSTOMIZE_PY, "<-bundlebuilder.py->", "exec")
251
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000252#
253# Extension modules can't be in the modules zip archive, so a placeholder
254# is added instead, that loads the extension from a specified location.
255#
Just van Rossum535ffa22002-11-29 20:06:52 +0000256EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000257def __load():
258 import imp, sys, os
259 for p in sys.path:
260 path = os.path.join(p, "%(filename)s")
261 if os.path.exists(path):
262 break
263 else:
264 assert 0, "file not found: %(filename)s"
265 mod = imp.load_dynamic("%(name)s", path)
266
267__load()
268del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000269"""
270
Just van Rossumcef32882002-11-26 00:34:52 +0000271MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
272 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
273 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
274]
275
276STRIP_EXEC = "/usr/bin/strip"
277
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000278#
279# We're using a stock interpreter to run the app, yet we need
280# a way to pass the Python main program to the interpreter. The
281# bootstrapping script fires up the interpreter with the right
282# arguments. os.execve() is used as OSX doesn't like us to
283# start a real new process. Also, the executable name must match
284# the CFBundleExecutable value in the Info.plist, so we lie
285# deliberately with argv[0]. The actual Python executable is
286# passed in an environment variable so we can "repair"
287# sys.executable later.
288#
Just van Rossum74bdca82002-11-28 11:30:56 +0000289BOOTSTRAP_SCRIPT = """\
Just van Rossum7322b1a2003-02-25 20:15:40 +0000290#!/usr/bin/env python
Just van Rossumad33d722002-11-21 10:23:04 +0000291
Just van Rossum7322b1a2003-02-25 20:15:40 +0000292import sys, os
293execdir = os.path.dirname(sys.argv[0])
294executable = os.path.join(execdir, "%(executable)s")
295resdir = os.path.join(os.path.dirname(execdir), "Resources")
296mainprogram = os.path.join(resdir, "%(mainprogram)s")
297
298sys.argv.insert(1, mainprogram)
299os.environ["PYTHONPATH"] = resdir
300os.environ["PYTHONEXECUTABLE"] = executable
301os.execve(executable, sys.argv, os.environ)
Just van Rossumad33d722002-11-21 10:23:04 +0000302"""
303
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000304
305#
306# Optional wrapper that converts "dropped files" into sys.argv values.
307#
308ARGV_EMULATOR = """\
Jack Jansena03adde2003-02-18 23:29:46 +0000309import argvemulator, os
310
311argvemulator.ArgvCollector().mainloop()
312execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
313"""
Just van Rossumcef32882002-11-26 00:34:52 +0000314
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000315
Just van Rossumad33d722002-11-21 10:23:04 +0000316class AppBuilder(BundleBuilder):
317
Just van Rossumda302da2002-11-23 22:26:44 +0000318 # A Python main program. If this argument is given, the main
319 # executable in the bundle will be a small wrapper that invokes
320 # the main program. (XXX Discuss why.)
321 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000322
Just van Rossumda302da2002-11-23 22:26:44 +0000323 # The main executable. If a Python main program is specified
324 # the executable will be copied to Resources and be invoked
325 # by the wrapper program mentioned above. Otherwise it will
326 # simply be used as the main executable.
327 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000328
Just van Rossumda302da2002-11-23 22:26:44 +0000329 # The name of the main nib, for Cocoa apps. *Must* be specified
330 # when building a Cocoa app.
331 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000332
Just van Rossum2aa09562003-02-01 08:34:46 +0000333 # The name of the icon file to be copied to Resources and used for
334 # the Finder icon.
335 iconfile = None
336
Just van Rossumda302da2002-11-23 22:26:44 +0000337 # Symlink the executable instead of copying it.
338 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000339
Just van Rossumcef32882002-11-26 00:34:52 +0000340 # If True, build standalone app.
341 standalone = 0
Jack Jansena03adde2003-02-18 23:29:46 +0000342
343 # If True, add a real main program that emulates sys.argv before calling
344 # mainprogram
345 argv_emulation = 0
Just van Rossumcef32882002-11-26 00:34:52 +0000346
347 # The following attributes are only used when building a standalone app.
348
349 # Exclude these modules.
350 excludeModules = []
351
352 # Include these modules.
353 includeModules = []
354
355 # Include these packages.
356 includePackages = []
357
358 # Strip binaries.
359 strip = 0
360
Just van Rossumcef32882002-11-26 00:34:52 +0000361 # Found Python modules: [(name, codeobject, ispkg), ...]
362 pymodules = []
363
364 # Modules that modulefinder couldn't find:
365 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000366 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000367
368 # List of all binaries (executables or shared libs), for stripping purposes
369 binaries = []
370
Just van Rossumceeb9622002-11-21 23:19:37 +0000371 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000372 if self.standalone and self.mainprogram is None:
373 raise BundleBuilderError, ("must specify 'mainprogram' when "
374 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000375 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000376 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000377 "'executable' and 'mainprogram'")
378
379 if self.name is not None:
380 pass
381 elif self.mainprogram is not None:
382 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
383 elif executable is not None:
384 self.name = os.path.splitext(os.path.basename(self.executable))[0]
385 if self.name[-4:] != ".app":
386 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000387
Just van Rossum74bdca82002-11-28 11:30:56 +0000388 if self.executable is None:
389 if not self.standalone:
390 self.symlink_exec = 1
391 self.executable = sys.executable
392
Just van Rossumceeb9622002-11-21 23:19:37 +0000393 if self.nibname:
394 self.plist.NSMainNibFile = self.nibname
395 if not hasattr(self.plist, "NSPrincipalClass"):
396 self.plist.NSPrincipalClass = "NSApplication"
397
398 BundleBuilder.setup(self)
399
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000400 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000401
Just van Rossumcef32882002-11-26 00:34:52 +0000402 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000403 self.findDependencies()
404
Just van Rossumf7aba232002-11-22 00:31:50 +0000405 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000406 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000407 if self.executable is not None:
408 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000409 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000410 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000411 execname = os.path.basename(self.executable)
412 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000413 if not self.symlink_exec:
414 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000415 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000416 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000417
418 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000419 mainprogram = os.path.basename(self.mainprogram)
420 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
Jack Jansena03adde2003-02-18 23:29:46 +0000421 if self.argv_emulation:
422 # Change the main program, and create the helper main program (which
423 # does argv collection and then calls the real main).
424 # Also update the included modules (if we're creating a standalone
425 # program) and the plist
426 realmainprogram = mainprogram
427 mainprogram = '__argvemulator_' + mainprogram
428 resdirpath = pathjoin(self.bundlepath, resdir)
429 mainprogrampath = pathjoin(resdirpath, mainprogram)
430 makedirs(resdirpath)
Just van Rossum8a3ed3f2003-02-25 20:53:12 +0000431 open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
Jack Jansena03adde2003-02-18 23:29:46 +0000432 if self.standalone:
433 self.includeModules.append("argvemulator")
434 self.includeModules.append("os")
435 if not self.plist.has_key("CFBundleDocumentTypes"):
436 self.plist["CFBundleDocumentTypes"] = [
437 { "CFBundleTypeOSTypes" : [
438 "****",
439 "fold",
440 "disk"],
441 "CFBundleTypeRole": "Viewer"}]
Just van Rossum24884f72002-11-29 21:22:33 +0000442 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000443 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000444 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000445 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000446 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000447 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
448 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000449
Just van Rossum2aa09562003-02-01 08:34:46 +0000450 if self.iconfile is not None:
451 iconbase = os.path.basename(self.iconfile)
452 self.plist.CFBundleIconFile = iconbase
453 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
454
Just van Rossum16aebf72002-11-22 11:43:10 +0000455 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000456 if self.standalone:
457 self.addPythonModules()
Just van Rossum7322b1a2003-02-25 20:15:40 +0000458 else:
459 sitecustomizepath = pathjoin(self.bundlepath, "Contents", "Resources",
460 "sitecustomize" + PYC_EXT)
461 writePyc(SITECUSTOMIZE_CO, sitecustomizepath)
Just van Rossumcef32882002-11-26 00:34:52 +0000462 if self.strip and not self.symlink:
463 self.stripBinaries()
464
Just van Rossum16aebf72002-11-22 11:43:10 +0000465 if self.symlink_exec and self.executable:
466 self.message("Symlinking executable %s to %s" % (self.executable,
467 self.execpath), 2)
468 dst = pathjoin(self.bundlepath, self.execpath)
469 makedirs(os.path.dirname(dst))
470 os.symlink(os.path.abspath(self.executable), dst)
471
Just van Rossum74bdca82002-11-28 11:30:56 +0000472 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000473 self.reportMissing()
474
475 def addPythonModules(self):
476 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000477
Just van Rossum109ecbf2003-01-02 13:13:01 +0000478 if USE_ZIPIMPORT:
479 # Create a zip file containing all modules as pyc.
480 import zipfile
481 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000482 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000483 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
484 for name, code, ispkg in self.pymodules:
485 self.message("Adding Python module %s" % name, 2)
486 path, pyc = getPycData(name, code, ispkg)
487 zf.writestr(path, pyc)
488 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000489 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000490 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
491 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000492 writePyc(SITE_CO, sitepath)
493 else:
494 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000495 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000496 if ispkg:
497 name += ".__init__"
498 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000499 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000500
501 if ispkg:
502 self.message("Adding Python package %s" % path, 2)
503 else:
504 self.message("Adding Python module %s" % path, 2)
505
506 abspath = pathjoin(self.bundlepath, path)
507 makedirs(os.path.dirname(abspath))
508 writePyc(code, abspath)
509
510 def stripBinaries(self):
511 if not os.path.exists(STRIP_EXEC):
512 self.message("Error: can't strip binaries: no strip program at "
513 "%s" % STRIP_EXEC, 0)
514 else:
515 self.message("Stripping binaries", 1)
516 for relpath in self.binaries:
517 self.message("Stripping %s" % relpath, 2)
518 abspath = pathjoin(self.bundlepath, relpath)
519 assert not os.path.islink(abspath)
520 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
521
522 def findDependencies(self):
523 self.message("Finding module dependencies", 1)
524 import modulefinder
525 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000526 if USE_ZIPIMPORT:
527 # zipimport imports zlib, must add it manually
528 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000529 # manually add our own site.py
530 site = mf.add_module("site")
531 site.__code__ = SITE_CO
532 mf.scan_code(SITE_CO, site)
533
Just van Rossum7322b1a2003-02-25 20:15:40 +0000534 # warnings.py gets imported implicitly from C
535 mf.import_hook("warnings")
536
Just van Rossumcef32882002-11-26 00:34:52 +0000537 includeModules = self.includeModules[:]
538 for name in self.includePackages:
539 includeModules.extend(findPackageContents(name).keys())
540 for name in includeModules:
541 try:
542 mf.import_hook(name)
543 except ImportError:
544 self.missingModules.append(name)
545
Just van Rossumcef32882002-11-26 00:34:52 +0000546 mf.run_script(self.mainprogram)
547 modules = mf.modules.items()
548 modules.sort()
549 for name, mod in modules:
550 if mod.__file__ and mod.__code__ is None:
551 # C extension
552 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000553 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000554 if USE_ZIPIMPORT:
555 # Python modules are stored in a Zip archive, but put
556 # extensions in Contents/Resources/.a and add a tiny "loader"
557 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000558 dstpath = pathjoin("Contents", "Resources", filename)
559 source = EXT_LOADER % {"name": name, "filename": filename}
560 code = compile(source, "<dynloader for %s>" % name, "exec")
561 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000562 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000563 # just copy the file
564 dstpath = name.split(".")[:-1] + [filename]
565 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000566 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000567 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000568 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000569 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000570 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000571 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000572 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000573 self.pymodules.append((name, mod.__code__, ispkg))
574
Just van Rossum74bdca82002-11-28 11:30:56 +0000575 if hasattr(mf, "any_missing_maybe"):
576 missing, maybe = mf.any_missing_maybe()
577 else:
578 missing = mf.any_missing()
579 maybe = []
580 self.missingModules.extend(missing)
581 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000582
583 def reportMissing(self):
584 missing = [name for name in self.missingModules
585 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000586 if self.maybeMissingModules:
587 maybe = self.maybeMissingModules
588 else:
589 maybe = [name for name in missing if "." in name]
590 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000591 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000592 maybe.sort()
593 if maybe:
594 self.message("Warning: couldn't find the following submodules:", 1)
595 self.message(" (Note that these could be false alarms -- "
596 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000597 self.message(" possible to distinguish between \"from package "
598 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000599 self.message(" and \"from package import name\")", 1)
600 for name in maybe:
601 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000602 if missing:
603 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000604 for name in missing:
605 self.message(" ? " + name, 1)
606
607 def report(self):
608 # XXX something decent
609 import pprint
610 pprint.pprint(self.__dict__)
611 if self.standalone:
612 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000613
614#
615# Utilities.
616#
617
618SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
619identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
620
621def findPackageContents(name, searchpath=None):
622 head = name.split(".")[-1]
623 if identifierRE.match(head) is None:
624 return {}
625 try:
626 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
627 except ImportError:
628 return {}
629 modules = {name: None}
630 if tp == imp.PKG_DIRECTORY and path:
631 files = os.listdir(path)
632 for sub in files:
633 sub, ext = os.path.splitext(sub)
634 fullname = name + "." + sub
635 if sub != "__init__" and fullname not in modules:
636 modules.update(findPackageContents(fullname, [path]))
637 return modules
638
639def writePyc(code, path):
640 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000641 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000642 f.write("\0" * 4) # don't bother about a time stamp
643 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000644 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000645
Just van Rossumad33d722002-11-21 10:23:04 +0000646def copy(src, dst, mkdirs=0):
647 """Copy a file or a directory."""
648 if mkdirs:
649 makedirs(os.path.dirname(dst))
650 if os.path.isdir(src):
651 shutil.copytree(src, dst)
652 else:
653 shutil.copy2(src, dst)
654
655def copytodir(src, dstdir):
656 """Copy a file or a directory to an existing directory."""
657 dst = pathjoin(dstdir, os.path.basename(src))
658 copy(src, dst)
659
660def makedirs(dir):
661 """Make all directories leading up to 'dir' including the leaf
662 directory. Don't moan if any path element already exists."""
663 try:
664 os.makedirs(dir)
665 except OSError, why:
666 if why.errno != errno.EEXIST:
667 raise
668
669def symlink(src, dst, mkdirs=0):
670 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000671 if not os.path.exists(src):
672 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000673 if mkdirs:
674 makedirs(os.path.dirname(dst))
675 os.symlink(os.path.abspath(src), dst)
676
677def pathjoin(*args):
678 """Safe wrapper for os.path.join: asserts that all but the first
679 argument are relative paths."""
680 for seg in args[1:]:
681 assert seg[0] != "/"
682 return os.path.join(*args)
683
684
Just van Rossumceeb9622002-11-21 23:19:37 +0000685cmdline_doc = """\
686Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000687 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000688 python mybuildscript.py [options] command
689
690Commands:
691 build build the application
692 report print a report
693
694Options:
695 -b, --builddir=DIR the build directory; defaults to "build"
696 -n, --name=NAME application name
697 -r, --resource=FILE extra file or folder to be copied to Resources
Just van Rossum7215e082003-02-25 21:00:55 +0000698 -f, --file=SRC:DST extra file or folder to be copied into the bundle;
699 DST must be a path relative to the bundle root
Just van Rossumceeb9622002-11-21 23:19:37 +0000700 -e, --executable=FILE the executable to be used
701 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000702 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000703 -p, --plist=FILE .plist file (default: generate one)
704 --nib=NAME main nib name
705 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000706 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000707 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000708 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000709 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000710 --standalone build a standalone application, which is fully
711 independent of a Python installation
712 -x, --exclude=MODULE exclude module (with --standalone)
713 -i, --include=MODULE include module (with --standalone)
714 --package=PACKAGE include a whole package (with --standalone)
715 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000716 -v, --verbose increase verbosity level
717 -q, --quiet decrease verbosity level
718 -h, --help print this message
719"""
720
721def usage(msg=None):
722 if msg:
723 print msg
724 print cmdline_doc
725 sys.exit(1)
726
727def main(builder=None):
728 if builder is None:
729 builder = AppBuilder(verbosity=1)
730
Jack Jansen00cbf072003-02-24 16:27:08 +0000731 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
Just van Rossum7215e082003-02-25 21:00:55 +0000732 longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000733 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000734 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000735 "exclude=", "include=", "package=", "strip", "iconfile=")
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 Rossumceeb9622002-11-21 23:19:37 +0000765 elif opt == "--nib":
766 builder.nibname = arg
767 elif opt in ('-p', '--plist'):
768 builder.plist = Plist.fromFile(arg)
769 elif opt in ('-l', '--link'):
770 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000771 elif opt == '--link-exec':
772 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000773 elif opt in ('-h', '--help'):
774 usage()
775 elif opt in ('-v', '--verbose'):
776 builder.verbosity += 1
777 elif opt in ('-q', '--quiet'):
778 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000779 elif opt == '--standalone':
780 builder.standalone = 1
781 elif opt in ('-x', '--exclude'):
782 builder.excludeModules.append(arg)
783 elif opt in ('-i', '--include'):
784 builder.includeModules.append(arg)
785 elif opt == '--package':
786 builder.includePackages.append(arg)
787 elif opt == '--strip':
788 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000789
790 if len(args) != 1:
791 usage("Must specify one command ('build', 'report' or 'help')")
792 command = args[0]
793
794 if command == "build":
795 builder.setup()
796 builder.build()
797 elif command == "report":
798 builder.setup()
799 builder.report()
800 elif command == "help":
801 usage()
802 else:
803 usage("Unknown command '%s'" % command)
804
805
Just van Rossumad33d722002-11-21 10:23:04 +0000806def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000807 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000808 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000809
810
811if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000812 main()