blob: 3034ec581414d7bfcfe62a4456dba82856107ef5 [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 Rossumda302da2002-11-23 22:26:44 +0000284 # Symlink the executable instead of copying it.
285 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000286
Just van Rossumcef32882002-11-26 00:34:52 +0000287 # If True, build standalone app.
288 standalone = 0
289
290 # The following attributes are only used when building a standalone app.
291
292 # Exclude these modules.
293 excludeModules = []
294
295 # Include these modules.
296 includeModules = []
297
298 # Include these packages.
299 includePackages = []
300
301 # Strip binaries.
302 strip = 0
303
Just van Rossumcef32882002-11-26 00:34:52 +0000304 # Found Python modules: [(name, codeobject, ispkg), ...]
305 pymodules = []
306
307 # Modules that modulefinder couldn't find:
308 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000309 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000310
311 # List of all binaries (executables or shared libs), for stripping purposes
312 binaries = []
313
Just van Rossumceeb9622002-11-21 23:19:37 +0000314 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000315 if self.standalone and self.mainprogram is None:
316 raise BundleBuilderError, ("must specify 'mainprogram' when "
317 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000318 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000319 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000320 "'executable' and 'mainprogram'")
321
322 if self.name is not None:
323 pass
324 elif self.mainprogram is not None:
325 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
326 elif executable is not None:
327 self.name = os.path.splitext(os.path.basename(self.executable))[0]
328 if self.name[-4:] != ".app":
329 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000330
Just van Rossum74bdca82002-11-28 11:30:56 +0000331 if self.executable is None:
332 if not self.standalone:
333 self.symlink_exec = 1
334 self.executable = sys.executable
335
Just van Rossumceeb9622002-11-21 23:19:37 +0000336 if self.nibname:
337 self.plist.NSMainNibFile = self.nibname
338 if not hasattr(self.plist, "NSPrincipalClass"):
339 self.plist.NSPrincipalClass = "NSApplication"
340
341 BundleBuilder.setup(self)
342
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000343 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000344
Just van Rossumcef32882002-11-26 00:34:52 +0000345 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000346 self.findDependencies()
347
Just van Rossumf7aba232002-11-22 00:31:50 +0000348 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000349 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000350 if self.executable is not None:
351 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000352 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000353 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000354 execname = os.path.basename(self.executable)
355 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000356 if not self.symlink_exec:
357 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000358 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000359 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000360
361 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000362 mainprogram = os.path.basename(self.mainprogram)
363 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
364 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000365 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000366 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000367 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000368 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000369 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
370 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000371
Just van Rossum16aebf72002-11-22 11:43:10 +0000372 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000373 if self.standalone:
374 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000375 if self.strip and not self.symlink:
376 self.stripBinaries()
377
Just van Rossum16aebf72002-11-22 11:43:10 +0000378 if self.symlink_exec and self.executable:
379 self.message("Symlinking executable %s to %s" % (self.executable,
380 self.execpath), 2)
381 dst = pathjoin(self.bundlepath, self.execpath)
382 makedirs(os.path.dirname(dst))
383 os.symlink(os.path.abspath(self.executable), dst)
384
Just van Rossum74bdca82002-11-28 11:30:56 +0000385 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000386 self.reportMissing()
387
388 def addPythonModules(self):
389 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000390
Just van Rossum109ecbf2003-01-02 13:13:01 +0000391 if USE_ZIPIMPORT:
392 # Create a zip file containing all modules as pyc.
393 import zipfile
394 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000395 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000396 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
397 for name, code, ispkg in self.pymodules:
398 self.message("Adding Python module %s" % name, 2)
399 path, pyc = getPycData(name, code, ispkg)
400 zf.writestr(path, pyc)
401 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000402 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000403 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
404 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000405 writePyc(SITE_CO, sitepath)
406 else:
407 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000408 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000409 if ispkg:
410 name += ".__init__"
411 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000412 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000413
414 if ispkg:
415 self.message("Adding Python package %s" % path, 2)
416 else:
417 self.message("Adding Python module %s" % path, 2)
418
419 abspath = pathjoin(self.bundlepath, path)
420 makedirs(os.path.dirname(abspath))
421 writePyc(code, abspath)
422
423 def stripBinaries(self):
424 if not os.path.exists(STRIP_EXEC):
425 self.message("Error: can't strip binaries: no strip program at "
426 "%s" % STRIP_EXEC, 0)
427 else:
428 self.message("Stripping binaries", 1)
429 for relpath in self.binaries:
430 self.message("Stripping %s" % relpath, 2)
431 abspath = pathjoin(self.bundlepath, relpath)
432 assert not os.path.islink(abspath)
433 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
434
435 def findDependencies(self):
436 self.message("Finding module dependencies", 1)
437 import modulefinder
438 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000439 if USE_ZIPIMPORT:
440 # zipimport imports zlib, must add it manually
441 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000442 # manually add our own site.py
443 site = mf.add_module("site")
444 site.__code__ = SITE_CO
445 mf.scan_code(SITE_CO, site)
446
447 includeModules = self.includeModules[:]
448 for name in self.includePackages:
449 includeModules.extend(findPackageContents(name).keys())
450 for name in includeModules:
451 try:
452 mf.import_hook(name)
453 except ImportError:
454 self.missingModules.append(name)
455
Just van Rossumcef32882002-11-26 00:34:52 +0000456 mf.run_script(self.mainprogram)
457 modules = mf.modules.items()
458 modules.sort()
459 for name, mod in modules:
460 if mod.__file__ and mod.__code__ is None:
461 # C extension
462 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000463 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000464 if USE_ZIPIMPORT:
465 # Python modules are stored in a Zip archive, but put
466 # extensions in Contents/Resources/.a and add a tiny "loader"
467 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000468 dstpath = pathjoin("Contents", "Resources", filename)
469 source = EXT_LOADER % {"name": name, "filename": filename}
470 code = compile(source, "<dynloader for %s>" % name, "exec")
471 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000472 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000473 # just copy the file
474 dstpath = name.split(".")[:-1] + [filename]
475 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000476 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000477 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000478 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000479 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000480 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000481 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000482 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000483 self.pymodules.append((name, mod.__code__, ispkg))
484
Just van Rossum74bdca82002-11-28 11:30:56 +0000485 if hasattr(mf, "any_missing_maybe"):
486 missing, maybe = mf.any_missing_maybe()
487 else:
488 missing = mf.any_missing()
489 maybe = []
490 self.missingModules.extend(missing)
491 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000492
493 def reportMissing(self):
494 missing = [name for name in self.missingModules
495 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000496 if self.maybeMissingModules:
497 maybe = self.maybeMissingModules
498 else:
499 maybe = [name for name in missing if "." in name]
500 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000501 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000502 maybe.sort()
503 if maybe:
504 self.message("Warning: couldn't find the following submodules:", 1)
505 self.message(" (Note that these could be false alarms -- "
506 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000507 self.message(" possible to distinguish between \"from package "
508 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000509 self.message(" and \"from package import name\")", 1)
510 for name in maybe:
511 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000512 if missing:
513 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000514 for name in missing:
515 self.message(" ? " + name, 1)
516
517 def report(self):
518 # XXX something decent
519 import pprint
520 pprint.pprint(self.__dict__)
521 if self.standalone:
522 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000523
524#
525# Utilities.
526#
527
528SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
529identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
530
531def findPackageContents(name, searchpath=None):
532 head = name.split(".")[-1]
533 if identifierRE.match(head) is None:
534 return {}
535 try:
536 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
537 except ImportError:
538 return {}
539 modules = {name: None}
540 if tp == imp.PKG_DIRECTORY and path:
541 files = os.listdir(path)
542 for sub in files:
543 sub, ext = os.path.splitext(sub)
544 fullname = name + "." + sub
545 if sub != "__init__" and fullname not in modules:
546 modules.update(findPackageContents(fullname, [path]))
547 return modules
548
549def writePyc(code, path):
550 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000551 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000552 f.write("\0" * 4) # don't bother about a time stamp
553 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000554 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000555
Just van Rossumad33d722002-11-21 10:23:04 +0000556def copy(src, dst, mkdirs=0):
557 """Copy a file or a directory."""
558 if mkdirs:
559 makedirs(os.path.dirname(dst))
560 if os.path.isdir(src):
561 shutil.copytree(src, dst)
562 else:
563 shutil.copy2(src, dst)
564
565def copytodir(src, dstdir):
566 """Copy a file or a directory to an existing directory."""
567 dst = pathjoin(dstdir, os.path.basename(src))
568 copy(src, dst)
569
570def makedirs(dir):
571 """Make all directories leading up to 'dir' including the leaf
572 directory. Don't moan if any path element already exists."""
573 try:
574 os.makedirs(dir)
575 except OSError, why:
576 if why.errno != errno.EEXIST:
577 raise
578
579def symlink(src, dst, mkdirs=0):
580 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000581 if not os.path.exists(src):
582 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000583 if mkdirs:
584 makedirs(os.path.dirname(dst))
585 os.symlink(os.path.abspath(src), dst)
586
587def pathjoin(*args):
588 """Safe wrapper for os.path.join: asserts that all but the first
589 argument are relative paths."""
590 for seg in args[1:]:
591 assert seg[0] != "/"
592 return os.path.join(*args)
593
594
Just van Rossumceeb9622002-11-21 23:19:37 +0000595cmdline_doc = """\
596Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000597 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000598 python mybuildscript.py [options] command
599
600Commands:
601 build build the application
602 report print a report
603
604Options:
605 -b, --builddir=DIR the build directory; defaults to "build"
606 -n, --name=NAME application name
607 -r, --resource=FILE extra file or folder to be copied to Resources
608 -e, --executable=FILE the executable to be used
609 -m, --mainprogram=FILE the Python main program
610 -p, --plist=FILE .plist file (default: generate one)
611 --nib=NAME main nib name
612 -c, --creator=CCCC 4-char creator code (default: '????')
613 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000614 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000615 --standalone build a standalone application, which is fully
616 independent of a Python installation
617 -x, --exclude=MODULE exclude module (with --standalone)
618 -i, --include=MODULE include module (with --standalone)
619 --package=PACKAGE include a whole package (with --standalone)
620 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000621 -v, --verbose increase verbosity level
622 -q, --quiet decrease verbosity level
623 -h, --help print this message
624"""
625
626def usage(msg=None):
627 if msg:
628 print msg
629 print cmdline_doc
630 sys.exit(1)
631
632def main(builder=None):
633 if builder is None:
634 builder = AppBuilder(verbosity=1)
635
Just van Rossumcef32882002-11-26 00:34:52 +0000636 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000637 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000638 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000639 "link-exec", "help", "verbose", "quiet", "standalone",
640 "exclude=", "include=", "package=", "strip")
Just van Rossumceeb9622002-11-21 23:19:37 +0000641
642 try:
643 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
644 except getopt.error:
645 usage()
646
647 for opt, arg in options:
648 if opt in ('-b', '--builddir'):
649 builder.builddir = arg
650 elif opt in ('-n', '--name'):
651 builder.name = arg
652 elif opt in ('-r', '--resource'):
653 builder.resources.append(arg)
654 elif opt in ('-e', '--executable'):
655 builder.executable = arg
656 elif opt in ('-m', '--mainprogram'):
657 builder.mainprogram = arg
658 elif opt in ('-c', '--creator'):
659 builder.creator = arg
660 elif opt == "--nib":
661 builder.nibname = arg
662 elif opt in ('-p', '--plist'):
663 builder.plist = Plist.fromFile(arg)
664 elif opt in ('-l', '--link'):
665 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000666 elif opt == '--link-exec':
667 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000668 elif opt in ('-h', '--help'):
669 usage()
670 elif opt in ('-v', '--verbose'):
671 builder.verbosity += 1
672 elif opt in ('-q', '--quiet'):
673 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000674 elif opt == '--standalone':
675 builder.standalone = 1
676 elif opt in ('-x', '--exclude'):
677 builder.excludeModules.append(arg)
678 elif opt in ('-i', '--include'):
679 builder.includeModules.append(arg)
680 elif opt == '--package':
681 builder.includePackages.append(arg)
682 elif opt == '--strip':
683 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000684
685 if len(args) != 1:
686 usage("Must specify one command ('build', 'report' or 'help')")
687 command = args[0]
688
689 if command == "build":
690 builder.setup()
691 builder.build()
692 elif command == "report":
693 builder.setup()
694 builder.report()
695 elif command == "help":
696 usage()
697 else:
698 usage("Unknown command '%s'" % command)
699
700
Just van Rossumad33d722002-11-21 10:23:04 +0000701def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000702 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000703 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000704
705
706if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000707 main()