blob: d911292cbd2f0ca0afa83b8648243f16c87e5bb5 [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
Just van Rossum888e1002002-11-30 19:56:14 +0000233for p in sys.path:
234 path = os.path.join(p, "%(filename)s")
235 if os.path.exists(path):
236 break
237else:
238 assert 0, "file not found: %(filename)s"
Just van Rossum535ffa22002-11-29 20:06:52 +0000239mod = imp.load_dynamic("%(name)s", path)
240sys.modules["%(name)s"] = mod
241"""
242
Just van Rossumcef32882002-11-26 00:34:52 +0000243MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
244 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
245 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
246]
247
248STRIP_EXEC = "/usr/bin/strip"
249
Just van Rossum74bdca82002-11-28 11:30:56 +0000250BOOTSTRAP_SCRIPT = """\
251#!/bin/sh
Just van Rossumad33d722002-11-21 10:23:04 +0000252
Just van Rossum74bdca82002-11-28 11:30:56 +0000253execdir=$(dirname ${0})
254executable=${execdir}/%(executable)s
255resdir=$(dirname ${execdir})/Resources
256main=${resdir}/%(mainprogram)s
257PYTHONPATH=$resdir
258export PYTHONPATH
259exec ${executable} ${main} ${1}
Just van Rossumad33d722002-11-21 10:23:04 +0000260"""
261
Just van Rossumcef32882002-11-26 00:34:52 +0000262
Just van Rossumad33d722002-11-21 10:23:04 +0000263class AppBuilder(BundleBuilder):
264
Just van Rossumda302da2002-11-23 22:26:44 +0000265 # A Python main program. If this argument is given, the main
266 # executable in the bundle will be a small wrapper that invokes
267 # the main program. (XXX Discuss why.)
268 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000269
Just van Rossumda302da2002-11-23 22:26:44 +0000270 # The main executable. If a Python main program is specified
271 # the executable will be copied to Resources and be invoked
272 # by the wrapper program mentioned above. Otherwise it will
273 # simply be used as the main executable.
274 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000275
Just van Rossumda302da2002-11-23 22:26:44 +0000276 # The name of the main nib, for Cocoa apps. *Must* be specified
277 # when building a Cocoa app.
278 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000279
Just van Rossumda302da2002-11-23 22:26:44 +0000280 # Symlink the executable instead of copying it.
281 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000282
Just van Rossumcef32882002-11-26 00:34:52 +0000283 # If True, build standalone app.
284 standalone = 0
285
286 # The following attributes are only used when building a standalone app.
287
288 # Exclude these modules.
289 excludeModules = []
290
291 # Include these modules.
292 includeModules = []
293
294 # Include these packages.
295 includePackages = []
296
297 # Strip binaries.
298 strip = 0
299
Just van Rossumcef32882002-11-26 00:34:52 +0000300 # Found Python modules: [(name, codeobject, ispkg), ...]
301 pymodules = []
302
303 # Modules that modulefinder couldn't find:
304 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000305 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000306
307 # List of all binaries (executables or shared libs), for stripping purposes
308 binaries = []
309
Just van Rossumceeb9622002-11-21 23:19:37 +0000310 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000311 if self.standalone and self.mainprogram is None:
312 raise BundleBuilderError, ("must specify 'mainprogram' when "
313 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000314 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000315 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000316 "'executable' and 'mainprogram'")
317
318 if self.name is not None:
319 pass
320 elif self.mainprogram is not None:
321 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
322 elif executable is not None:
323 self.name = os.path.splitext(os.path.basename(self.executable))[0]
324 if self.name[-4:] != ".app":
325 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000326
Just van Rossum74bdca82002-11-28 11:30:56 +0000327 if self.executable is None:
328 if not self.standalone:
329 self.symlink_exec = 1
330 self.executable = sys.executable
331
Just van Rossumceeb9622002-11-21 23:19:37 +0000332 if self.nibname:
333 self.plist.NSMainNibFile = self.nibname
334 if not hasattr(self.plist, "NSPrincipalClass"):
335 self.plist.NSPrincipalClass = "NSApplication"
336
337 BundleBuilder.setup(self)
338
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000339 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000340
Just van Rossumcef32882002-11-26 00:34:52 +0000341 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000342 self.findDependencies()
343
Just van Rossumf7aba232002-11-22 00:31:50 +0000344 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000345 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000346 if self.executable is not None:
347 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000348 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000349 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000350 execname = os.path.basename(self.executable)
351 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000352 if not self.symlink_exec:
353 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000354 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000355 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000356
357 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000358 mainprogram = os.path.basename(self.mainprogram)
359 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
360 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000361 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000362 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000363 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000364 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000365 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
366 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000367
Just van Rossum16aebf72002-11-22 11:43:10 +0000368 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000369 if self.standalone:
370 self.addPythonModules()
Just van Rossumcef32882002-11-26 00:34:52 +0000371 if self.strip and not self.symlink:
372 self.stripBinaries()
373
Just van Rossum16aebf72002-11-22 11:43:10 +0000374 if self.symlink_exec and self.executable:
375 self.message("Symlinking executable %s to %s" % (self.executable,
376 self.execpath), 2)
377 dst = pathjoin(self.bundlepath, self.execpath)
378 makedirs(os.path.dirname(dst))
379 os.symlink(os.path.abspath(self.executable), dst)
380
Just van Rossum74bdca82002-11-28 11:30:56 +0000381 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000382 self.reportMissing()
383
384 def addPythonModules(self):
385 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000386
387 if USE_FROZEN:
388 # This anticipates the acceptance of this patch:
389 # http://www.python.org/sf/642578
390 # Create a file containing all modules, frozen.
391 frozenmodules = []
Just van Rossum535ffa22002-11-29 20:06:52 +0000392 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000393 if ispkg:
394 self.message("Adding Python package %s" % name, 2)
395 else:
396 self.message("Adding Python module %s" % name, 2)
397 frozenmodules.append((name, marshal.dumps(code), ispkg))
398 frozenmodules = tuple(frozenmodules)
Just van Rossum535ffa22002-11-29 20:06:52 +0000399 relpath = pathjoin("Contents", "Resources", FROZEN_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000400 abspath = pathjoin(self.bundlepath, relpath)
401 f = open(abspath, "wb")
402 marshal.dump(frozenmodules, f)
403 f.close()
404 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000405 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
406 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000407 writePyc(SITE_CO, sitepath)
408 else:
409 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000410 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000411 if ispkg:
412 name += ".__init__"
413 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000414 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000415
416 if ispkg:
417 self.message("Adding Python package %s" % path, 2)
418 else:
419 self.message("Adding Python module %s" % path, 2)
420
421 abspath = pathjoin(self.bundlepath, path)
422 makedirs(os.path.dirname(abspath))
423 writePyc(code, abspath)
424
425 def stripBinaries(self):
426 if not os.path.exists(STRIP_EXEC):
427 self.message("Error: can't strip binaries: no strip program at "
428 "%s" % STRIP_EXEC, 0)
429 else:
430 self.message("Stripping binaries", 1)
431 for relpath in self.binaries:
432 self.message("Stripping %s" % relpath, 2)
433 abspath = pathjoin(self.bundlepath, relpath)
434 assert not os.path.islink(abspath)
435 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
436
437 def findDependencies(self):
438 self.message("Finding module dependencies", 1)
439 import modulefinder
440 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
441 # manually add our own site.py
442 site = mf.add_module("site")
443 site.__code__ = SITE_CO
444 mf.scan_code(SITE_CO, site)
445
446 includeModules = self.includeModules[:]
447 for name in self.includePackages:
448 includeModules.extend(findPackageContents(name).keys())
449 for name in includeModules:
450 try:
451 mf.import_hook(name)
452 except ImportError:
453 self.missingModules.append(name)
454
Just van Rossumcef32882002-11-26 00:34:52 +0000455 mf.run_script(self.mainprogram)
456 modules = mf.modules.items()
457 modules.sort()
458 for name, mod in modules:
459 if mod.__file__ and mod.__code__ is None:
460 # C extension
461 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000462 filename = os.path.basename(path)
463 if USE_FROZEN:
464 # "proper" freezing, put extensions in Contents/Resources/,
465 # freeze a tiny "loader" program. Due to Thomas Heller.
466 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
478 if not USE_FROZEN or name != "site":
479 # Our site.py is doing the bootstrapping, so we must
480 # include a real .pyc file if USE_FROZEN is True.
481 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")
549 f.write("\0" * 8) # don't bother about a time stamp
550 marshal.dump(code, f)
551 f.seek(0, 0)
552 f.write(MAGIC)
553 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000554
Just van Rossumad33d722002-11-21 10:23:04 +0000555def copy(src, dst, mkdirs=0):
556 """Copy a file or a directory."""
557 if mkdirs:
558 makedirs(os.path.dirname(dst))
559 if os.path.isdir(src):
560 shutil.copytree(src, dst)
561 else:
562 shutil.copy2(src, dst)
563
564def copytodir(src, dstdir):
565 """Copy a file or a directory to an existing directory."""
566 dst = pathjoin(dstdir, os.path.basename(src))
567 copy(src, dst)
568
569def makedirs(dir):
570 """Make all directories leading up to 'dir' including the leaf
571 directory. Don't moan if any path element already exists."""
572 try:
573 os.makedirs(dir)
574 except OSError, why:
575 if why.errno != errno.EEXIST:
576 raise
577
578def symlink(src, dst, mkdirs=0):
579 """Copy a file or a directory."""
580 if mkdirs:
581 makedirs(os.path.dirname(dst))
582 os.symlink(os.path.abspath(src), dst)
583
584def pathjoin(*args):
585 """Safe wrapper for os.path.join: asserts that all but the first
586 argument are relative paths."""
587 for seg in args[1:]:
588 assert seg[0] != "/"
589 return os.path.join(*args)
590
591
Just van Rossumceeb9622002-11-21 23:19:37 +0000592cmdline_doc = """\
593Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000594 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000595 python mybuildscript.py [options] command
596
597Commands:
598 build build the application
599 report print a report
600
601Options:
602 -b, --builddir=DIR the build directory; defaults to "build"
603 -n, --name=NAME application name
604 -r, --resource=FILE extra file or folder to be copied to Resources
605 -e, --executable=FILE the executable to be used
606 -m, --mainprogram=FILE the Python main program
607 -p, --plist=FILE .plist file (default: generate one)
608 --nib=NAME main nib name
609 -c, --creator=CCCC 4-char creator code (default: '????')
610 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000611 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000612 --standalone build a standalone application, which is fully
613 independent of a Python installation
614 -x, --exclude=MODULE exclude module (with --standalone)
615 -i, --include=MODULE include module (with --standalone)
616 --package=PACKAGE include a whole package (with --standalone)
617 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000618 -v, --verbose increase verbosity level
619 -q, --quiet decrease verbosity level
620 -h, --help print this message
621"""
622
623def usage(msg=None):
624 if msg:
625 print msg
626 print cmdline_doc
627 sys.exit(1)
628
629def main(builder=None):
630 if builder is None:
631 builder = AppBuilder(verbosity=1)
632
Just van Rossumcef32882002-11-26 00:34:52 +0000633 shortopts = "b:n:r:e:m:c:p:lx:i:hvq"
Just van Rossumceeb9622002-11-21 23:19:37 +0000634 longopts = ("builddir=", "name=", "resource=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000635 "mainprogram=", "creator=", "nib=", "plist=", "link",
Just van Rossumcef32882002-11-26 00:34:52 +0000636 "link-exec", "help", "verbose", "quiet", "standalone",
637 "exclude=", "include=", "package=", "strip")
Just van Rossumceeb9622002-11-21 23:19:37 +0000638
639 try:
640 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
641 except getopt.error:
642 usage()
643
644 for opt, arg in options:
645 if opt in ('-b', '--builddir'):
646 builder.builddir = arg
647 elif opt in ('-n', '--name'):
648 builder.name = arg
649 elif opt in ('-r', '--resource'):
650 builder.resources.append(arg)
651 elif opt in ('-e', '--executable'):
652 builder.executable = arg
653 elif opt in ('-m', '--mainprogram'):
654 builder.mainprogram = arg
655 elif opt in ('-c', '--creator'):
656 builder.creator = arg
657 elif opt == "--nib":
658 builder.nibname = arg
659 elif opt in ('-p', '--plist'):
660 builder.plist = Plist.fromFile(arg)
661 elif opt in ('-l', '--link'):
662 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000663 elif opt == '--link-exec':
664 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000665 elif opt in ('-h', '--help'):
666 usage()
667 elif opt in ('-v', '--verbose'):
668 builder.verbosity += 1
669 elif opt in ('-q', '--quiet'):
670 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000671 elif opt == '--standalone':
672 builder.standalone = 1
673 elif opt in ('-x', '--exclude'):
674 builder.excludeModules.append(arg)
675 elif opt in ('-i', '--include'):
676 builder.includeModules.append(arg)
677 elif opt == '--package':
678 builder.includePackages.append(arg)
679 elif opt == '--strip':
680 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000681
682 if len(args) != 1:
683 usage("Must specify one command ('build', 'report' or 'help')")
684 command = args[0]
685
686 if command == "build":
687 builder.setup()
688 builder.build()
689 elif command == "report":
690 builder.setup()
691 builder.report()
692 elif command == "help":
693 usage()
694 else:
695 usage("Unknown command '%s'" % command)
696
697
Just van Rossumad33d722002-11-21 10:23:04 +0000698def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000699 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000700 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000701
702
703if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000704 main()