blob: 0bef268bf7461835aa1baf1ae7bbf47e5cf70db5 [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()
144
145 def preProcess(self):
146 """Hook for subclasses."""
147 pass
148 def postProcess(self):
149 """Hook for subclasses."""
150 pass
151
152 def _addMetaFiles(self):
153 contents = pathjoin(self.bundlepath, "Contents")
154 makedirs(contents)
155 #
156 # Write Contents/PkgInfo
157 assert len(self.type) == len(self.creator) == 4, \
158 "type and creator must be 4-byte strings."
159 pkginfo = pathjoin(contents, "PkgInfo")
160 f = open(pkginfo, "wb")
161 f.write(self.type + self.creator)
162 f.close()
163 #
164 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000165 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000166 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000167
168 def _copyFiles(self):
169 files = self.files[:]
170 for path in self.resources:
171 files.append((path, pathjoin("Contents", "Resources",
172 os.path.basename(path))))
173 if self.symlink:
174 self.message("Making symbolic links", 1)
175 msg = "Making symlink from"
176 else:
177 self.message("Copying files", 1)
178 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000179 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000180 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000181 if os.path.isdir(src):
182 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
183 else:
184 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000185 dst = pathjoin(self.bundlepath, dst)
186 if self.symlink:
187 symlink(src, dst, mkdirs=1)
188 else:
189 copy(src, dst, mkdirs=1)
190
191 def message(self, msg, level=0):
192 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000193 indent = ""
194 if level > 1:
195 indent = (level - 1) * " "
196 sys.stderr.write(indent + msg + "\n")
197
198 def report(self):
199 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000200 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000201
202
Just van Rossumcef32882002-11-26 00:34:52 +0000203
204if __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
231MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
232 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
233 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
234]
235
236STRIP_EXEC = "/usr/bin/strip"
237
Just van Rossum74bdca82002-11-28 11:30:56 +0000238BOOTSTRAP_SCRIPT = """\
239#!/bin/sh
Just van Rossumad33d722002-11-21 10:23:04 +0000240
Just van Rossum74bdca82002-11-28 11:30:56 +0000241execdir=$(dirname ${0})
242executable=${execdir}/%(executable)s
243resdir=$(dirname ${execdir})/Resources
244main=${resdir}/%(mainprogram)s
245PYTHONPATH=$resdir
246export PYTHONPATH
247exec ${executable} ${main} ${1}
Just van Rossumad33d722002-11-21 10:23:04 +0000248"""
249
Just van Rossumcef32882002-11-26 00:34:52 +0000250
Just van Rossumad33d722002-11-21 10:23:04 +0000251class AppBuilder(BundleBuilder):
252
Just van Rossumda302da2002-11-23 22:26:44 +0000253 # A Python main program. If this argument is given, the main
254 # executable in the bundle will be a small wrapper that invokes
255 # the main program. (XXX Discuss why.)
256 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000257
Just van Rossumda302da2002-11-23 22:26:44 +0000258 # The main executable. If a Python main program is specified
259 # the executable will be copied to Resources and be invoked
260 # by the wrapper program mentioned above. Otherwise it will
261 # simply be used as the main executable.
262 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000263
Just van Rossumda302da2002-11-23 22:26:44 +0000264 # The name of the main nib, for Cocoa apps. *Must* be specified
265 # when building a Cocoa app.
266 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000267
Just van Rossumda302da2002-11-23 22:26:44 +0000268 # Symlink the executable instead of copying it.
269 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000270
Just van Rossumcef32882002-11-26 00:34:52 +0000271 # If True, build standalone app.
272 standalone = 0
273
274 # The following attributes are only used when building a standalone app.
275
276 # Exclude these modules.
277 excludeModules = []
278
279 # Include these modules.
280 includeModules = []
281
282 # Include these packages.
283 includePackages = []
284
285 # Strip binaries.
286 strip = 0
287
288 # Found C extension modules: [(name, path), ...]
289 extensions = []
290
291 # Found Python modules: [(name, codeobject, ispkg), ...]
292 pymodules = []
293
294 # Modules that modulefinder couldn't find:
295 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000296 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000297
298 # List of all binaries (executables or shared libs), for stripping purposes
299 binaries = []
300
Just van Rossumceeb9622002-11-21 23:19:37 +0000301 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000302 if self.standalone and self.mainprogram is None:
303 raise BundleBuilderError, ("must specify 'mainprogram' when "
304 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000305 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000306 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000307 "'executable' and 'mainprogram'")
308
309 if self.name is not None:
310 pass
311 elif self.mainprogram is not None:
312 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
313 elif executable is not None:
314 self.name = os.path.splitext(os.path.basename(self.executable))[0]
315 if self.name[-4:] != ".app":
316 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000317
Just van Rossum74bdca82002-11-28 11:30:56 +0000318 if self.executable is None:
319 if not self.standalone:
320 self.symlink_exec = 1
321 self.executable = sys.executable
322
Just van Rossumceeb9622002-11-21 23:19:37 +0000323 if self.nibname:
324 self.plist.NSMainNibFile = self.nibname
325 if not hasattr(self.plist, "NSPrincipalClass"):
326 self.plist.NSPrincipalClass = "NSApplication"
327
328 BundleBuilder.setup(self)
329
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000330 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000331
Just van Rossumcef32882002-11-26 00:34:52 +0000332 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000333 self.findDependencies()
334
Just van Rossumf7aba232002-11-22 00:31:50 +0000335 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000336 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000337 if self.executable is not None:
338 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000339 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000340 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000341 execname = os.path.basename(self.executable)
342 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000343 if not self.symlink_exec:
344 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000345 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000346 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000347
348 if self.mainprogram is not None:
349 mainname = os.path.basename(self.mainprogram)
Just van Rossumceeb9622002-11-21 23:19:37 +0000350 self.files.append((self.mainprogram, pathjoin(resdir, mainname)))
Just van Rossumad33d722002-11-21 10:23:04 +0000351 # Create execve wrapper
352 mainprogram = self.mainprogram # XXX for locals() call
Just van Rossum74bdca82002-11-28 11:30:56 +0000353 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000354 execdir = pathjoin(self.bundlepath, self.execdir)
355 mainwrapperpath = pathjoin(execdir, self.name)
356 makedirs(execdir)
Just van Rossum74bdca82002-11-28 11:30:56 +0000357 open(mainwrapperpath, "w").write(BOOTSTRAP_SCRIPT % locals())
Just van Rossumad33d722002-11-21 10:23:04 +0000358 os.chmod(mainwrapperpath, 0777)
359
Just van Rossum16aebf72002-11-22 11:43:10 +0000360 def postProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000361 self.addPythonModules()
362 if self.strip and not self.symlink:
363 self.stripBinaries()
364
Just van Rossum16aebf72002-11-22 11:43:10 +0000365 if self.symlink_exec and self.executable:
366 self.message("Symlinking executable %s to %s" % (self.executable,
367 self.execpath), 2)
368 dst = pathjoin(self.bundlepath, self.execpath)
369 makedirs(os.path.dirname(dst))
370 os.symlink(os.path.abspath(self.executable), dst)
371
Just van Rossum74bdca82002-11-28 11:30:56 +0000372 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000373 self.reportMissing()
374
375 def addPythonModules(self):
376 self.message("Adding Python modules", 1)
377 pymodules = self.pymodules
378
379 if USE_FROZEN:
380 # This anticipates the acceptance of this patch:
381 # http://www.python.org/sf/642578
382 # Create a file containing all modules, frozen.
383 frozenmodules = []
384 for name, code, ispkg in pymodules:
385 if ispkg:
386 self.message("Adding Python package %s" % name, 2)
387 else:
388 self.message("Adding Python module %s" % name, 2)
389 frozenmodules.append((name, marshal.dumps(code), ispkg))
390 frozenmodules = tuple(frozenmodules)
391 relpath = "Contents/Resources/" + FROZEN_ARCHIVE
392 abspath = pathjoin(self.bundlepath, relpath)
393 f = open(abspath, "wb")
394 marshal.dump(frozenmodules, f)
395 f.close()
396 # add site.pyc
397 sitepath = pathjoin(self.bundlepath, "Contents/Resources/site" + PYC_EXT)
398 writePyc(SITE_CO, sitepath)
399 else:
400 # Create individual .pyc files.
401 for name, code, ispkg in pymodules:
402 if ispkg:
403 name += ".__init__"
404 path = name.split(".")
405 path = pathjoin("Contents/Resources/", *path) + PYC_EXT
406
407 if ispkg:
408 self.message("Adding Python package %s" % path, 2)
409 else:
410 self.message("Adding Python module %s" % path, 2)
411
412 abspath = pathjoin(self.bundlepath, path)
413 makedirs(os.path.dirname(abspath))
414 writePyc(code, abspath)
415
416 def stripBinaries(self):
417 if not os.path.exists(STRIP_EXEC):
418 self.message("Error: can't strip binaries: no strip program at "
419 "%s" % STRIP_EXEC, 0)
420 else:
421 self.message("Stripping binaries", 1)
422 for relpath in self.binaries:
423 self.message("Stripping %s" % relpath, 2)
424 abspath = pathjoin(self.bundlepath, relpath)
425 assert not os.path.islink(abspath)
426 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
427
428 def findDependencies(self):
429 self.message("Finding module dependencies", 1)
430 import modulefinder
431 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
432 # manually add our own site.py
433 site = mf.add_module("site")
434 site.__code__ = SITE_CO
435 mf.scan_code(SITE_CO, site)
436
437 includeModules = self.includeModules[:]
438 for name in self.includePackages:
439 includeModules.extend(findPackageContents(name).keys())
440 for name in includeModules:
441 try:
442 mf.import_hook(name)
443 except ImportError:
444 self.missingModules.append(name)
445
446
447 mf.run_script(self.mainprogram)
448 modules = mf.modules.items()
449 modules.sort()
450 for name, mod in modules:
451 if mod.__file__ and mod.__code__ is None:
452 # C extension
453 path = mod.__file__
454 ext = os.path.splitext(path)[1]
455 if USE_FROZEN: # "proper" freezing
456 # rename extensions that are submodules of packages to
457 # <packagename>.<modulename>.<ext>
458 dstpath = "Contents/Resources/" + name + ext
459 else:
460 dstpath = name.split(".")
461 dstpath = pathjoin("Contents/Resources/", *dstpath) + ext
462 self.files.append((path, dstpath))
463 self.extensions.append((name, path, dstpath))
464 self.binaries.append(dstpath)
465 elif mod.__code__ is not None:
466 ispkg = mod.__path__ is not None
467 if not USE_FROZEN or name != "site":
468 # Our site.py is doing the bootstrapping, so we must
469 # include a real .pyc file if USE_FROZEN is True.
470 self.pymodules.append((name, mod.__code__, ispkg))
471
Just van Rossum74bdca82002-11-28 11:30:56 +0000472 if hasattr(mf, "any_missing_maybe"):
473 missing, maybe = mf.any_missing_maybe()
474 else:
475 missing = mf.any_missing()
476 maybe = []
477 self.missingModules.extend(missing)
478 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000479
480 def reportMissing(self):
481 missing = [name for name in self.missingModules
482 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000483 if self.maybeMissingModules:
484 maybe = self.maybeMissingModules
485 else:
486 maybe = [name for name in missing if "." in name]
487 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000488 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000489 maybe.sort()
490 if maybe:
491 self.message("Warning: couldn't find the following submodules:", 1)
492 self.message(" (Note that these could be false alarms -- "
493 "it's not always", 1)
494 self.message(" possible to distinguish between from \"package import submodule\" ", 1)
495 self.message(" and \"from package import name\")", 1)
496 for name in maybe:
497 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000498 if missing:
499 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000500 for name in missing:
501 self.message(" ? " + name, 1)
502
503 def report(self):
504 # XXX something decent
505 import pprint
506 pprint.pprint(self.__dict__)
507 if self.standalone:
508 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000509
510#
511# Utilities.
512#
513
514SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
515identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
516
517def findPackageContents(name, searchpath=None):
518 head = name.split(".")[-1]
519 if identifierRE.match(head) is None:
520 return {}
521 try:
522 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
523 except ImportError:
524 return {}
525 modules = {name: None}
526 if tp == imp.PKG_DIRECTORY and path:
527 files = os.listdir(path)
528 for sub in files:
529 sub, ext = os.path.splitext(sub)
530 fullname = name + "." + sub
531 if sub != "__init__" and fullname not in modules:
532 modules.update(findPackageContents(fullname, [path]))
533 return modules
534
535def writePyc(code, path):
536 f = open(path, "wb")
537 f.write("\0" * 8) # don't bother about a time stamp
538 marshal.dump(code, f)
539 f.seek(0, 0)
540 f.write(MAGIC)
541 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000542
Just van Rossumad33d722002-11-21 10:23:04 +0000543def copy(src, dst, mkdirs=0):
544 """Copy a file or a directory."""
545 if mkdirs:
546 makedirs(os.path.dirname(dst))
547 if os.path.isdir(src):
548 shutil.copytree(src, dst)
549 else:
550 shutil.copy2(src, dst)
551
552def copytodir(src, dstdir):
553 """Copy a file or a directory to an existing directory."""
554 dst = pathjoin(dstdir, os.path.basename(src))
555 copy(src, dst)
556
557def makedirs(dir):
558 """Make all directories leading up to 'dir' including the leaf
559 directory. Don't moan if any path element already exists."""
560 try:
561 os.makedirs(dir)
562 except OSError, why:
563 if why.errno != errno.EEXIST:
564 raise
565
566def symlink(src, dst, mkdirs=0):
567 """Copy a file or a directory."""
568 if mkdirs:
569 makedirs(os.path.dirname(dst))
570 os.symlink(os.path.abspath(src), dst)
571
572def pathjoin(*args):
573 """Safe wrapper for os.path.join: asserts that all but the first
574 argument are relative paths."""
575 for seg in args[1:]:
576 assert seg[0] != "/"
577 return os.path.join(*args)
578
579
Just van Rossumceeb9622002-11-21 23:19:37 +0000580cmdline_doc = """\
581Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000582 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000583 python mybuildscript.py [options] command
584
585Commands:
586 build build the application
587 report print a report
588
589Options:
590 -b, --builddir=DIR the build directory; defaults to "build"
591 -n, --name=NAME application name
592 -r, --resource=FILE extra file or folder to be copied to Resources
593 -e, --executable=FILE the executable to be used
594 -m, --mainprogram=FILE the Python main program
595 -p, --plist=FILE .plist file (default: generate one)
596 --nib=NAME main nib name
597 -c, --creator=CCCC 4-char creator code (default: '????')
598 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000599 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000600 --standalone build a standalone application, which is fully
601 independent of a Python installation
602 -x, --exclude=MODULE exclude module (with --standalone)
603 -i, --include=MODULE include module (with --standalone)
604 --package=PACKAGE include a whole package (with --standalone)
605 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000606 -v, --verbose increase verbosity level
607 -q, --quiet decrease verbosity level
608 -h, --help print this message
609"""
610
611def usage(msg=None):
612 if msg:
613 print msg
614 print cmdline_doc
615 sys.exit(1)
616
617def main(builder=None):
618 if builder is None:
619 builder = AppBuilder(verbosity=1)
620
Just van Rossumcef32882002-11-26 00:34:52 +0000621 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000622 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000623 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000624 "link-exec", "help", "verbose", "quiet", "standalone",
625 "exclude=", "include=", "package=", "strip")
Just van Rossumceeb9622002-11-21 23:19:37 +0000626
627 try:
628 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
629 except getopt.error:
630 usage()
631
632 for opt, arg in options:
633 if opt in ('-b', '--builddir'):
634 builder.builddir = arg
635 elif opt in ('-n', '--name'):
636 builder.name = arg
637 elif opt in ('-r', '--resource'):
638 builder.resources.append(arg)
639 elif opt in ('-e', '--executable'):
640 builder.executable = arg
641 elif opt in ('-m', '--mainprogram'):
642 builder.mainprogram = arg
643 elif opt in ('-c', '--creator'):
644 builder.creator = arg
645 elif opt == "--nib":
646 builder.nibname = arg
647 elif opt in ('-p', '--plist'):
648 builder.plist = Plist.fromFile(arg)
649 elif opt in ('-l', '--link'):
650 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000651 elif opt == '--link-exec':
652 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000653 elif opt in ('-h', '--help'):
654 usage()
655 elif opt in ('-v', '--verbose'):
656 builder.verbosity += 1
657 elif opt in ('-q', '--quiet'):
658 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000659 elif opt == '--standalone':
660 builder.standalone = 1
661 elif opt in ('-x', '--exclude'):
662 builder.excludeModules.append(arg)
663 elif opt in ('-i', '--include'):
664 builder.includeModules.append(arg)
665 elif opt == '--package':
666 builder.includePackages.append(arg)
667 elif opt == '--strip':
668 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000669
670 if len(args) != 1:
671 usage("Must specify one command ('build', 'report' or 'help')")
672 command = args[0]
673
674 if command == "build":
675 builder.setup()
676 builder.build()
677 elif command == "report":
678 builder.setup()
679 builder.report()
680 elif command == "help":
681 usage()
682 else:
683 usage("Unknown command '%s'" % command)
684
685
Just van Rossumad33d722002-11-21 10:23:04 +0000686def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000687 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000688 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000689
690
691if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000692 main()