blob: 4c33e64a298b351a0dbc419f8e5c69b427c3113a [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
Jack Jansen946c1942003-02-17 16:47:12 +000039import macresource
Just van Rossumad33d722002-11-21 10:23:04 +000040
41
Just van Rossumcef32882002-11-26 00:34:52 +000042class BundleBuilderError(Exception): pass
43
44
Just van Rossumda302da2002-11-23 22:26:44 +000045class Defaults:
46
47 """Class attributes that don't start with an underscore and are
48 not functions or classmethods are (deep)copied to self.__dict__.
49 This allows for mutable default values.
50 """
51
52 def __init__(self, **kwargs):
53 defaults = self._getDefaults()
54 defaults.update(kwargs)
55 self.__dict__.update(defaults)
56
57 def _getDefaults(cls):
58 defaults = {}
59 for name, value in cls.__dict__.items():
60 if name[0] != "_" and not isinstance(value,
61 (function, classmethod)):
62 defaults[name] = deepcopy(value)
63 for base in cls.__bases__:
64 if hasattr(base, "_getDefaults"):
65 defaults.update(base._getDefaults())
66 return defaults
67 _getDefaults = classmethod(_getDefaults)
Just van Rossumad33d722002-11-21 10:23:04 +000068
69
Just van Rossumda302da2002-11-23 22:26:44 +000070class BundleBuilder(Defaults):
Just van Rossumad33d722002-11-21 10:23:04 +000071
72 """BundleBuilder is a barebones class for assembling bundles. It
73 knows nothing about executables or icons, it only copies files
74 and creates the PkgInfo and Info.plist files.
Just van Rossumad33d722002-11-21 10:23:04 +000075 """
76
Just van Rossumda302da2002-11-23 22:26:44 +000077 # (Note that Defaults.__init__ (deep)copies these values to
78 # instance variables. Mutable defaults are therefore safe.)
79
80 # Name of the bundle, with or without extension.
81 name = None
82
83 # The property list ("plist")
84 plist = Plist(CFBundleDevelopmentRegion = "English",
85 CFBundleInfoDictionaryVersion = "6.0")
86
87 # The type of the bundle.
88 type = "APPL"
89 # The creator code of the bundle.
Just van Rossume6b49022002-11-24 01:23:45 +000090 creator = None
Just van Rossumda302da2002-11-23 22:26:44 +000091
92 # List of files that have to be copied to <bundle>/Contents/Resources.
93 resources = []
94
95 # List of (src, dest) tuples; dest should be a path relative to the bundle
96 # (eg. "Contents/Resources/MyStuff/SomeFile.ext).
97 files = []
98
99 # Directory where the bundle will be assembled.
100 builddir = "build"
101
102 # platform, name of the subfolder of Contents that contains the executable.
103 platform = "MacOS"
104
105 # Make symlinks instead copying files. This is handy during debugging, but
106 # makes the bundle non-distributable.
107 symlink = 0
108
109 # Verbosity level.
110 verbosity = 1
Just van Rossumad33d722002-11-21 10:23:04 +0000111
Just van Rossumceeb9622002-11-21 23:19:37 +0000112 def setup(self):
Just van Rossumda302da2002-11-23 22:26:44 +0000113 # XXX rethink self.name munging, this is brittle.
Just van Rossumceeb9622002-11-21 23:19:37 +0000114 self.name, ext = os.path.splitext(self.name)
115 if not ext:
116 ext = ".bundle"
Just van Rossumda302da2002-11-23 22:26:44 +0000117 bundleextension = ext
Just van Rossumceeb9622002-11-21 23:19:37 +0000118 # misc (derived) attributes
Just van Rossumda302da2002-11-23 22:26:44 +0000119 self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
Just van Rossumceeb9622002-11-21 23:19:37 +0000120 self.execdir = pathjoin("Contents", self.platform)
121
Just van Rossumda302da2002-11-23 22:26:44 +0000122 plist = self.plist
Just van Rossumceeb9622002-11-21 23:19:37 +0000123 plist.CFBundleName = self.name
124 plist.CFBundlePackageType = self.type
Just van Rossume6b49022002-11-24 01:23:45 +0000125 if self.creator is None:
126 if hasattr(plist, "CFBundleSignature"):
127 self.creator = plist.CFBundleSignature
128 else:
129 self.creator = "????"
Just van Rossumceeb9622002-11-21 23:19:37 +0000130 plist.CFBundleSignature = self.creator
Just van Rossum9896ea22003-01-13 23:30:04 +0000131 if not hasattr(plist, "CFBundleIdentifier"):
132 plist.CFBundleIdentifier = self.name
Just van Rossumceeb9622002-11-21 23:19:37 +0000133
Just van Rossumad33d722002-11-21 10:23:04 +0000134 def build(self):
135 """Build the bundle."""
136 builddir = self.builddir
137 if builddir and not os.path.exists(builddir):
138 os.mkdir(builddir)
139 self.message("Building %s" % repr(self.bundlepath), 1)
140 if os.path.exists(self.bundlepath):
141 shutil.rmtree(self.bundlepath)
142 os.mkdir(self.bundlepath)
143 self.preProcess()
144 self._copyFiles()
145 self._addMetaFiles()
146 self.postProcess()
Just van Rossum535ffa22002-11-29 20:06:52 +0000147 self.message("Done.", 1)
Just van Rossumad33d722002-11-21 10:23:04 +0000148
149 def preProcess(self):
150 """Hook for subclasses."""
151 pass
152 def postProcess(self):
153 """Hook for subclasses."""
154 pass
155
156 def _addMetaFiles(self):
157 contents = pathjoin(self.bundlepath, "Contents")
158 makedirs(contents)
159 #
160 # Write Contents/PkgInfo
161 assert len(self.type) == len(self.creator) == 4, \
162 "type and creator must be 4-byte strings."
163 pkginfo = pathjoin(contents, "PkgInfo")
164 f = open(pkginfo, "wb")
165 f.write(self.type + self.creator)
166 f.close()
167 #
168 # Write Contents/Info.plist
Just van Rossumad33d722002-11-21 10:23:04 +0000169 infoplist = pathjoin(contents, "Info.plist")
Just van Rossumceeb9622002-11-21 23:19:37 +0000170 self.plist.write(infoplist)
Just van Rossumad33d722002-11-21 10:23:04 +0000171
172 def _copyFiles(self):
173 files = self.files[:]
174 for path in self.resources:
175 files.append((path, pathjoin("Contents", "Resources",
176 os.path.basename(path))))
177 if self.symlink:
178 self.message("Making symbolic links", 1)
179 msg = "Making symlink from"
180 else:
181 self.message("Copying files", 1)
182 msg = "Copying"
Just van Rossumcef32882002-11-26 00:34:52 +0000183 files.sort()
Just van Rossumad33d722002-11-21 10:23:04 +0000184 for src, dst in files:
Just van Rossumceeb9622002-11-21 23:19:37 +0000185 if os.path.isdir(src):
186 self.message("%s %s/ to %s/" % (msg, src, dst), 2)
187 else:
188 self.message("%s %s to %s" % (msg, src, dst), 2)
Just van Rossumad33d722002-11-21 10:23:04 +0000189 dst = pathjoin(self.bundlepath, dst)
190 if self.symlink:
191 symlink(src, dst, mkdirs=1)
Jack Jansen946c1942003-02-17 16:47:12 +0000192 elif os.path.splitext(src)[1] == '.rsrc':
193 macresource.install(src, dst, mkdirs=1)
Just van Rossumad33d722002-11-21 10:23:04 +0000194 else:
195 copy(src, dst, mkdirs=1)
196
197 def message(self, msg, level=0):
198 if level <= self.verbosity:
Just van Rossumceeb9622002-11-21 23:19:37 +0000199 indent = ""
200 if level > 1:
201 indent = (level - 1) * " "
202 sys.stderr.write(indent + msg + "\n")
203
204 def report(self):
205 # XXX something decent
Just van Rossum74bdca82002-11-28 11:30:56 +0000206 pass
Just van Rossumad33d722002-11-21 10:23:04 +0000207
208
Just van Rossumcef32882002-11-26 00:34:52 +0000209if __debug__:
210 PYC_EXT = ".pyc"
211else:
212 PYC_EXT = ".pyo"
213
214MAGIC = imp.get_magic()
Just van Rossum109ecbf2003-01-02 13:13:01 +0000215USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
Just van Rossumcef32882002-11-26 00:34:52 +0000216
217# For standalone apps, we have our own minimal site.py. We don't need
218# all the cruft of the real site.py.
219SITE_PY = """\
220import sys
221del sys.path[1:] # sys.path[0] is Contents/Resources/
222"""
223
Just van Rossum109ecbf2003-01-02 13:13:01 +0000224if USE_ZIPIMPORT:
225 ZIP_ARCHIVE = "Modules.zip"
226 SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
227 def getPycData(fullname, code, ispkg):
228 if ispkg:
229 fullname += ".__init__"
230 path = fullname.replace(".", os.sep) + PYC_EXT
231 return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
Just van Rossumcef32882002-11-26 00:34:52 +0000232
Just van Rossum7322b1a2003-02-25 20:15:40 +0000233SITECUSTOMIZE_PY = """\
234import sys, os
235executable = os.getenv("PYTHONEXECUTABLE")
236if executable is not None:
237 sys.executable = executable
238"""
239
240SITE_PY += SITECUSTOMIZE_PY
Just van Rossum74bdca82002-11-28 11:30:56 +0000241SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec")
Just van Rossum7322b1a2003-02-25 20:15:40 +0000242SITECUSTOMIZE_CO = compile(SITECUSTOMIZE_PY, "<-bundlebuilder.py->", "exec")
243
Just van Rossumcef32882002-11-26 00:34:52 +0000244
Just van Rossum535ffa22002-11-29 20:06:52 +0000245EXT_LOADER = """\
Just van Rossum109ecbf2003-01-02 13:13:01 +0000246def __load():
247 import imp, sys, os
248 for p in sys.path:
249 path = os.path.join(p, "%(filename)s")
250 if os.path.exists(path):
251 break
252 else:
253 assert 0, "file not found: %(filename)s"
254 mod = imp.load_dynamic("%(name)s", path)
255
256__load()
257del __load
Just van Rossum535ffa22002-11-29 20:06:52 +0000258"""
259
Just van Rossumcef32882002-11-26 00:34:52 +0000260MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
261 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
262 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
263]
264
265STRIP_EXEC = "/usr/bin/strip"
266
Just van Rossum74bdca82002-11-28 11:30:56 +0000267BOOTSTRAP_SCRIPT = """\
Just van Rossum7322b1a2003-02-25 20:15:40 +0000268#!/usr/bin/env python
Just van Rossumad33d722002-11-21 10:23:04 +0000269
Just van Rossum7322b1a2003-02-25 20:15:40 +0000270import sys, os
271execdir = os.path.dirname(sys.argv[0])
272executable = os.path.join(execdir, "%(executable)s")
273resdir = os.path.join(os.path.dirname(execdir), "Resources")
274mainprogram = os.path.join(resdir, "%(mainprogram)s")
275
276sys.argv.insert(1, mainprogram)
277os.environ["PYTHONPATH"] = resdir
278os.environ["PYTHONEXECUTABLE"] = executable
279os.execve(executable, sys.argv, os.environ)
Just van Rossumad33d722002-11-21 10:23:04 +0000280"""
281
Jack Jansena03adde2003-02-18 23:29:46 +0000282ARGVEMULATOR="""\
283import argvemulator, os
284
285argvemulator.ArgvCollector().mainloop()
286execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
287"""
Just van Rossumcef32882002-11-26 00:34:52 +0000288
Just van Rossumad33d722002-11-21 10:23:04 +0000289class AppBuilder(BundleBuilder):
290
Just van Rossumda302da2002-11-23 22:26:44 +0000291 # A Python main program. If this argument is given, the main
292 # executable in the bundle will be a small wrapper that invokes
293 # the main program. (XXX Discuss why.)
294 mainprogram = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000295
Just van Rossumda302da2002-11-23 22:26:44 +0000296 # The main executable. If a Python main program is specified
297 # the executable will be copied to Resources and be invoked
298 # by the wrapper program mentioned above. Otherwise it will
299 # simply be used as the main executable.
300 executable = None
Just van Rossumceeb9622002-11-21 23:19:37 +0000301
Just van Rossumda302da2002-11-23 22:26:44 +0000302 # The name of the main nib, for Cocoa apps. *Must* be specified
303 # when building a Cocoa app.
304 nibname = None
Just van Rossumad33d722002-11-21 10:23:04 +0000305
Just van Rossum2aa09562003-02-01 08:34:46 +0000306 # The name of the icon file to be copied to Resources and used for
307 # the Finder icon.
308 iconfile = None
309
Just van Rossumda302da2002-11-23 22:26:44 +0000310 # Symlink the executable instead of copying it.
311 symlink_exec = 0
Just van Rossumad33d722002-11-21 10:23:04 +0000312
Just van Rossumcef32882002-11-26 00:34:52 +0000313 # If True, build standalone app.
314 standalone = 0
Jack Jansena03adde2003-02-18 23:29:46 +0000315
316 # If True, add a real main program that emulates sys.argv before calling
317 # mainprogram
318 argv_emulation = 0
Just van Rossumcef32882002-11-26 00:34:52 +0000319
320 # The following attributes are only used when building a standalone app.
321
322 # Exclude these modules.
323 excludeModules = []
324
325 # Include these modules.
326 includeModules = []
327
328 # Include these packages.
329 includePackages = []
330
331 # Strip binaries.
332 strip = 0
333
Just van Rossumcef32882002-11-26 00:34:52 +0000334 # Found Python modules: [(name, codeobject, ispkg), ...]
335 pymodules = []
336
337 # Modules that modulefinder couldn't find:
338 missingModules = []
Just van Rossum74bdca82002-11-28 11:30:56 +0000339 maybeMissingModules = []
Just van Rossumcef32882002-11-26 00:34:52 +0000340
341 # List of all binaries (executables or shared libs), for stripping purposes
342 binaries = []
343
Just van Rossumceeb9622002-11-21 23:19:37 +0000344 def setup(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000345 if self.standalone and self.mainprogram is None:
346 raise BundleBuilderError, ("must specify 'mainprogram' when "
347 "building a standalone application.")
Just van Rossumceeb9622002-11-21 23:19:37 +0000348 if self.mainprogram is None and self.executable is None:
Just van Rossumcef32882002-11-26 00:34:52 +0000349 raise BundleBuilderError, ("must specify either or both of "
Just van Rossumceeb9622002-11-21 23:19:37 +0000350 "'executable' and 'mainprogram'")
351
352 if self.name is not None:
353 pass
354 elif self.mainprogram is not None:
355 self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
356 elif executable is not None:
357 self.name = os.path.splitext(os.path.basename(self.executable))[0]
358 if self.name[-4:] != ".app":
359 self.name += ".app"
Just van Rossumceeb9622002-11-21 23:19:37 +0000360
Just van Rossum74bdca82002-11-28 11:30:56 +0000361 if self.executable is None:
362 if not self.standalone:
363 self.symlink_exec = 1
364 self.executable = sys.executable
365
Just van Rossumceeb9622002-11-21 23:19:37 +0000366 if self.nibname:
367 self.plist.NSMainNibFile = self.nibname
368 if not hasattr(self.plist, "NSPrincipalClass"):
369 self.plist.NSPrincipalClass = "NSApplication"
370
371 BundleBuilder.setup(self)
372
Just van Rossum7fd69ad2002-11-22 00:08:47 +0000373 self.plist.CFBundleExecutable = self.name
Just van Rossumf7aba232002-11-22 00:31:50 +0000374
Just van Rossumcef32882002-11-26 00:34:52 +0000375 if self.standalone:
Just van Rossumcef32882002-11-26 00:34:52 +0000376 self.findDependencies()
377
Just van Rossumf7aba232002-11-22 00:31:50 +0000378 def preProcess(self):
Just van Rossumcef32882002-11-26 00:34:52 +0000379 resdir = "Contents/Resources"
Just van Rossumad33d722002-11-21 10:23:04 +0000380 if self.executable is not None:
381 if self.mainprogram is None:
Just van Rossum74bdca82002-11-28 11:30:56 +0000382 execname = self.name
Just van Rossumad33d722002-11-21 10:23:04 +0000383 else:
Just van Rossum74bdca82002-11-28 11:30:56 +0000384 execname = os.path.basename(self.executable)
385 execpath = pathjoin(self.execdir, execname)
Just van Rossum16aebf72002-11-22 11:43:10 +0000386 if not self.symlink_exec:
387 self.files.append((self.executable, execpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000388 self.binaries.append(execpath)
Just van Rossumda302da2002-11-23 22:26:44 +0000389 self.execpath = execpath
Just van Rossumad33d722002-11-21 10:23:04 +0000390
391 if self.mainprogram is not None:
Just van Rossum24884f72002-11-29 21:22:33 +0000392 mainprogram = os.path.basename(self.mainprogram)
393 self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
Jack Jansena03adde2003-02-18 23:29:46 +0000394 if self.argv_emulation:
395 # Change the main program, and create the helper main program (which
396 # does argv collection and then calls the real main).
397 # Also update the included modules (if we're creating a standalone
398 # program) and the plist
399 realmainprogram = mainprogram
400 mainprogram = '__argvemulator_' + mainprogram
401 resdirpath = pathjoin(self.bundlepath, resdir)
402 mainprogrampath = pathjoin(resdirpath, mainprogram)
403 makedirs(resdirpath)
404 open(mainprogrampath, "w").write(ARGVEMULATOR % locals())
405 if self.standalone:
406 self.includeModules.append("argvemulator")
407 self.includeModules.append("os")
408 if not self.plist.has_key("CFBundleDocumentTypes"):
409 self.plist["CFBundleDocumentTypes"] = [
410 { "CFBundleTypeOSTypes" : [
411 "****",
412 "fold",
413 "disk"],
414 "CFBundleTypeRole": "Viewer"}]
Just van Rossum24884f72002-11-29 21:22:33 +0000415 # Write bootstrap script
Just van Rossum74bdca82002-11-28 11:30:56 +0000416 executable = os.path.basename(self.executable)
Just van Rossumad33d722002-11-21 10:23:04 +0000417 execdir = pathjoin(self.bundlepath, self.execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000418 bootstrappath = pathjoin(execdir, self.name)
Just van Rossumad33d722002-11-21 10:23:04 +0000419 makedirs(execdir)
Just van Rossum24884f72002-11-29 21:22:33 +0000420 open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
421 os.chmod(bootstrappath, 0775)
Just van Rossumad33d722002-11-21 10:23:04 +0000422
Just van Rossum2aa09562003-02-01 08:34:46 +0000423 if self.iconfile is not None:
424 iconbase = os.path.basename(self.iconfile)
425 self.plist.CFBundleIconFile = iconbase
426 self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
427
Just van Rossum16aebf72002-11-22 11:43:10 +0000428 def postProcess(self):
Just van Rossum888e1002002-11-30 19:56:14 +0000429 if self.standalone:
430 self.addPythonModules()
Just van Rossum7322b1a2003-02-25 20:15:40 +0000431 else:
432 sitecustomizepath = pathjoin(self.bundlepath, "Contents", "Resources",
433 "sitecustomize" + PYC_EXT)
434 writePyc(SITECUSTOMIZE_CO, sitecustomizepath)
Just van Rossumcef32882002-11-26 00:34:52 +0000435 if self.strip and not self.symlink:
436 self.stripBinaries()
437
Just van Rossum16aebf72002-11-22 11:43:10 +0000438 if self.symlink_exec and self.executable:
439 self.message("Symlinking executable %s to %s" % (self.executable,
440 self.execpath), 2)
441 dst = pathjoin(self.bundlepath, self.execpath)
442 makedirs(os.path.dirname(dst))
443 os.symlink(os.path.abspath(self.executable), dst)
444
Just van Rossum74bdca82002-11-28 11:30:56 +0000445 if self.missingModules or self.maybeMissingModules:
Just van Rossumcef32882002-11-26 00:34:52 +0000446 self.reportMissing()
447
448 def addPythonModules(self):
449 self.message("Adding Python modules", 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000450
Just van Rossum109ecbf2003-01-02 13:13:01 +0000451 if USE_ZIPIMPORT:
452 # Create a zip file containing all modules as pyc.
453 import zipfile
454 relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
Just van Rossumcef32882002-11-26 00:34:52 +0000455 abspath = pathjoin(self.bundlepath, relpath)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000456 zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
457 for name, code, ispkg in self.pymodules:
458 self.message("Adding Python module %s" % name, 2)
459 path, pyc = getPycData(name, code, ispkg)
460 zf.writestr(path, pyc)
461 zf.close()
Just van Rossumcef32882002-11-26 00:34:52 +0000462 # add site.pyc
Just van Rossum535ffa22002-11-29 20:06:52 +0000463 sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
464 "site" + PYC_EXT)
Just van Rossumcef32882002-11-26 00:34:52 +0000465 writePyc(SITE_CO, sitepath)
466 else:
467 # Create individual .pyc files.
Just van Rossum535ffa22002-11-29 20:06:52 +0000468 for name, code, ispkg in self.pymodules:
Just van Rossumcef32882002-11-26 00:34:52 +0000469 if ispkg:
470 name += ".__init__"
471 path = name.split(".")
Just van Rossum535ffa22002-11-29 20:06:52 +0000472 path = pathjoin("Contents", "Resources", *path) + PYC_EXT
Just van Rossumcef32882002-11-26 00:34:52 +0000473
474 if ispkg:
475 self.message("Adding Python package %s" % path, 2)
476 else:
477 self.message("Adding Python module %s" % path, 2)
478
479 abspath = pathjoin(self.bundlepath, path)
480 makedirs(os.path.dirname(abspath))
481 writePyc(code, abspath)
482
483 def stripBinaries(self):
484 if not os.path.exists(STRIP_EXEC):
485 self.message("Error: can't strip binaries: no strip program at "
486 "%s" % STRIP_EXEC, 0)
487 else:
488 self.message("Stripping binaries", 1)
489 for relpath in self.binaries:
490 self.message("Stripping %s" % relpath, 2)
491 abspath = pathjoin(self.bundlepath, relpath)
492 assert not os.path.islink(abspath)
493 rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath))
494
495 def findDependencies(self):
496 self.message("Finding module dependencies", 1)
497 import modulefinder
498 mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000499 if USE_ZIPIMPORT:
500 # zipimport imports zlib, must add it manually
501 mf.import_hook("zlib")
Just van Rossumcef32882002-11-26 00:34:52 +0000502 # manually add our own site.py
503 site = mf.add_module("site")
504 site.__code__ = SITE_CO
505 mf.scan_code(SITE_CO, site)
506
Just van Rossum7322b1a2003-02-25 20:15:40 +0000507 # warnings.py gets imported implicitly from C
508 mf.import_hook("warnings")
509
Just van Rossumcef32882002-11-26 00:34:52 +0000510 includeModules = self.includeModules[:]
511 for name in self.includePackages:
512 includeModules.extend(findPackageContents(name).keys())
513 for name in includeModules:
514 try:
515 mf.import_hook(name)
516 except ImportError:
517 self.missingModules.append(name)
518
Just van Rossumcef32882002-11-26 00:34:52 +0000519 mf.run_script(self.mainprogram)
520 modules = mf.modules.items()
521 modules.sort()
522 for name, mod in modules:
523 if mod.__file__ and mod.__code__ is None:
524 # C extension
525 path = mod.__file__
Just van Rossum535ffa22002-11-29 20:06:52 +0000526 filename = os.path.basename(path)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000527 if USE_ZIPIMPORT:
528 # Python modules are stored in a Zip archive, but put
529 # extensions in Contents/Resources/.a and add a tiny "loader"
530 # program in the Zip archive. Due to Thomas Heller.
Just van Rossum535ffa22002-11-29 20:06:52 +0000531 dstpath = pathjoin("Contents", "Resources", filename)
532 source = EXT_LOADER % {"name": name, "filename": filename}
533 code = compile(source, "<dynloader for %s>" % name, "exec")
534 mod.__code__ = code
Just van Rossumcef32882002-11-26 00:34:52 +0000535 else:
Just van Rossum535ffa22002-11-29 20:06:52 +0000536 # just copy the file
537 dstpath = name.split(".")[:-1] + [filename]
538 dstpath = pathjoin("Contents", "Resources", *dstpath)
Just van Rossumcef32882002-11-26 00:34:52 +0000539 self.files.append((path, dstpath))
Just van Rossumcef32882002-11-26 00:34:52 +0000540 self.binaries.append(dstpath)
Just van Rossum535ffa22002-11-29 20:06:52 +0000541 if mod.__code__ is not None:
Just van Rossumcef32882002-11-26 00:34:52 +0000542 ispkg = mod.__path__ is not None
Just van Rossum109ecbf2003-01-02 13:13:01 +0000543 if not USE_ZIPIMPORT or name != "site":
Just van Rossumcef32882002-11-26 00:34:52 +0000544 # Our site.py is doing the bootstrapping, so we must
Just van Rossum109ecbf2003-01-02 13:13:01 +0000545 # include a real .pyc file if USE_ZIPIMPORT is True.
Just van Rossumcef32882002-11-26 00:34:52 +0000546 self.pymodules.append((name, mod.__code__, ispkg))
547
Just van Rossum74bdca82002-11-28 11:30:56 +0000548 if hasattr(mf, "any_missing_maybe"):
549 missing, maybe = mf.any_missing_maybe()
550 else:
551 missing = mf.any_missing()
552 maybe = []
553 self.missingModules.extend(missing)
554 self.maybeMissingModules.extend(maybe)
Just van Rossumcef32882002-11-26 00:34:52 +0000555
556 def reportMissing(self):
557 missing = [name for name in self.missingModules
558 if name not in MAYMISS_MODULES]
Just van Rossum74bdca82002-11-28 11:30:56 +0000559 if self.maybeMissingModules:
560 maybe = self.maybeMissingModules
561 else:
562 maybe = [name for name in missing if "." in name]
563 missing = [name for name in missing if "." not in name]
Just van Rossumcef32882002-11-26 00:34:52 +0000564 missing.sort()
Just van Rossum74bdca82002-11-28 11:30:56 +0000565 maybe.sort()
566 if maybe:
567 self.message("Warning: couldn't find the following submodules:", 1)
568 self.message(" (Note that these could be false alarms -- "
569 "it's not always", 1)
Just van Rossumad692cc2002-11-28 18:56:50 +0000570 self.message(" possible to distinguish between \"from package "
571 "import submodule\" ", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000572 self.message(" and \"from package import name\")", 1)
573 for name in maybe:
574 self.message(" ? " + name, 1)
Just van Rossumcef32882002-11-26 00:34:52 +0000575 if missing:
576 self.message("Warning: couldn't find the following modules:", 1)
Just van Rossum74bdca82002-11-28 11:30:56 +0000577 for name in missing:
578 self.message(" ? " + name, 1)
579
580 def report(self):
581 # XXX something decent
582 import pprint
583 pprint.pprint(self.__dict__)
584 if self.standalone:
585 self.reportMissing()
Just van Rossumcef32882002-11-26 00:34:52 +0000586
587#
588# Utilities.
589#
590
591SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
592identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
593
594def findPackageContents(name, searchpath=None):
595 head = name.split(".")[-1]
596 if identifierRE.match(head) is None:
597 return {}
598 try:
599 fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
600 except ImportError:
601 return {}
602 modules = {name: None}
603 if tp == imp.PKG_DIRECTORY and path:
604 files = os.listdir(path)
605 for sub in files:
606 sub, ext = os.path.splitext(sub)
607 fullname = name + "." + sub
608 if sub != "__init__" and fullname not in modules:
609 modules.update(findPackageContents(fullname, [path]))
610 return modules
611
612def writePyc(code, path):
613 f = open(path, "wb")
Just van Rossumcef32882002-11-26 00:34:52 +0000614 f.write(MAGIC)
Just van Rossum109ecbf2003-01-02 13:13:01 +0000615 f.write("\0" * 4) # don't bother about a time stamp
616 marshal.dump(code, f)
Just van Rossumcef32882002-11-26 00:34:52 +0000617 f.close()
Just van Rossumad33d722002-11-21 10:23:04 +0000618
Just van Rossumad33d722002-11-21 10:23:04 +0000619def copy(src, dst, mkdirs=0):
620 """Copy a file or a directory."""
621 if mkdirs:
622 makedirs(os.path.dirname(dst))
623 if os.path.isdir(src):
624 shutil.copytree(src, dst)
625 else:
626 shutil.copy2(src, dst)
627
628def copytodir(src, dstdir):
629 """Copy a file or a directory to an existing directory."""
630 dst = pathjoin(dstdir, os.path.basename(src))
631 copy(src, dst)
632
633def makedirs(dir):
634 """Make all directories leading up to 'dir' including the leaf
635 directory. Don't moan if any path element already exists."""
636 try:
637 os.makedirs(dir)
638 except OSError, why:
639 if why.errno != errno.EEXIST:
640 raise
641
642def symlink(src, dst, mkdirs=0):
643 """Copy a file or a directory."""
Just van Rossum504377d2003-01-17 20:02:06 +0000644 if not os.path.exists(src):
645 raise IOError, "No such file or directory: '%s'" % src
Just van Rossumad33d722002-11-21 10:23:04 +0000646 if mkdirs:
647 makedirs(os.path.dirname(dst))
648 os.symlink(os.path.abspath(src), dst)
649
650def pathjoin(*args):
651 """Safe wrapper for os.path.join: asserts that all but the first
652 argument are relative paths."""
653 for seg in args[1:]:
654 assert seg[0] != "/"
655 return os.path.join(*args)
656
657
Just van Rossumceeb9622002-11-21 23:19:37 +0000658cmdline_doc = """\
659Usage:
Just van Rossumf7aba232002-11-22 00:31:50 +0000660 python bundlebuilder.py [options] command
Just van Rossumceeb9622002-11-21 23:19:37 +0000661 python mybuildscript.py [options] command
662
663Commands:
664 build build the application
665 report print a report
666
667Options:
668 -b, --builddir=DIR the build directory; defaults to "build"
669 -n, --name=NAME application name
670 -r, --resource=FILE extra file or folder to be copied to Resources
Jack Jansen00cbf072003-02-24 16:27:08 +0000671 -f, --copyfile=SRC:DST extra file or folder to be copied into the bundle
Just van Rossumceeb9622002-11-21 23:19:37 +0000672 -e, --executable=FILE the executable to be used
673 -m, --mainprogram=FILE the Python main program
Jack Jansena03adde2003-02-18 23:29:46 +0000674 -a, --argv add a wrapper main program to create sys.argv
Just van Rossumceeb9622002-11-21 23:19:37 +0000675 -p, --plist=FILE .plist file (default: generate one)
676 --nib=NAME main nib name
677 -c, --creator=CCCC 4-char creator code (default: '????')
Just van Rossum9af69682003-02-02 18:56:37 +0000678 --iconfile=FILE filename of the icon (an .icns file) to be used
Just van Rossum2aa09562003-02-01 08:34:46 +0000679 as the Finder icon
Just van Rossumceeb9622002-11-21 23:19:37 +0000680 -l, --link symlink files/folder instead of copying them
Just van Rossum16aebf72002-11-22 11:43:10 +0000681 --link-exec symlink the executable instead of copying it
Just van Rossumcef32882002-11-26 00:34:52 +0000682 --standalone build a standalone application, which is fully
683 independent of a Python installation
684 -x, --exclude=MODULE exclude module (with --standalone)
685 -i, --include=MODULE include module (with --standalone)
686 --package=PACKAGE include a whole package (with --standalone)
687 --strip strip binaries (remove debug info)
Just van Rossumceeb9622002-11-21 23:19:37 +0000688 -v, --verbose increase verbosity level
689 -q, --quiet decrease verbosity level
690 -h, --help print this message
691"""
692
693def usage(msg=None):
694 if msg:
695 print msg
696 print cmdline_doc
697 sys.exit(1)
698
699def main(builder=None):
700 if builder is None:
701 builder = AppBuilder(verbosity=1)
702
Jack Jansen00cbf072003-02-24 16:27:08 +0000703 shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
704 longopts = ("builddir=", "name=", "resource=", "copyfile=", "executable=",
Just van Rossum16aebf72002-11-22 11:43:10 +0000705 "mainprogram=", "creator=", "nib=", "plist=", "link",
Jack Jansena03adde2003-02-18 23:29:46 +0000706 "link-exec", "help", "verbose", "quiet", "argv", "standalone",
Just van Rossum2aa09562003-02-01 08:34:46 +0000707 "exclude=", "include=", "package=", "strip", "iconfile=")
Just van Rossumceeb9622002-11-21 23:19:37 +0000708
709 try:
710 options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
711 except getopt.error:
712 usage()
713
714 for opt, arg in options:
715 if opt in ('-b', '--builddir'):
716 builder.builddir = arg
717 elif opt in ('-n', '--name'):
718 builder.name = arg
719 elif opt in ('-r', '--resource'):
720 builder.resources.append(arg)
Jack Jansen00cbf072003-02-24 16:27:08 +0000721 elif opt in ('-f', '--copyfile'):
722 srcdst = arg.split(':')
723 if len(srcdst) != 2:
724 usage()
725 builder.files.append(srcdst)
Just van Rossumceeb9622002-11-21 23:19:37 +0000726 elif opt in ('-e', '--executable'):
727 builder.executable = arg
728 elif opt in ('-m', '--mainprogram'):
729 builder.mainprogram = arg
Jack Jansena03adde2003-02-18 23:29:46 +0000730 elif opt in ('-a', '--argv'):
731 builder.argv_emulation = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000732 elif opt in ('-c', '--creator'):
733 builder.creator = arg
Just van Rossum2aa09562003-02-01 08:34:46 +0000734 elif opt == '--iconfile':
735 builder.iconfile = arg
Just van Rossumceeb9622002-11-21 23:19:37 +0000736 elif opt == "--nib":
737 builder.nibname = arg
738 elif opt in ('-p', '--plist'):
739 builder.plist = Plist.fromFile(arg)
740 elif opt in ('-l', '--link'):
741 builder.symlink = 1
Just van Rossum16aebf72002-11-22 11:43:10 +0000742 elif opt == '--link-exec':
743 builder.symlink_exec = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000744 elif opt in ('-h', '--help'):
745 usage()
746 elif opt in ('-v', '--verbose'):
747 builder.verbosity += 1
748 elif opt in ('-q', '--quiet'):
749 builder.verbosity -= 1
Just van Rossumcef32882002-11-26 00:34:52 +0000750 elif opt == '--standalone':
751 builder.standalone = 1
752 elif opt in ('-x', '--exclude'):
753 builder.excludeModules.append(arg)
754 elif opt in ('-i', '--include'):
755 builder.includeModules.append(arg)
756 elif opt == '--package':
757 builder.includePackages.append(arg)
758 elif opt == '--strip':
759 builder.strip = 1
Just van Rossumceeb9622002-11-21 23:19:37 +0000760
761 if len(args) != 1:
762 usage("Must specify one command ('build', 'report' or 'help')")
763 command = args[0]
764
765 if command == "build":
766 builder.setup()
767 builder.build()
768 elif command == "report":
769 builder.setup()
770 builder.report()
771 elif command == "help":
772 usage()
773 else:
774 usage("Unknown command '%s'" % command)
775
776
Just van Rossumad33d722002-11-21 10:23:04 +0000777def buildapp(**kwargs):
Just van Rossumad33d722002-11-21 10:23:04 +0000778 builder = AppBuilder(**kwargs)
Just van Rossumceeb9622002-11-21 23:19:37 +0000779 main(builder)
Just van Rossumad33d722002-11-21 10:23:04 +0000780
781
782if __name__ == "__main__":
Just van Rossumceeb9622002-11-21 23:19:37 +0000783 main()