blob: 58f75d7a189704e17e24ada323e1f817f0b8b63a [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
40
Just van Rossumcef32882002-11-26 00:34:52 +000041class BundleBuilderError(Exception): pass
42
43
Just van Rossumda302da2002-11-23 22:26:44 +000044class Defaults:
45
46 """Class attributes that don't start with an underscore and are
47 not functions or classmethods are (deep)copied to self.__dict__.
48 This allows for mutable default values.
49 """
50
51 def __init__(self, **kwargs):
52 defaults = self._getDefaults()
53 defaults.update(kwargs)
54 self.__dict__.update(defaults)
55
56 def _getDefaults(cls):
57 defaults = {}
58 for name, value in cls.__dict__.items():
59 if name[0] != "_" and not isinstance(value,
60 (function, classmethod)):
61 defaults[name] = deepcopy(value)
62 for base in cls.__bases__:
63 if hasattr(base, "_getDefaults"):
64 defaults.update(base._getDefaults())
65 return defaults
66 _getDefaults = classmethod(_getDefaults)
Just van Rossumad33d722002-11-21 10:23:04 +000067
68
Just van Rossumda302da2002-11-23 22:26:44 +000069class BundleBuilder(Defaults):
Just van Rossumad33d722002-11-21 10:23:04 +000070
71 """BundleBuilder is a barebones class for assembling bundles. It
72 knows nothing about executables or icons, it only copies files
73 and creates the PkgInfo and Info.plist files.
Just van Rossumad33d722002-11-21 10:23:04 +000074 """
75
Just van Rossumda302da2002-11-23 22:26:44 +000076 # (Note that Defaults.__init__ (deep)copies these values to
77 # instance variables. Mutable defaults are therefore safe.)
78
79 # Name of the bundle, with or without extension.
80 name = None
81
82 # The property list ("plist")
83 plist = Plist(CFBundleDevelopmentRegion = "English",
84 CFBundleInfoDictionaryVersion = "6.0")
85
86 # The type of the bundle.
87 type = "APPL"
88 # The creator code of the bundle.
Just van Rossume6b49022002-11-24 01:23:45 +000089 creator = None
Just van Rossumda302da2002-11-23 22:26:44 +000090
91 # List of files that have to be copied to <bundle>/Contents/Resources.
92 resources = []
93
94 # List of (src, dest) tuples; dest should be a path relative to the bundle
95 # (eg. "Contents/Resources/MyStuff/SomeFile.ext).
96 files = []
97
98 # Directory where the bundle will be assembled.
99 builddir = "build"
100
101 # platform, name of the subfolder of Contents that contains the executable.
102 platform = "MacOS"
103
104 # Make symlinks instead copying files. This is handy during debugging, but
105 # makes the bundle non-distributable.
106 symlink = 0
107
108 # Verbosity level.
109 verbosity = 1
Just van Rossumad33d722002-11-21 10:23:04 +0000110
Just van Rossumceeb9622002-11-21 23:19:37 +0000111 def setup(self):
Just van Rossumda302da2002-11-23 22:26:44 +0000112 # XXX rethink self.name munging, this is brittle.
Just van Rossumceeb9622002-11-21 23:19:37 +0000113 self.name, ext = os.path.splitext(self.name)
114 if not ext:
115 ext = ".bundle"
Just van Rossumda302da2002-11-23 22:26:44 +0000116 bundleextension = ext
Just van Rossumceeb9622002-11-21 23:19:37 +0000117 # misc (derived) attributes
Just van Rossumda302da2002-11-23 22:26:44 +0000118 self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
Just van Rossumceeb9622002-11-21 23:19:37 +0000119 self.execdir = pathjoin("Contents", self.platform)
120
Just van Rossumda302da2002-11-23 22:26:44 +0000121 plist = self.plist
Just van Rossumceeb9622002-11-21 23:19:37 +0000122 plist.CFBundleName = self.name
123 plist.CFBundlePackageType = self.type
Just van Rossume6b49022002-11-24 01:23:45 +0000124 if self.creator is None:
125 if hasattr(plist, "CFBundleSignature"):
126 self.creator = plist.CFBundleSignature
127 else:
128 self.creator = "????"
Just van Rossumceeb9622002-11-21 23:19:37 +0000129 plist.CFBundleSignature = self.creator
Just van Rossum9896ea22003-01-13 23:30:04 +0000130 if not hasattr(plist, "CFBundleIdentifier"):
131 plist.CFBundleIdentifier = self.name
Just van Rossumceeb9622002-11-21 23:19:37 +0000132
Just van Rossumad33d722002-11-21 10:23:04 +0000133 def build(self):
134 """Build the bundle."""
135 builddir = self.builddir
136 if builddir and not os.path.exists(builddir):
137 os.mkdir(builddir)
138 self.message("Building %s" % repr(self.bundlepath), 1)
139 if os.path.exists(self.bundlepath):
140 shutil.rmtree(self.bundlepath)
141 os.mkdir(self.bundlepath)
142 self.preProcess()
143 self._copyFiles()
144 self._addMetaFiles()
145 self.postProcess()
Just van Rossum535ffa22002-11-29 20:06:52 +0000146 self.message("Done.", 1)
Just van Rossumad33d722002-11-21 10:23:04 +0000147
148 def preProcess(self):
149 """Hook for subclasses."""
150 pass
151 def postProcess(self):
152 """Hook for subclasses."""
153 pass
154
155 def _addMetaFiles(self):
156 contents = pathjoin(self.bundlepath, "Contents")
157 makedirs(contents)
158 #
159 # Write Contents/PkgInfo
160 assert len(self.type) == len(self.creator) == 4, \
161 "type and creator must be 4-byte strings."
162 pkginfo = pathjoin(contents, "PkgInfo")
163 f = open(pkginfo, "wb")
164 f.write(self.type + self.creator)
165 f.close()
166 #
167 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000168 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000169 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000170
171 def _copyFiles(self):
172 files = self.files[:]
173 for path in self.resources:
174 files.append((path, pathjoin("Contents", "Resources",
175 os.path.basename(path))))
176 if self.symlink:
177 self.message("Making symbolic links", 1)
178 msg = "Making symlink from"
179 else:
180 self.message("Copying files", 1)
181 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000182 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000183 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000184 if os.path.isdir(src):
185 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
186 else:
187 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000188 dst = pathjoin(self.bundlepath, dst)
189 if self.symlink:
190 symlink(src, dst, mkdirs=1)
191 else:
192 copy(src, dst, mkdirs=1)
193
194 def message(self, msg, level=0):
195 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000196 indent = ""
197 if level > 1:
198 indent = (level - 1) * " "
199 sys.stderr.write(indent + msg + "\n")
200
201 def report(self):
202 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000203 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000204
205
Just van Rossumcef32882002-11-26 00:34:52 +0000206if __debug__:
207 PYC_EXT = ".pyc"
208else:
209 PYC_EXT = ".pyo"
210
211MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000212USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000213
214# For standalone apps, we have our own minimal site.py. We don't need
215# all the cruft of the real site.py.
216SITE_PY = """\
217import sys
218del sys.path[1:] # sys.path[0] is Contents/Resources/
219"""
220
Just van Rossum109ecbf2003-01-02 13:13:01 +0000221if USE_ZIPIMPORT:
222 ZIP_ARCHIVE = "Modules.zip"
223 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
224 def getPycData(fullname, code, ispkg):
225 if ispkg:
226 fullname += ".__init__"
227 path = fullname.replace(".", os.sep) + PYC_EXT
228 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000229
Just van Rossum74bdca82002-11-28 11:30:56 +0000230SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossumcef32882002-11-26 00:34:52 +0000231
Just van Rossum535ffa22002-11-29 20:06:52 +0000232EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000233def __load():
234 import imp, sys, os
235 for p in sys.path:
236 path = os.path.join(p, "%(filename)s")
237 if os.path.exists(path):
238 break
239 else:
240 assert 0, "file not found: %(filename)s"
241 mod = imp.load_dynamic("%(name)s", path)
242
243__load()
244del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000245"""
246
Just van Rossumcef32882002-11-26 00:34:52 +0000247MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
248 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
249 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
250]
251
252STRIP_EXEC = "/usr/bin/strip"
253
Just van Rossum74bdca82002-11-28 11:30:56 +0000254BOOTSTRAP_SCRIPT = """\
255#!/bin/sh
Just van Rossumad33d722002-11-21 10:23:04 +0000256
Just van Rossum74bdca82002-11-28 11:30:56 +0000257execdir=$(dirname ${0})
258executable=${execdir}/%(executable)s
259resdir=$(dirname ${execdir})/Resources
260main=${resdir}/%(mainprogram)s
261PYTHONPATH=$resdir
262export PYTHONPATH
263exec ${executable} ${main} ${1}
Just van Rossumad33d722002-11-21 10:23:04 +0000264"""
265
Just van Rossumcef32882002-11-26 00:34:52 +0000266
Just van Rossumad33d722002-11-21 10:23:04 +0000267class AppBuilder(BundleBuilder):
268
Just van Rossumda302da2002-11-23 22:26:44 +0000269 # A Python main program. If this argument is given, the main
270 # executable in the bundle will be a small wrapper that invokes
271 # the main program. (XXX Discuss why.)
272 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000273
Just van Rossumda302da2002-11-23 22:26:44 +0000274 # The main executable. If a Python main program is specified
275 # the executable will be copied to Resources and be invoked
276 # by the wrapper program mentioned above. Otherwise it will
277 # simply be used as the main executable.
278 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000279
Just van Rossumda302da2002-11-23 22:26:44 +0000280 # The name of the main nib, for Cocoa apps. *Must* be specified
281 # when building a Cocoa app.
282 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000283
Just van Rossum2aa09562003-02-01 08:34:46 +0000284 # The name of the icon file to be copied to Resources and used for
285 # the Finder icon.
286 iconfile = None
287
Just van Rossumda302da2002-11-23 22:26:44 +0000288 # Symlink the executable instead of copying it.
289 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000290
Just van Rossumcef32882002-11-26 00:34:52 +0000291 # If True, build standalone app.
292 standalone = 0
293
294 # The following attributes are only used when building a standalone app.
295
296 # Exclude these modules.
297 excludeModules = []
298
299 # Include these modules.
300 includeModules = []
301
302 # Include these packages.
303 includePackages = []
304
305 # Strip binaries.
306 strip = 0
307
Just van Rossumcef32882002-11-26 00:34:52 +0000308 # Found Python modules: [(name, codeobject, ispkg), ...]
309 pymodules = []
310
311 # Modules that modulefinder couldn't find:
312 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000313 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000314
315 # List of all binaries (executables or shared libs), for stripping purposes
316 binaries = []
317
Just van Rossumceeb9622002-11-21 23:19:37 +0000318 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000319 if self.standalone and self.mainprogram is None:
320 raise BundleBuilderError, ("must specify 'mainprogram' when "
321 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000322 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000323 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000324 "'executable' and 'mainprogram'")
325
326 if self.name is not None:
327 pass
328 elif self.mainprogram is not None:
329 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
330 elif executable is not None:
331 self.name = os.path.splitext(os.path.basename(self.executable))[0]
332 if self.name[-4:] != ".app":
333 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000334
Just van Rossum74bdca82002-11-28 11:30:56 +0000335 if self.executable is None:
336 if not self.standalone:
337 self.symlink_exec = 1
338 self.executable = sys.executable
339
Just van Rossumceeb9622002-11-21 23:19:37 +0000340 if self.nibname:
341 self.plist.NSMainNibFile = self.nibname
342 if not hasattr(self.plist, "NSPrincipalClass"):
343 self.plist.NSPrincipalClass = "NSApplication"
344
345 BundleBuilder.setup(self)
346
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000347 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000348
Just van Rossumcef32882002-11-26 00:34:52 +0000349 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000350 self.findDependencies()
351
Just van Rossumf7aba232002-11-22 00:31:50 +0000352 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000353 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000354 if self.executable is not None:
355 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000356 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000357 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000358 execname = os.path.basename(self.executable)
359 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000360 if not self.symlink_exec:
361 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000362 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000363 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000364
365 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000366 mainprogram = os.path.basename(self.mainprogram)
367 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
368 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000369 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000370 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000371 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000372 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000373 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
374 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000375
Just van Rossum2aa09562003-02-01 08:34:46 +0000376 if self.iconfile is not None:
377 iconbase = os.path.basename(self.iconfile)
378 self.plist.CFBundleIconFile = iconbase
379 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
380
Just van Rossum16aebf72002-11-22 11:43:10 +0000381 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000382 if self.standalone:
383 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000384 if self.strip and not self.symlink:
385 self.stripBinaries()
386
Just van Rossum16aebf72002-11-22 11:43:10 +0000387 if self.symlink_exec and self.executable:
388 self.message("Symlinking executable %s to %s" % (self.executable,
389 self.execpath), 2)
390 dst = pathjoin(self.bundlepath, self.execpath)
391 makedirs(os.path.dirname(dst))
392 os.symlink(os.path.abspath(self.executable), dst)
393
Just van Rossum74bdca82002-11-28 11:30:56 +0000394 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000395 self.reportMissing()
396
397 def addPythonModules(self):
398 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000399
Just van Rossum109ecbf2003-01-02 13:13:01 +0000400 if USE_ZIPIMPORT:
401 # Create a zip file containing all modules as pyc.
402 import zipfile
403 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000404 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000405 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
406 for name, code, ispkg in self.pymodules:
407 self.message("Adding Python module %s" % name, 2)
408 path, pyc = getPycData(name, code, ispkg)
409 zf.writestr(path, pyc)
410 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000411 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000412 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
413 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000414 writePyc(SITE_CO, sitepath)
415 else:
416 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000417 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000418 if ispkg:
419 name += ".__init__"
420 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000421 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000422
423 if ispkg:
424 self.message("Adding Python package %s" % path, 2)
425 else:
426 self.message("Adding Python module %s" % path, 2)
427
428 abspath = pathjoin(self.bundlepath, path)
429 makedirs(os.path.dirname(abspath))
430 writePyc(code, abspath)
431
432 def stripBinaries(self):
433 if not os.path.exists(STRIP_EXEC):
434 self.message("Error: can't strip binaries: no strip program at "
435 "%s" % STRIP_EXEC, 0)
436 else:
437 self.message("Stripping binaries", 1)
438 for relpath in self.binaries:
439 self.message("Stripping %s" % relpath, 2)
440 abspath = pathjoin(self.bundlepath, relpath)
441 assert not os.path.islink(abspath)
442 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
443
444 def findDependencies(self):
445 self.message("Finding module dependencies", 1)
446 import modulefinder
447 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000448 if USE_ZIPIMPORT:
449 # zipimport imports zlib, must add it manually
450 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000451 # manually add our own site.py
452 site = mf.add_module("site")
453 site.__code__ = SITE_CO
454 mf.scan_code(SITE_CO, site)
455
456 includeModules = self.includeModules[:]
457 for name in self.includePackages:
458 includeModules.extend(findPackageContents(name).keys())
459 for name in includeModules:
460 try:
461 mf.import_hook(name)
462 except ImportError:
463 self.missingModules.append(name)
464
Just van Rossumcef32882002-11-26 00:34:52 +0000465 mf.run_script(self.mainprogram)
466 modules = mf.modules.items()
467 modules.sort()
468 for name, mod in modules:
469 if mod.__file__ and mod.__code__ is None:
470 # C extension
471 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000472 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000473 if USE_ZIPIMPORT:
474 # Python modules are stored in a Zip archive, but put
475 # extensions in Contents/Resources/.a and add a tiny "loader"
476 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000477 dstpath = pathjoin("Contents", "Resources", filename)
478 source = EXT_LOADER % {"name": name, "filename": filename}
479 code = compile(source, "<dynloader for %s>" % name, "exec")
480 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000481 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000482 # just copy the file
483 dstpath = name.split(".")[:-1] + [filename]
484 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000485 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000486 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000487 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000488 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000489 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000490 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000491 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000492 self.pymodules.append((name, mod.__code__, ispkg))
493
Just van Rossum74bdca82002-11-28 11:30:56 +0000494 if hasattr(mf, "any_missing_maybe"):
495 missing, maybe = mf.any_missing_maybe()
496 else:
497 missing = mf.any_missing()
498 maybe = []
499 self.missingModules.extend(missing)
500 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000501
502 def reportMissing(self):
503 missing = [name for name in self.missingModules
504 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000505 if self.maybeMissingModules:
506 maybe = self.maybeMissingModules
507 else:
508 maybe = [name for name in missing if "." in name]
509 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000510 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000511 maybe.sort()
512 if maybe:
513 self.message("Warning: couldn't find the following submodules:", 1)
514 self.message(" (Note that these could be false alarms -- "
515 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000516 self.message(" possible to distinguish between \"from package "
517 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000518 self.message(" and \"from package import name\")", 1)
519 for name in maybe:
520 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000521 if missing:
522 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000523 for name in missing:
524 self.message(" ? " + name, 1)
525
526 def report(self):
527 # XXX something decent
528 import pprint
529 pprint.pprint(self.__dict__)
530 if self.standalone:
531 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000532
533#
534# Utilities.
535#
536
537SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
538identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
539
540def findPackageContents(name, searchpath=None):
541 head = name.split(".")[-1]
542 if identifierRE.match(head) is None:
543 return {}
544 try:
545 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
546 except ImportError:
547 return {}
548 modules = {name: None}
549 if tp == imp.PKG_DIRECTORY and path:
550 files = os.listdir(path)
551 for sub in files:
552 sub, ext = os.path.splitext(sub)
553 fullname = name + "." + sub
554 if sub != "__init__" and fullname not in modules:
555 modules.update(findPackageContents(fullname, [path]))
556 return modules
557
558def writePyc(code, path):
559 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000560 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000561 f.write("\0" * 4) # don't bother about a time stamp
562 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000563 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000564
Just van Rossumad33d722002-11-21 10:23:04 +0000565def copy(src, dst, mkdirs=0):
566 """Copy a file or a directory."""
567 if mkdirs:
568 makedirs(os.path.dirname(dst))
569 if os.path.isdir(src):
570 shutil.copytree(src, dst)
571 else:
572 shutil.copy2(src, dst)
573
574def copytodir(src, dstdir):
575 """Copy a file or a directory to an existing directory."""
576 dst = pathjoin(dstdir, os.path.basename(src))
577 copy(src, dst)
578
579def makedirs(dir):
580 """Make all directories leading up to 'dir' including the leaf
581 directory. Don't moan if any path element already exists."""
582 try:
583 os.makedirs(dir)
584 except OSError, why:
585 if why.errno != errno.EEXIST:
586 raise
587
588def symlink(src, dst, mkdirs=0):
589 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000590 if not os.path.exists(src):
591 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000592 if mkdirs:
593 makedirs(os.path.dirname(dst))
594 os.symlink(os.path.abspath(src), dst)
595
596def pathjoin(*args):
597 """Safe wrapper for os.path.join: asserts that all but the first
598 argument are relative paths."""
599 for seg in args[1:]:
600 assert seg[0] != "/"
601 return os.path.join(*args)
602
603
Just van Rossumceeb9622002-11-21 23:19:37 +0000604cmdline_doc = """\
605Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000606 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000607 python mybuildscript.py [options] command
608
609Commands:
610 build build the application
611 report print a report
612
613Options:
614 -b, --builddir=DIR the build directory; defaults to "build"
615 -n, --name=NAME application name
616 -r, --resource=FILE extra file or folder to be copied to Resources
617 -e, --executable=FILE the executable to be used
618 -m, --mainprogram=FILE the Python main program
619 -p, --plist=FILE .plist file (default: generate one)
620 --nib=NAME main nib name
621 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum2aa09562003-02-01 08:34:46 +0000622 --iconfile=FILE filename of the icon (an .icns file) to be used
623 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000624 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000625 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000626 --standalone build a standalone application, which is fully
627 independent of a Python installation
628 -x, --exclude=MODULE exclude module (with --standalone)
629 -i, --include=MODULE include module (with --standalone)
630 --package=PACKAGE include a whole package (with --standalone)
631 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000632 -v, --verbose increase verbosity level
633 -q, --quiet decrease verbosity level
634 -h, --help print this message
635"""
636
637def usage(msg=None):
638 if msg:
639 print msg
640 print cmdline_doc
641 sys.exit(1)
642
643def main(builder=None):
644 if builder is None:
645 builder = AppBuilder(verbosity=1)
646
Just van Rossumcef32882002-11-26 00:34:52 +0000647 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000648 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000649 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000650 "link-exec", "help", "verbose", "quiet", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000651 "exclude=", "include=", "package=", "strip", "iconfile=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000652
653 try:
654 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
655 except getopt.error:
656 usage()
657
658 for opt, arg in options:
659 if opt in ('-b', '--builddir'):
660 builder.builddir = arg
661 elif opt in ('-n', '--name'):
662 builder.name = arg
663 elif opt in ('-r', '--resource'):
664 builder.resources.append(arg)
665 elif opt in ('-e', '--executable'):
666 builder.executable = arg
667 elif opt in ('-m', '--mainprogram'):
668 builder.mainprogram = arg
669 elif opt in ('-c', '--creator'):
670 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000671 elif opt == '--iconfile':
672 builder.iconfile = arg
Just van Rossumceeb9622002-11-21 23:19:37 +0000673 elif opt == "--nib":
674 builder.nibname = arg
675 elif opt in ('-p', '--plist'):
676 builder.plist = Plist.fromFile(arg)
677 elif opt in ('-l', '--link'):
678 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000679 elif opt == '--link-exec':
680 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000681 elif opt in ('-h', '--help'):
682 usage()
683 elif opt in ('-v', '--verbose'):
684 builder.verbosity += 1
685 elif opt in ('-q', '--quiet'):
686 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000687 elif opt == '--standalone':
688 builder.standalone = 1
689 elif opt in ('-x', '--exclude'):
690 builder.excludeModules.append(arg)
691 elif opt in ('-i', '--include'):
692 builder.includeModules.append(arg)
693 elif opt == '--package':
694 builder.includePackages.append(arg)
695 elif opt == '--strip':
696 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000697
698 if len(args) != 1:
699 usage("Must specify one command ('build', 'report' or 'help')")
700 command = args[0]
701
702 if command == "build":
703 builder.setup()
704 builder.build()
705 elif command == "report":
706 builder.setup()
707 builder.report()
708 elif command == "help":
709 usage()
710 else:
711 usage("Unknown command '%s'" % command)
712
713
Just van Rossumad33d722002-11-21 10:23:04 +0000714def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000715 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000716 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000717
718
719if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000720 main()