blob: 96e364a706134f7c9b1e7a3d30ee089c34482900 [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
200 import pprint
201 pprint.pprint(self.__dict__)
Just van Rossumad33d722002-11-21 10:23:04 +0000202
203
Just van Rossumcef32882002-11-26 00:34:52 +0000204
205if __debug__:
206 PYC_EXT = ".pyc"
207else:
208 PYC_EXT = ".pyo"
209
210MAGIC = imp.get_magic()
211USE_FROZEN = hasattr(imp, "set_frozenmodules")
212
213# For standalone apps, we have our own minimal site.py. We don't need
214# all the cruft of the real site.py.
215SITE_PY = """\
216import sys
217del sys.path[1:] # sys.path[0] is Contents/Resources/
218"""
219
220if USE_FROZEN:
221 FROZEN_ARCHIVE = "FrozenModules.marshal"
222 SITE_PY += """\
223# bootstrapping
224import imp, marshal
225f = open(sys.path[0] + "/%s", "rb")
226imp.set_frozenmodules(marshal.load(f))
227f.close()
228""" % FROZEN_ARCHIVE
229
230SITE_CO = compile(SITE_PY, "<-bundlebuilder->", "exec")
231
232MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
233 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
234 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
235]
236
237STRIP_EXEC = "/usr/bin/strip"
238
239EXECVE_WRAPPER = """\
Just van Rossumad33d722002-11-21 10:23:04 +0000240#!/usr/bin/env python
241
242import os
243from sys import argv, executable
244resources = os.path.join(os.path.dirname(os.path.dirname(argv[0])),
245 "Resources")
246mainprogram = os.path.join(resources, "%(mainprogram)s")
247assert os.path.exists(mainprogram)
248argv.insert(1, mainprogram)
Just van Rossumceeb9622002-11-21 23:19:37 +0000249os.environ["PYTHONPATH"] = resources
Just van Rossumceeb9622002-11-21 23:19:37 +0000250%(setexecutable)s
Just van Rossumad33d722002-11-21 10:23:04 +0000251os.execve(executable, argv, os.environ)
252"""
253
Just van Rossumceeb9622002-11-21 23:19:37 +0000254setExecutableTemplate = """executable = os.path.join(resources, "%s")"""
255pythonhomeSnippet = """os.environ["home"] = resources"""
Just van Rossumad33d722002-11-21 10:23:04 +0000256
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
295 # Found C extension modules: [(name, path), ...]
296 extensions = []
297
298 # Found Python modules: [(name, codeobject, ispkg), ...]
299 pymodules = []
300
301 # Modules that modulefinder couldn't find:
302 missingModules = []
303
304 # List of all binaries (executables or shared libs), for stripping purposes
305 binaries = []
306
Just van Rossumceeb9622002-11-21 23:19:37 +0000307 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000308 if self.standalone and self.mainprogram is None:
309 raise BundleBuilderError, ("must specify 'mainprogram' when "
310 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000311 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000312 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000313 "'executable' and 'mainprogram'")
314
315 if self.name is not None:
316 pass
317 elif self.mainprogram is not None:
318 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
319 elif executable is not None:
320 self.name = os.path.splitext(os.path.basename(self.executable))[0]
321 if self.name[-4:] != ".app":
322 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000323
324 if self.nibname:
325 self.plist.NSMainNibFile = self.nibname
326 if not hasattr(self.plist, "NSPrincipalClass"):
327 self.plist.NSPrincipalClass = "NSApplication"
328
329 BundleBuilder.setup(self)
330
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000331 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000332
Just van Rossumcef32882002-11-26 00:34:52 +0000333 if self.standalone:
334 if self.executable is None: # *assert* that it is None?
335 self.executable = sys.executable
336 self.findDependencies()
337
Just van Rossumf7aba232002-11-22 00:31:50 +0000338 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000339 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000340 if self.executable is not None:
341 if self.mainprogram is None:
342 execpath = pathjoin(self.execdir, self.name)
343 else:
Just van Rossumceeb9622002-11-21 23:19:37 +0000344 execpath = pathjoin(resdir, os.path.basename(self.executable))
Just van Rossum16aebf72002-11-22 11:43:10 +0000345 if not self.symlink_exec:
346 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000347 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000348 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000349 # For execve wrapper
Just van Rossumceeb9622002-11-21 23:19:37 +0000350 setexecutable = setExecutableTemplate % os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000351 else:
Just van Rossumceeb9622002-11-21 23:19:37 +0000352 setexecutable = "" # XXX for locals() call
Just van Rossumad33d722002-11-21 10:23:04 +0000353
354 if self.mainprogram is not None:
355 mainname = os.path.basename(self.mainprogram)
Just van Rossumceeb9622002-11-21 23:19:37 +0000356 self.files.append((self.mainprogram, pathjoin(resdir, mainname)))
Just van Rossumad33d722002-11-21 10:23:04 +0000357 # Create execve wrapper
358 mainprogram = self.mainprogram # XXX for locals() call
359 execdir = pathjoin(self.bundlepath, self.execdir)
360 mainwrapperpath = pathjoin(execdir, self.name)
361 makedirs(execdir)
Just van Rossumcef32882002-11-26 00:34:52 +0000362 open(mainwrapperpath, "w").write(EXECVE_WRAPPER % locals())
Just van Rossumad33d722002-11-21 10:23:04 +0000363 os.chmod(mainwrapperpath, 0777)
364
Just van Rossum16aebf72002-11-22 11:43:10 +0000365 def postProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000366 self.addPythonModules()
367 if self.strip and not self.symlink:
368 self.stripBinaries()
369
Just van Rossum16aebf72002-11-22 11:43:10 +0000370 if self.symlink_exec and self.executable:
371 self.message("Symlinking executable %s to %s" % (self.executable,
372 self.execpath), 2)
373 dst = pathjoin(self.bundlepath, self.execpath)
374 makedirs(os.path.dirname(dst))
375 os.symlink(os.path.abspath(self.executable), dst)
376
Just van Rossumcef32882002-11-26 00:34:52 +0000377 if self.missingModules:
378 self.reportMissing()
379
380 def addPythonModules(self):
381 self.message("Adding Python modules", 1)
382 pymodules = self.pymodules
383
384 if USE_FROZEN:
385 # This anticipates the acceptance of this patch:
386 # http://www.python.org/sf/642578
387 # Create a file containing all modules, frozen.
388 frozenmodules = []
389 for name, code, ispkg in pymodules:
390 if ispkg:
391 self.message("Adding Python package %s" % name, 2)
392 else:
393 self.message("Adding Python module %s" % name, 2)
394 frozenmodules.append((name, marshal.dumps(code), ispkg))
395 frozenmodules = tuple(frozenmodules)
396 relpath = "Contents/Resources/" + FROZEN_ARCHIVE
397 abspath = pathjoin(self.bundlepath, relpath)
398 f = open(abspath, "wb")
399 marshal.dump(frozenmodules, f)
400 f.close()
401 # add site.pyc
402 sitepath = pathjoin(self.bundlepath, "Contents/Resources/site" + PYC_EXT)
403 writePyc(SITE_CO, sitepath)
404 else:
405 # Create individual .pyc files.
406 for name, code, ispkg in pymodules:
407 if ispkg:
408 name += ".__init__"
409 path = name.split(".")
410 path = pathjoin("Contents/Resources/", *path) + PYC_EXT
411
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)
437 # manually add our own site.py
438 site = mf.add_module("site")
439 site.__code__ = SITE_CO
440 mf.scan_code(SITE_CO, site)
441
442 includeModules = self.includeModules[:]
443 for name in self.includePackages:
444 includeModules.extend(findPackageContents(name).keys())
445 for name in includeModules:
446 try:
447 mf.import_hook(name)
448 except ImportError:
449 self.missingModules.append(name)
450
451
452 mf.run_script(self.mainprogram)
453 modules = mf.modules.items()
454 modules.sort()
455 for name, mod in modules:
456 if mod.__file__ and mod.__code__ is None:
457 # C extension
458 path = mod.__file__
459 ext = os.path.splitext(path)[1]
460 if USE_FROZEN: # "proper" freezing
461 # rename extensions that are submodules of packages to
462 # <packagename>.<modulename>.<ext>
463 dstpath = "Contents/Resources/" + name + ext
464 else:
465 dstpath = name.split(".")
466 dstpath = pathjoin("Contents/Resources/", *dstpath) + ext
467 self.files.append((path, dstpath))
468 self.extensions.append((name, path, dstpath))
469 self.binaries.append(dstpath)
470 elif mod.__code__ is not None:
471 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
477 self.missingModules.extend(mf.any_missing())
478
479 def reportMissing(self):
480 missing = [name for name in self.missingModules
481 if name not in MAYMISS_MODULES]
482 missingsub = [name for name in missing if "." in name]
483 missing = [name for name in missing if "." not in name]
484 missing.sort()
485 missingsub.sort()
486 if missing:
487 self.message("Warning: couldn't find the following modules:", 1)
488 self.message(" " + ", ".join(missing))
489 if missingsub:
490 self.message("Warning: couldn't find the following submodules "
491 "(but it's probably OK since modulefinder can't distinguish "
492 "between from \"module import submodule\" and "
493 "\"from module import name\"):", 1)
494 self.message(" " + ", ".join(missingsub))
495
496#
497# Utilities.
498#
499
500SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
501identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
502
503def findPackageContents(name, searchpath=None):
504 head = name.split(".")[-1]
505 if identifierRE.match(head) is None:
506 return {}
507 try:
508 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
509 except ImportError:
510 return {}
511 modules = {name: None}
512 if tp == imp.PKG_DIRECTORY and path:
513 files = os.listdir(path)
514 for sub in files:
515 sub, ext = os.path.splitext(sub)
516 fullname = name + "." + sub
517 if sub != "__init__" and fullname not in modules:
518 modules.update(findPackageContents(fullname, [path]))
519 return modules
520
521def writePyc(code, path):
522 f = open(path, "wb")
523 f.write("\0" * 8) # don't bother about a time stamp
524 marshal.dump(code, f)
525 f.seek(0, 0)
526 f.write(MAGIC)
527 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000528
Just van Rossumad33d722002-11-21 10:23:04 +0000529def copy(src, dst, mkdirs=0):
530 """Copy a file or a directory."""
531 if mkdirs:
532 makedirs(os.path.dirname(dst))
533 if os.path.isdir(src):
534 shutil.copytree(src, dst)
535 else:
536 shutil.copy2(src, dst)
537
538def copytodir(src, dstdir):
539 """Copy a file or a directory to an existing directory."""
540 dst = pathjoin(dstdir, os.path.basename(src))
541 copy(src, dst)
542
543def makedirs(dir):
544 """Make all directories leading up to 'dir' including the leaf
545 directory. Don't moan if any path element already exists."""
546 try:
547 os.makedirs(dir)
548 except OSError, why:
549 if why.errno != errno.EEXIST:
550 raise
551
552def symlink(src, dst, mkdirs=0):
553 """Copy a file or a directory."""
554 if mkdirs:
555 makedirs(os.path.dirname(dst))
556 os.symlink(os.path.abspath(src), dst)
557
558def pathjoin(*args):
559 """Safe wrapper for os.path.join: asserts that all but the first
560 argument are relative paths."""
561 for seg in args[1:]:
562 assert seg[0] != "/"
563 return os.path.join(*args)
564
565
Just van Rossumceeb9622002-11-21 23:19:37 +0000566cmdline_doc = """\
567Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000568 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000569 python mybuildscript.py [options] command
570
571Commands:
572 build build the application
573 report print a report
574
575Options:
576 -b, --builddir=DIR the build directory; defaults to "build"
577 -n, --name=NAME application name
578 -r, --resource=FILE extra file or folder to be copied to Resources
579 -e, --executable=FILE the executable to be used
580 -m, --mainprogram=FILE the Python main program
581 -p, --plist=FILE .plist file (default: generate one)
582 --nib=NAME main nib name
583 -c, --creator=CCCC 4-char creator code (default: '????')
584 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000585 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000586 --standalone build a standalone application, which is fully
587 independent of a Python installation
588 -x, --exclude=MODULE exclude module (with --standalone)
589 -i, --include=MODULE include module (with --standalone)
590 --package=PACKAGE include a whole package (with --standalone)
591 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000592 -v, --verbose increase verbosity level
593 -q, --quiet decrease verbosity level
594 -h, --help print this message
595"""
596
597def usage(msg=None):
598 if msg:
599 print msg
600 print cmdline_doc
601 sys.exit(1)
602
603def main(builder=None):
604 if builder is None:
605 builder = AppBuilder(verbosity=1)
606
Just van Rossumcef32882002-11-26 00:34:52 +0000607 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000608 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000609 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000610 "link-exec", "help", "verbose", "quiet", "standalone",
611 "exclude=", "include=", "package=", "strip")
Just van Rossumceeb9622002-11-21 23:19:37 +0000612
613 try:
614 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
615 except getopt.error:
616 usage()
617
618 for opt, arg in options:
619 if opt in ('-b', '--builddir'):
620 builder.builddir = arg
621 elif opt in ('-n', '--name'):
622 builder.name = arg
623 elif opt in ('-r', '--resource'):
624 builder.resources.append(arg)
625 elif opt in ('-e', '--executable'):
626 builder.executable = arg
627 elif opt in ('-m', '--mainprogram'):
628 builder.mainprogram = arg
629 elif opt in ('-c', '--creator'):
630 builder.creator = arg
631 elif opt == "--nib":
632 builder.nibname = arg
633 elif opt in ('-p', '--plist'):
634 builder.plist = Plist.fromFile(arg)
635 elif opt in ('-l', '--link'):
636 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000637 elif opt == '--link-exec':
638 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000639 elif opt in ('-h', '--help'):
640 usage()
641 elif opt in ('-v', '--verbose'):
642 builder.verbosity += 1
643 elif opt in ('-q', '--quiet'):
644 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000645 elif opt == '--standalone':
646 builder.standalone = 1
647 elif opt in ('-x', '--exclude'):
648 builder.excludeModules.append(arg)
649 elif opt in ('-i', '--include'):
650 builder.includeModules.append(arg)
651 elif opt == '--package':
652 builder.includePackages.append(arg)
653 elif opt == '--strip':
654 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000655
656 if len(args) != 1:
657 usage("Must specify one command ('build', 'report' or 'help')")
658 command = args[0]
659
660 if command == "build":
661 builder.setup()
662 builder.build()
663 elif command == "report":
664 builder.setup()
665 builder.report()
666 elif command == "help":
667 usage()
668 else:
669 usage("Unknown command '%s'" % command)
670
671
Just van Rossumad33d722002-11-21 10:23:04 +0000672def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000673 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000674 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000675
676
677if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000678 main()