blob: 749d85104b9308adda53745f259f373e56597f8b [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 Rossumceeb9622002-11-21 23:19:37 +0000130
Just van Rossumad33d722002-11-21 10:23:04 +0000131 def build(self):
132 """Build the bundle."""
133 builddir = self.builddir
134 if builddir and not os.path.exists(builddir):
135 os.mkdir(builddir)
136 self.message("Building %s" % repr(self.bundlepath), 1)
137 if os.path.exists(self.bundlepath):
138 shutil.rmtree(self.bundlepath)
139 os.mkdir(self.bundlepath)
140 self.preProcess()
141 self._copyFiles()
142 self._addMetaFiles()
143 self.postProcess()
Just van Rossum535ffa22002-11-29 20:06:52 +0000144 self.message("Done.", 1)
Just van Rossumad33d722002-11-21 10:23:04 +0000145
146 def preProcess(self):
147 """Hook for subclasses."""
148 pass
149 def postProcess(self):
150 """Hook for subclasses."""
151 pass
152
153 def _addMetaFiles(self):
154 contents = pathjoin(self.bundlepath, "Contents")
155 makedirs(contents)
156 #
157 # Write Contents/PkgInfo
158 assert len(self.type) == len(self.creator) == 4, \
159 "type and creator must be 4-byte strings."
160 pkginfo = pathjoin(contents, "PkgInfo")
161 f = open(pkginfo, "wb")
162 f.write(self.type + self.creator)
163 f.close()
164 #
165 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000166 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000167 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000168
169 def _copyFiles(self):
170 files = self.files[:]
171 for path in self.resources:
172 files.append((path, pathjoin("Contents", "Resources",
173 os.path.basename(path))))
174 if self.symlink:
175 self.message("Making symbolic links", 1)
176 msg = "Making symlink from"
177 else:
178 self.message("Copying files", 1)
179 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000180 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000181 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000182 if os.path.isdir(src):
183 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
184 else:
185 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000186 dst = pathjoin(self.bundlepath, dst)
187 if self.symlink:
188 symlink(src, dst, mkdirs=1)
189 else:
190 copy(src, dst, mkdirs=1)
191
192 def message(self, msg, level=0):
193 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000194 indent = ""
195 if level > 1:
196 indent = (level - 1) * " "
197 sys.stderr.write(indent + msg + "\n")
198
199 def report(self):
200 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000201 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000202
203
Just van Rossumcef32882002-11-26 00:34:52 +0000204if __debug__:
205 PYC_EXT = ".pyc"
206else:
207 PYC_EXT = ".pyo"
208
209MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000210USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000211
212# For standalone apps, we have our own minimal site.py. We don't need
213# all the cruft of the real site.py.
214SITE_PY = """\
215import sys
216del sys.path[1:] # sys.path[0] is Contents/Resources/
217"""
218
Just van Rossum109ecbf2003-01-02 13:13:01 +0000219if USE_ZIPIMPORT:
220 ZIP_ARCHIVE = "Modules.zip"
221 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
222 def getPycData(fullname, code, ispkg):
223 if ispkg:
224 fullname += ".__init__"
225 path = fullname.replace(".", os.sep) + PYC_EXT
226 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000227
Just van Rossum74bdca82002-11-28 11:30:56 +0000228SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossumcef32882002-11-26 00:34:52 +0000229
Just van Rossum535ffa22002-11-29 20:06:52 +0000230EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000231def __load():
232 import imp, sys, os
233 for p in sys.path:
234 path = os.path.join(p, "%(filename)s")
235 if os.path.exists(path):
236 break
237 else:
238 assert 0, "file not found: %(filename)s"
239 mod = imp.load_dynamic("%(name)s", path)
240
241__load()
242del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000243"""
244
Just van Rossumcef32882002-11-26 00:34:52 +0000245MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
246 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
247 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
248]
249
250STRIP_EXEC = "/usr/bin/strip"
251
Just van Rossum74bdca82002-11-28 11:30:56 +0000252BOOTSTRAP_SCRIPT = """\
253#!/bin/sh
Just van Rossumad33d722002-11-21 10:23:04 +0000254
Just van Rossum74bdca82002-11-28 11:30:56 +0000255execdir=$(dirname ${0})
256executable=${execdir}/%(executable)s
257resdir=$(dirname ${execdir})/Resources
258main=${resdir}/%(mainprogram)s
259PYTHONPATH=$resdir
260export PYTHONPATH
261exec ${executable} ${main} ${1}
Just van Rossumad33d722002-11-21 10:23:04 +0000262"""
263
Just van Rossumcef32882002-11-26 00:34:52 +0000264
Just van Rossumad33d722002-11-21 10:23:04 +0000265class AppBuilder(BundleBuilder):
266
Just van Rossumda302da2002-11-23 22:26:44 +0000267 # A Python main program. If this argument is given, the main
268 # executable in the bundle will be a small wrapper that invokes
269 # the main program. (XXX Discuss why.)
270 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000271
Just van Rossumda302da2002-11-23 22:26:44 +0000272 # The main executable. If a Python main program is specified
273 # the executable will be copied to Resources and be invoked
274 # by the wrapper program mentioned above. Otherwise it will
275 # simply be used as the main executable.
276 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000277
Just van Rossumda302da2002-11-23 22:26:44 +0000278 # The name of the main nib, for Cocoa apps. *Must* be specified
279 # when building a Cocoa app.
280 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000281
Just van Rossumda302da2002-11-23 22:26:44 +0000282 # Symlink the executable instead of copying it.
283 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000284
Just van Rossumcef32882002-11-26 00:34:52 +0000285 # If True, build standalone app.
286 standalone = 0
287
288 # The following attributes are only used when building a standalone app.
289
290 # Exclude these modules.
291 excludeModules = []
292
293 # Include these modules.
294 includeModules = []
295
296 # Include these packages.
297 includePackages = []
298
299 # Strip binaries.
300 strip = 0
301
Just van Rossumcef32882002-11-26 00:34:52 +0000302 # Found Python modules: [(name, codeobject, ispkg), ...]
303 pymodules = []
304
305 # Modules that modulefinder couldn't find:
306 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000307 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000308
309 # List of all binaries (executables or shared libs), for stripping purposes
310 binaries = []
311
Just van Rossumceeb9622002-11-21 23:19:37 +0000312 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000313 if self.standalone and self.mainprogram is None:
314 raise BundleBuilderError, ("must specify 'mainprogram' when "
315 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000316 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000317 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000318 "'executable' and 'mainprogram'")
319
320 if self.name is not None:
321 pass
322 elif self.mainprogram is not None:
323 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
324 elif executable is not None:
325 self.name = os.path.splitext(os.path.basename(self.executable))[0]
326 if self.name[-4:] != ".app":
327 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000328
Just van Rossum74bdca82002-11-28 11:30:56 +0000329 if self.executable is None:
330 if not self.standalone:
331 self.symlink_exec = 1
332 self.executable = sys.executable
333
Just van Rossumceeb9622002-11-21 23:19:37 +0000334 if self.nibname:
335 self.plist.NSMainNibFile = self.nibname
336 if not hasattr(self.plist, "NSPrincipalClass"):
337 self.plist.NSPrincipalClass = "NSApplication"
338
339 BundleBuilder.setup(self)
340
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000341 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000342
Just van Rossumcef32882002-11-26 00:34:52 +0000343 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000344 self.findDependencies()
345
Just van Rossumf7aba232002-11-22 00:31:50 +0000346 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000347 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000348 if self.executable is not None:
349 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000350 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000351 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000352 execname = os.path.basename(self.executable)
353 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000354 if not self.symlink_exec:
355 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000356 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000357 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000358
359 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000360 mainprogram = os.path.basename(self.mainprogram)
361 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
362 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000363 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000364 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000365 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000366 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000367 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
368 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000369
Just van Rossum16aebf72002-11-22 11:43:10 +0000370 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000371 if self.standalone:
372 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000373 if self.strip and not self.symlink:
374 self.stripBinaries()
375
Just van Rossum16aebf72002-11-22 11:43:10 +0000376 if self.symlink_exec and self.executable:
377 self.message("Symlinking executable %s to %s" % (self.executable,
378 self.execpath), 2)
379 dst = pathjoin(self.bundlepath, self.execpath)
380 makedirs(os.path.dirname(dst))
381 os.symlink(os.path.abspath(self.executable), dst)
382
Just van Rossum74bdca82002-11-28 11:30:56 +0000383 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000384 self.reportMissing()
385
386 def addPythonModules(self):
387 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000388
Just van Rossum109ecbf2003-01-02 13:13:01 +0000389 if USE_ZIPIMPORT:
390 # Create a zip file containing all modules as pyc.
391 import zipfile
392 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000393 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000394 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
395 for name, code, ispkg in self.pymodules:
396 self.message("Adding Python module %s" % name, 2)
397 path, pyc = getPycData(name, code, ispkg)
398 zf.writestr(path, pyc)
399 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000400 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000401 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
402 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000403 writePyc(SITE_CO, sitepath)
404 else:
405 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000406 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000407 if ispkg:
408 name += ".__init__"
409 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000410 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000411
412 if ispkg:
413 self.message("Adding Python package %s" % path, 2)
414 else:
415 self.message("Adding Python module %s" % path, 2)
416
417 abspath = pathjoin(self.bundlepath, path)
418 makedirs(os.path.dirname(abspath))
419 writePyc(code, abspath)
420
421 def stripBinaries(self):
422 if not os.path.exists(STRIP_EXEC):
423 self.message("Error: can't strip binaries: no strip program at "
424 "%s" % STRIP_EXEC, 0)
425 else:
426 self.message("Stripping binaries", 1)
427 for relpath in self.binaries:
428 self.message("Stripping %s" % relpath, 2)
429 abspath = pathjoin(self.bundlepath, relpath)
430 assert not os.path.islink(abspath)
431 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
432
433 def findDependencies(self):
434 self.message("Finding module dependencies", 1)
435 import modulefinder
436 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000437 if USE_ZIPIMPORT:
438 # zipimport imports zlib, must add it manually
439 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000440 # manually add our own site.py
441 site = mf.add_module("site")
442 site.__code__ = SITE_CO
443 mf.scan_code(SITE_CO, site)
444
445 includeModules = self.includeModules[:]
446 for name in self.includePackages:
447 includeModules.extend(findPackageContents(name).keys())
448 for name in includeModules:
449 try:
450 mf.import_hook(name)
451 except ImportError:
452 self.missingModules.append(name)
453
Just van Rossumcef32882002-11-26 00:34:52 +0000454 mf.run_script(self.mainprogram)
455 modules = mf.modules.items()
456 modules.sort()
457 for name, mod in modules:
458 if mod.__file__ and mod.__code__ is None:
459 # C extension
460 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000461 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000462 if USE_ZIPIMPORT:
463 # Python modules are stored in a Zip archive, but put
464 # extensions in Contents/Resources/.a and add a tiny "loader"
465 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000466 dstpath = pathjoin("Contents", "Resources", filename)
467 source = EXT_LOADER % {"name": name, "filename": filename}
468 code = compile(source, "<dynloader for %s>" % name, "exec")
469 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000470 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000471 # just copy the file
472 dstpath = name.split(".")[:-1] + [filename]
473 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000474 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000475 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000476 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000477 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000478 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000479 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000480 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000481 self.pymodules.append((name, mod.__code__, ispkg))
482
Just van Rossum74bdca82002-11-28 11:30:56 +0000483 if hasattr(mf, "any_missing_maybe"):
484 missing, maybe = mf.any_missing_maybe()
485 else:
486 missing = mf.any_missing()
487 maybe = []
488 self.missingModules.extend(missing)
489 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000490
491 def reportMissing(self):
492 missing = [name for name in self.missingModules
493 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000494 if self.maybeMissingModules:
495 maybe = self.maybeMissingModules
496 else:
497 maybe = [name for name in missing if "." in name]
498 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000499 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000500 maybe.sort()
501 if maybe:
502 self.message("Warning: couldn't find the following submodules:", 1)
503 self.message(" (Note that these could be false alarms -- "
504 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000505 self.message(" possible to distinguish between \"from package "
506 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000507 self.message(" and \"from package import name\")", 1)
508 for name in maybe:
509 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000510 if missing:
511 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000512 for name in missing:
513 self.message(" ? " + name, 1)
514
515 def report(self):
516 # XXX something decent
517 import pprint
518 pprint.pprint(self.__dict__)
519 if self.standalone:
520 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000521
522#
523# Utilities.
524#
525
526SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
527identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
528
529def findPackageContents(name, searchpath=None):
530 head = name.split(".")[-1]
531 if identifierRE.match(head) is None:
532 return {}
533 try:
534 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
535 except ImportError:
536 return {}
537 modules = {name: None}
538 if tp == imp.PKG_DIRECTORY and path:
539 files = os.listdir(path)
540 for sub in files:
541 sub, ext = os.path.splitext(sub)
542 fullname = name + "." + sub
543 if sub != "__init__" and fullname not in modules:
544 modules.update(findPackageContents(fullname, [path]))
545 return modules
546
547def writePyc(code, path):
548 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000549 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000550 f.write("\0" * 4) # don't bother about a time stamp
551 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000552 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000553
Just van Rossumad33d722002-11-21 10:23:04 +0000554def copy(src, dst, mkdirs=0):
555 """Copy a file or a directory."""
556 if mkdirs:
557 makedirs(os.path.dirname(dst))
558 if os.path.isdir(src):
559 shutil.copytree(src, dst)
560 else:
561 shutil.copy2(src, dst)
562
563def copytodir(src, dstdir):
564 """Copy a file or a directory to an existing directory."""
565 dst = pathjoin(dstdir, os.path.basename(src))
566 copy(src, dst)
567
568def makedirs(dir):
569 """Make all directories leading up to 'dir' including the leaf
570 directory. Don't moan if any path element already exists."""
571 try:
572 os.makedirs(dir)
573 except OSError, why:
574 if why.errno != errno.EEXIST:
575 raise
576
577def symlink(src, dst, mkdirs=0):
578 """Copy a file or a directory."""
579 if mkdirs:
580 makedirs(os.path.dirname(dst))
581 os.symlink(os.path.abspath(src), dst)
582
583def pathjoin(*args):
584 """Safe wrapper for os.path.join: asserts that all but the first
585 argument are relative paths."""
586 for seg in args[1:]:
587 assert seg[0] != "/"
588 return os.path.join(*args)
589
590
Just van Rossumceeb9622002-11-21 23:19:37 +0000591cmdline_doc = """\
592Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000593 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000594 python mybuildscript.py [options] command
595
596Commands:
597 build build the application
598 report print a report
599
600Options:
601 -b, --builddir=DIR the build directory; defaults to "build"
602 -n, --name=NAME application name
603 -r, --resource=FILE extra file or folder to be copied to Resources
604 -e, --executable=FILE the executable to be used
605 -m, --mainprogram=FILE the Python main program
606 -p, --plist=FILE .plist file (default: generate one)
607 --nib=NAME main nib name
608 -c, --creator=CCCC 4-char creator code (default: '????')
609 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000610 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000611 --standalone build a standalone application, which is fully
612 independent of a Python installation
613 -x, --exclude=MODULE exclude module (with --standalone)
614 -i, --include=MODULE include module (with --standalone)
615 --package=PACKAGE include a whole package (with --standalone)
616 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000617 -v, --verbose increase verbosity level
618 -q, --quiet decrease verbosity level
619 -h, --help print this message
620"""
621
622def usage(msg=None):
623 if msg:
624 print msg
625 print cmdline_doc
626 sys.exit(1)
627
628def main(builder=None):
629 if builder is None:
630 builder = AppBuilder(verbosity=1)
631
Just van Rossumcef32882002-11-26 00:34:52 +0000632 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000633 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000634 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000635 "link-exec", "help", "verbose", "quiet", "standalone",
636 "exclude=", "include=", "package=", "strip")
Just van Rossumceeb9622002-11-21 23:19:37 +0000637
638 try:
639 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
640 except getopt.error:
641 usage()
642
643 for opt, arg in options:
644 if opt in ('-b', '--builddir'):
645 builder.builddir = arg
646 elif opt in ('-n', '--name'):
647 builder.name = arg
648 elif opt in ('-r', '--resource'):
649 builder.resources.append(arg)
650 elif opt in ('-e', '--executable'):
651 builder.executable = arg
652 elif opt in ('-m', '--mainprogram'):
653 builder.mainprogram = arg
654 elif opt in ('-c', '--creator'):
655 builder.creator = arg
656 elif opt == "--nib":
657 builder.nibname = arg
658 elif opt in ('-p', '--plist'):
659 builder.plist = Plist.fromFile(arg)
660 elif opt in ('-l', '--link'):
661 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000662 elif opt == '--link-exec':
663 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000664 elif opt in ('-h', '--help'):
665 usage()
666 elif opt in ('-v', '--verbose'):
667 builder.verbosity += 1
668 elif opt in ('-q', '--quiet'):
669 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000670 elif opt == '--standalone':
671 builder.standalone = 1
672 elif opt in ('-x', '--exclude'):
673 builder.excludeModules.append(arg)
674 elif opt in ('-i', '--include'):
675 builder.includeModules.append(arg)
676 elif opt == '--package':
677 builder.includePackages.append(arg)
678 elif opt == '--strip':
679 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000680
681 if len(args) != 1:
682 usage("Must specify one command ('build', 'report' or 'help')")
683 command = args[0]
684
685 if command == "build":
686 builder.setup()
687 builder.build()
688 elif command == "report":
689 builder.setup()
690 builder.report()
691 elif command == "help":
692 usage()
693 else:
694 usage("Unknown command '%s'" % command)
695
696
Just van Rossumad33d722002-11-21 10:23:04 +0000697def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000698 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000699 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000700
701
702if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000703 main()