blob: a4811f19805cecec363a13ec2291ba1277f07cef [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()
210USE_FROZEN = hasattr(imp, "set_frozenmodules")
211
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
219if USE_FROZEN:
220 FROZEN_ARCHIVE = "FrozenModules.marshal"
221 SITE_PY += """\
222# bootstrapping
223import imp, marshal
224f = open(sys.path[0] + "/%s", "rb")
225imp.set_frozenmodules(marshal.load(f))
226f.close()
227""" % FROZEN_ARCHIVE
228
Just van Rossum74bdca82002-11-28 11:30:56 +0000229SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossumcef32882002-11-26 00:34:52 +0000230
Just van Rossum535ffa22002-11-29 20:06:52 +0000231EXT_LOADER = """\
232import imp, sys, os
233path = os.path.join(sys.path[0], "%(filename)s")
234mod = imp.load_dynamic("%(name)s", path)
235sys.modules["%(name)s"] = mod
236"""
237
Just van Rossumcef32882002-11-26 00:34:52 +0000238MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
239 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
240 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
241]
242
243STRIP_EXEC = "/usr/bin/strip"
244
Just van Rossum74bdca82002-11-28 11:30:56 +0000245BOOTSTRAP_SCRIPT = """\
246#!/bin/sh
Just van Rossumad33d722002-11-21 10:23:04 +0000247
Just van Rossum74bdca82002-11-28 11:30:56 +0000248execdir=$(dirname ${0})
249executable=${execdir}/%(executable)s
250resdir=$(dirname ${execdir})/Resources
251main=${resdir}/%(mainprogram)s
252PYTHONPATH=$resdir
253export PYTHONPATH
254exec ${executable} ${main} ${1}
Just van Rossumad33d722002-11-21 10:23:04 +0000255"""
256
Just van Rossumcef32882002-11-26 00:34:52 +0000257
Just van Rossumad33d722002-11-21 10:23:04 +0000258class AppBuilder(BundleBuilder):
259
Just van Rossumda302da2002-11-23 22:26:44 +0000260 # A Python main program. If this argument is given, the main
261 # executable in the bundle will be a small wrapper that invokes
262 # the main program. (XXX Discuss why.)
263 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000264
Just van Rossumda302da2002-11-23 22:26:44 +0000265 # The main executable. If a Python main program is specified
266 # the executable will be copied to Resources and be invoked
267 # by the wrapper program mentioned above. Otherwise it will
268 # simply be used as the main executable.
269 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000270
Just van Rossumda302da2002-11-23 22:26:44 +0000271 # The name of the main nib, for Cocoa apps. *Must* be specified
272 # when building a Cocoa app.
273 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000274
Just van Rossumda302da2002-11-23 22:26:44 +0000275 # Symlink the executable instead of copying it.
276 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000277
Just van Rossumcef32882002-11-26 00:34:52 +0000278 # If True, build standalone app.
279 standalone = 0
280
281 # The following attributes are only used when building a standalone app.
282
283 # Exclude these modules.
284 excludeModules = []
285
286 # Include these modules.
287 includeModules = []
288
289 # Include these packages.
290 includePackages = []
291
292 # Strip binaries.
293 strip = 0
294
Just van Rossumcef32882002-11-26 00:34:52 +0000295 # Found Python modules: [(name, codeobject, ispkg), ...]
296 pymodules = []
297
298 # Modules that modulefinder couldn't find:
299 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000300 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000301
302 # List of all binaries (executables or shared libs), for stripping purposes
303 binaries = []
304
Just van Rossumceeb9622002-11-21 23:19:37 +0000305 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000306 if self.standalone and self.mainprogram is None:
307 raise BundleBuilderError, ("must specify 'mainprogram' when "
308 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000309 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000310 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000311 "'executable' and 'mainprogram'")
312
313 if self.name is not None:
314 pass
315 elif self.mainprogram is not None:
316 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
317 elif executable is not None:
318 self.name = os.path.splitext(os.path.basename(self.executable))[0]
319 if self.name[-4:] != ".app":
320 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000321
Just van Rossum74bdca82002-11-28 11:30:56 +0000322 if self.executable is None:
323 if not self.standalone:
324 self.symlink_exec = 1
325 self.executable = sys.executable
326
Just van Rossumceeb9622002-11-21 23:19:37 +0000327 if self.nibname:
328 self.plist.NSMainNibFile = self.nibname
329 if not hasattr(self.plist, "NSPrincipalClass"):
330 self.plist.NSPrincipalClass = "NSApplication"
331
332 BundleBuilder.setup(self)
333
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000334 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000335
Just van Rossumcef32882002-11-26 00:34:52 +0000336 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000337 self.findDependencies()
338
Just van Rossumf7aba232002-11-22 00:31:50 +0000339 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000340 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000341 if self.executable is not None:
342 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000343 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000344 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000345 execname = os.path.basename(self.executable)
346 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000347 if not self.symlink_exec:
348 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000349 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000350 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000351
352 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000353 mainprogram = os.path.basename(self.mainprogram)
354 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
355 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000356 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000357 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000358 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000359 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000360 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
361 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000362
Just van Rossum16aebf72002-11-22 11:43:10 +0000363 def postProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000364 self.addPythonModules()
365 if self.strip and not self.symlink:
366 self.stripBinaries()
367
Just van Rossum16aebf72002-11-22 11:43:10 +0000368 if self.symlink_exec and self.executable:
369 self.message("Symlinking executable %s to %s" % (self.executable,
370 self.execpath), 2)
371 dst = pathjoin(self.bundlepath, self.execpath)
372 makedirs(os.path.dirname(dst))
373 os.symlink(os.path.abspath(self.executable), dst)
374
Just van Rossum74bdca82002-11-28 11:30:56 +0000375 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000376 self.reportMissing()
377
378 def addPythonModules(self):
379 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000380
381 if USE_FROZEN:
382 # This anticipates the acceptance of this patch:
383 # http://www.python.org/sf/642578
384 # Create a file containing all modules, frozen.
385 frozenmodules = []
Just van Rossum535ffa22002-11-29 20:06:52 +0000386 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000387 if ispkg:
388 self.message("Adding Python package %s" % name, 2)
389 else:
390 self.message("Adding Python module %s" % name, 2)
391 frozenmodules.append((name, marshal.dumps(code), ispkg))
392 frozenmodules = tuple(frozenmodules)
Just van Rossum535ffa22002-11-29 20:06:52 +0000393 relpath = pathjoin("Contents", "Resources", FROZEN_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000394 abspath = pathjoin(self.bundlepath, relpath)
395 f = open(abspath, "wb")
396 marshal.dump(frozenmodules, f)
397 f.close()
398 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000399 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
400 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000401 writePyc(SITE_CO, sitepath)
402 else:
403 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000404 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000405 if ispkg:
406 name += ".__init__"
407 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000408 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000409
410 if ispkg:
411 self.message("Adding Python package %s" % path, 2)
412 else:
413 self.message("Adding Python module %s" % path, 2)
414
415 abspath = pathjoin(self.bundlepath, path)
416 makedirs(os.path.dirname(abspath))
417 writePyc(code, abspath)
418
419 def stripBinaries(self):
420 if not os.path.exists(STRIP_EXEC):
421 self.message("Error: can't strip binaries: no strip program at "
422 "%s" % STRIP_EXEC, 0)
423 else:
424 self.message("Stripping binaries", 1)
425 for relpath in self.binaries:
426 self.message("Stripping %s" % relpath, 2)
427 abspath = pathjoin(self.bundlepath, relpath)
428 assert not os.path.islink(abspath)
429 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
430
431 def findDependencies(self):
432 self.message("Finding module dependencies", 1)
433 import modulefinder
434 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
435 # manually add our own site.py
436 site = mf.add_module("site")
437 site.__code__ = SITE_CO
438 mf.scan_code(SITE_CO, site)
439
440 includeModules = self.includeModules[:]
441 for name in self.includePackages:
442 includeModules.extend(findPackageContents(name).keys())
443 for name in includeModules:
444 try:
445 mf.import_hook(name)
446 except ImportError:
447 self.missingModules.append(name)
448
Just van Rossumcef32882002-11-26 00:34:52 +0000449 mf.run_script(self.mainprogram)
450 modules = mf.modules.items()
451 modules.sort()
452 for name, mod in modules:
453 if mod.__file__ and mod.__code__ is None:
454 # C extension
455 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000456 filename = os.path.basename(path)
457 if USE_FROZEN:
458 # "proper" freezing, put extensions in Contents/Resources/,
459 # freeze a tiny "loader" program. Due to Thomas Heller.
460 dstpath = pathjoin("Contents", "Resources", filename)
461 source = EXT_LOADER % {"name": name, "filename": filename}
462 code = compile(source, "<dynloader for %s>" % name, "exec")
463 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000464 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000465 # just copy the file
466 dstpath = name.split(".")[:-1] + [filename]
467 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000468 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000469 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000470 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000471 ispkg = mod.__path__ is not None
472 if not USE_FROZEN or name != "site":
473 # Our site.py is doing the bootstrapping, so we must
474 # include a real .pyc file if USE_FROZEN is True.
475 self.pymodules.append((name, mod.__code__, ispkg))
476
Just van Rossum74bdca82002-11-28 11:30:56 +0000477 if hasattr(mf, "any_missing_maybe"):
478 missing, maybe = mf.any_missing_maybe()
479 else:
480 missing = mf.any_missing()
481 maybe = []
482 self.missingModules.extend(missing)
483 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000484
485 def reportMissing(self):
486 missing = [name for name in self.missingModules
487 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000488 if self.maybeMissingModules:
489 maybe = self.maybeMissingModules
490 else:
491 maybe = [name for name in missing if "." in name]
492 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000493 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000494 maybe.sort()
495 if maybe:
496 self.message("Warning: couldn't find the following submodules:", 1)
497 self.message(" (Note that these could be false alarms -- "
498 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000499 self.message(" possible to distinguish between \"from package "
500 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000501 self.message(" and \"from package import name\")", 1)
502 for name in maybe:
503 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000504 if missing:
505 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000506 for name in missing:
507 self.message(" ? " + name, 1)
508
509 def report(self):
510 # XXX something decent
511 import pprint
512 pprint.pprint(self.__dict__)
513 if self.standalone:
514 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000515
516#
517# Utilities.
518#
519
520SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
521identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
522
523def findPackageContents(name, searchpath=None):
524 head = name.split(".")[-1]
525 if identifierRE.match(head) is None:
526 return {}
527 try:
528 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
529 except ImportError:
530 return {}
531 modules = {name: None}
532 if tp == imp.PKG_DIRECTORY and path:
533 files = os.listdir(path)
534 for sub in files:
535 sub, ext = os.path.splitext(sub)
536 fullname = name + "." + sub
537 if sub != "__init__" and fullname not in modules:
538 modules.update(findPackageContents(fullname, [path]))
539 return modules
540
541def writePyc(code, path):
542 f = open(path, "wb")
543 f.write("\0" * 8) # don't bother about a time stamp
544 marshal.dump(code, f)
545 f.seek(0, 0)
546 f.write(MAGIC)
547 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000548
Just van Rossumad33d722002-11-21 10:23:04 +0000549def copy(src, dst, mkdirs=0):
550 """Copy a file or a directory."""
551 if mkdirs:
552 makedirs(os.path.dirname(dst))
553 if os.path.isdir(src):
554 shutil.copytree(src, dst)
555 else:
556 shutil.copy2(src, dst)
557
558def copytodir(src, dstdir):
559 """Copy a file or a directory to an existing directory."""
560 dst = pathjoin(dstdir, os.path.basename(src))
561 copy(src, dst)
562
563def makedirs(dir):
564 """Make all directories leading up to 'dir' including the leaf
565 directory. Don't moan if any path element already exists."""
566 try:
567 os.makedirs(dir)
568 except OSError, why:
569 if why.errno != errno.EEXIST:
570 raise
571
572def symlink(src, dst, mkdirs=0):
573 """Copy a file or a directory."""
574 if mkdirs:
575 makedirs(os.path.dirname(dst))
576 os.symlink(os.path.abspath(src), dst)
577
578def pathjoin(*args):
579 """Safe wrapper for os.path.join: asserts that all but the first
580 argument are relative paths."""
581 for seg in args[1:]:
582 assert seg[0] != "/"
583 return os.path.join(*args)
584
585
Just van Rossumceeb9622002-11-21 23:19:37 +0000586cmdline_doc = """\
587Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000588 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000589 python mybuildscript.py [options] command
590
591Commands:
592 build build the application
593 report print a report
594
595Options:
596 -b, --builddir=DIR the build directory; defaults to "build"
597 -n, --name=NAME application name
598 -r, --resource=FILE extra file or folder to be copied to Resources
599 -e, --executable=FILE the executable to be used
600 -m, --mainprogram=FILE the Python main program
601 -p, --plist=FILE .plist file (default: generate one)
602 --nib=NAME main nib name
603 -c, --creator=CCCC 4-char creator code (default: '????')
604 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000605 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000606 --standalone build a standalone application, which is fully
607 independent of a Python installation
608 -x, --exclude=MODULE exclude module (with --standalone)
609 -i, --include=MODULE include module (with --standalone)
610 --package=PACKAGE include a whole package (with --standalone)
611 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000612 -v, --verbose increase verbosity level
613 -q, --quiet decrease verbosity level
614 -h, --help print this message
615"""
616
617def usage(msg=None):
618 if msg:
619 print msg
620 print cmdline_doc
621 sys.exit(1)
622
623def main(builder=None):
624 if builder is None:
625 builder = AppBuilder(verbosity=1)
626
Just van Rossumcef32882002-11-26 00:34:52 +0000627 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000628 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000629 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000630 "link-exec", "help", "verbose", "quiet", "standalone",
631 "exclude=", "include=", "package=", "strip")
Just van Rossumceeb9622002-11-21 23:19:37 +0000632
633 try:
634 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
635 except getopt.error:
636 usage()
637
638 for opt, arg in options:
639 if opt in ('-b', '--builddir'):
640 builder.builddir = arg
641 elif opt in ('-n', '--name'):
642 builder.name = arg
643 elif opt in ('-r', '--resource'):
644 builder.resources.append(arg)
645 elif opt in ('-e', '--executable'):
646 builder.executable = arg
647 elif opt in ('-m', '--mainprogram'):
648 builder.mainprogram = arg
649 elif opt in ('-c', '--creator'):
650 builder.creator = arg
651 elif opt == "--nib":
652 builder.nibname = arg
653 elif opt in ('-p', '--plist'):
654 builder.plist = Plist.fromFile(arg)
655 elif opt in ('-l', '--link'):
656 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000657 elif opt == '--link-exec':
658 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000659 elif opt in ('-h', '--help'):
660 usage()
661 elif opt in ('-v', '--verbose'):
662 builder.verbosity += 1
663 elif opt in ('-q', '--quiet'):
664 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000665 elif opt == '--standalone':
666 builder.standalone = 1
667 elif opt in ('-x', '--exclude'):
668 builder.excludeModules.append(arg)
669 elif opt in ('-i', '--include'):
670 builder.includeModules.append(arg)
671 elif opt == '--package':
672 builder.includePackages.append(arg)
673 elif opt == '--strip':
674 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000675
676 if len(args) != 1:
677 usage("Must specify one command ('build', 'report' or 'help')")
678 command = args[0]
679
680 if command == "build":
681 builder.setup()
682 builder.build()
683 elif command == "report":
684 builder.setup()
685 builder.report()
686 elif command == "help":
687 usage()
688 else:
689 usage("Unknown command '%s'" % command)
690
691
Just van Rossumad33d722002-11-21 10:23:04 +0000692def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000693 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000694 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000695
696
697if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000698 main()