PageRenderTime 50ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/plat-mac/bundlebuilder.py

https://bitbucket.org/kkris/pypy
Python | 949 lines | 899 code | 20 blank | 30 comment | 52 complexity | 8109292ecf92e019fcfa618290490388 MD5 | raw file
  1. #! /usr/bin/env python
  2. """\
  3. bundlebuilder.py -- Tools to assemble MacOS X (application) bundles.
  4. This module contains two classes to build so called "bundles" for
  5. MacOS X. BundleBuilder is a general tool, AppBuilder is a subclass
  6. specialized in building application bundles.
  7. [Bundle|App]Builder objects are instantiated with a bunch of keyword
  8. arguments, and have a build() method that will do all the work. See
  9. the class doc strings for a description of the constructor arguments.
  10. The module contains a main program that can be used in two ways:
  11. % python bundlebuilder.py [options] build
  12. % python buildapp.py [options] build
  13. Where "buildapp.py" is a user-supplied setup.py-like script following
  14. this model:
  15. from bundlebuilder import buildapp
  16. buildapp(<lots-of-keyword-args>)
  17. """
  18. __all__ = ["BundleBuilder", "BundleBuilderError", "AppBuilder", "buildapp"]
  19. from warnings import warnpy3k
  20. warnpy3k("In 3.x, the bundlebuilder module is removed.", stacklevel=2)
  21. import sys
  22. import os, errno, shutil
  23. import imp, marshal
  24. import re
  25. from copy import deepcopy
  26. import getopt
  27. from plistlib import Plist
  28. from types import FunctionType as function
  29. class BundleBuilderError(Exception): pass
  30. class Defaults:
  31. """Class attributes that don't start with an underscore and are
  32. not functions or classmethods are (deep)copied to self.__dict__.
  33. This allows for mutable default values.
  34. """
  35. def __init__(self, **kwargs):
  36. defaults = self._getDefaults()
  37. defaults.update(kwargs)
  38. self.__dict__.update(defaults)
  39. def _getDefaults(cls):
  40. defaults = {}
  41. for base in cls.__bases__:
  42. if hasattr(base, "_getDefaults"):
  43. defaults.update(base._getDefaults())
  44. for name, value in cls.__dict__.items():
  45. if name[0] != "_" and not isinstance(value,
  46. (function, classmethod)):
  47. defaults[name] = deepcopy(value)
  48. return defaults
  49. _getDefaults = classmethod(_getDefaults)
  50. class BundleBuilder(Defaults):
  51. """BundleBuilder is a barebones class for assembling bundles. It
  52. knows nothing about executables or icons, it only copies files
  53. and creates the PkgInfo and Info.plist files.
  54. """
  55. # (Note that Defaults.__init__ (deep)copies these values to
  56. # instance variables. Mutable defaults are therefore safe.)
  57. # Name of the bundle, with or without extension.
  58. name = None
  59. # The property list ("plist")
  60. plist = Plist(CFBundleDevelopmentRegion = "English",
  61. CFBundleInfoDictionaryVersion = "6.0")
  62. # The type of the bundle.
  63. type = "BNDL"
  64. # The creator code of the bundle.
  65. creator = None
  66. # the CFBundleIdentifier (this is used for the preferences file name)
  67. bundle_id = None
  68. # List of files that have to be copied to <bundle>/Contents/Resources.
  69. resources = []
  70. # List of (src, dest) tuples; dest should be a path relative to the bundle
  71. # (eg. "Contents/Resources/MyStuff/SomeFile.ext).
  72. files = []
  73. # List of shared libraries (dylibs, Frameworks) to bundle with the app
  74. # will be placed in Contents/Frameworks
  75. libs = []
  76. # Directory where the bundle will be assembled.
  77. builddir = "build"
  78. # Make symlinks instead copying files. This is handy during debugging, but
  79. # makes the bundle non-distributable.
  80. symlink = 0
  81. # Verbosity level.
  82. verbosity = 1
  83. # Destination root directory
  84. destroot = ""
  85. def setup(self):
  86. # XXX rethink self.name munging, this is brittle.
  87. self.name, ext = os.path.splitext(self.name)
  88. if not ext:
  89. ext = ".bundle"
  90. bundleextension = ext
  91. # misc (derived) attributes
  92. self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
  93. plist = self.plist
  94. plist.CFBundleName = self.name
  95. plist.CFBundlePackageType = self.type
  96. if self.creator is None:
  97. if hasattr(plist, "CFBundleSignature"):
  98. self.creator = plist.CFBundleSignature
  99. else:
  100. self.creator = "????"
  101. plist.CFBundleSignature = self.creator
  102. if self.bundle_id:
  103. plist.CFBundleIdentifier = self.bundle_id
  104. elif not hasattr(plist, "CFBundleIdentifier"):
  105. plist.CFBundleIdentifier = self.name
  106. def build(self):
  107. """Build the bundle."""
  108. builddir = self.builddir
  109. if builddir and not os.path.exists(builddir):
  110. os.mkdir(builddir)
  111. self.message("Building %s" % repr(self.bundlepath), 1)
  112. if os.path.exists(self.bundlepath):
  113. shutil.rmtree(self.bundlepath)
  114. if os.path.exists(self.bundlepath + '~'):
  115. shutil.rmtree(self.bundlepath + '~')
  116. bp = self.bundlepath
  117. # Create the app bundle in a temporary location and then
  118. # rename the completed bundle. This way the Finder will
  119. # never see an incomplete bundle (where it might pick up
  120. # and cache the wrong meta data)
  121. self.bundlepath = bp + '~'
  122. try:
  123. os.mkdir(self.bundlepath)
  124. self.preProcess()
  125. self._copyFiles()
  126. self._addMetaFiles()
  127. self.postProcess()
  128. os.rename(self.bundlepath, bp)
  129. finally:
  130. self.bundlepath = bp
  131. self.message("Done.", 1)
  132. def preProcess(self):
  133. """Hook for subclasses."""
  134. pass
  135. def postProcess(self):
  136. """Hook for subclasses."""
  137. pass
  138. def _addMetaFiles(self):
  139. contents = pathjoin(self.bundlepath, "Contents")
  140. makedirs(contents)
  141. #
  142. # Write Contents/PkgInfo
  143. assert len(self.type) == len(self.creator) == 4, \
  144. "type and creator must be 4-byte strings."
  145. pkginfo = pathjoin(contents, "PkgInfo")
  146. f = open(pkginfo, "wb")
  147. f.write(self.type + self.creator)
  148. f.close()
  149. #
  150. # Write Contents/Info.plist
  151. infoplist = pathjoin(contents, "Info.plist")
  152. self.plist.write(infoplist)
  153. def _copyFiles(self):
  154. files = self.files[:]
  155. for path in self.resources:
  156. files.append((path, pathjoin("Contents", "Resources",
  157. os.path.basename(path))))
  158. for path in self.libs:
  159. files.append((path, pathjoin("Contents", "Frameworks",
  160. os.path.basename(path))))
  161. if self.symlink:
  162. self.message("Making symbolic links", 1)
  163. msg = "Making symlink from"
  164. else:
  165. self.message("Copying files", 1)
  166. msg = "Copying"
  167. files.sort()
  168. for src, dst in files:
  169. if os.path.isdir(src):
  170. self.message("%s %s/ to %s/" % (msg, src, dst), 2)
  171. else:
  172. self.message("%s %s to %s" % (msg, src, dst), 2)
  173. dst = pathjoin(self.bundlepath, dst)
  174. if self.symlink:
  175. symlink(src, dst, mkdirs=1)
  176. else:
  177. copy(src, dst, mkdirs=1)
  178. def message(self, msg, level=0):
  179. if level <= self.verbosity:
  180. indent = ""
  181. if level > 1:
  182. indent = (level - 1) * " "
  183. sys.stderr.write(indent + msg + "\n")
  184. def report(self):
  185. # XXX something decent
  186. pass
  187. if __debug__:
  188. PYC_EXT = ".pyc"
  189. else:
  190. PYC_EXT = ".pyo"
  191. MAGIC = imp.get_magic()
  192. USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
  193. # For standalone apps, we have our own minimal site.py. We don't need
  194. # all the cruft of the real site.py.
  195. SITE_PY = """\
  196. import sys
  197. if not %(semi_standalone)s:
  198. del sys.path[1:] # sys.path[0] is Contents/Resources/
  199. """
  200. ZIP_ARCHIVE = "Modules.zip"
  201. SITE_PY_ZIP = SITE_PY + ("sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE)
  202. def getPycData(fullname, code, ispkg):
  203. if ispkg:
  204. fullname += ".__init__"
  205. path = fullname.replace(".", os.sep) + PYC_EXT
  206. return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
  207. #
  208. # Extension modules can't be in the modules zip archive, so a placeholder
  209. # is added instead, that loads the extension from a specified location.
  210. #
  211. EXT_LOADER = """\
  212. def __load():
  213. import imp, sys, os
  214. for p in sys.path:
  215. path = os.path.join(p, "%(filename)s")
  216. if os.path.exists(path):
  217. break
  218. else:
  219. assert 0, "file not found: %(filename)s"
  220. mod = imp.load_dynamic("%(name)s", path)
  221. __load()
  222. del __load
  223. """
  224. MAYMISS_MODULES = ['os2', 'nt', 'ntpath', 'dos', 'dospath',
  225. 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
  226. 'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
  227. ]
  228. STRIP_EXEC = "/usr/bin/strip"
  229. #
  230. # We're using a stock interpreter to run the app, yet we need
  231. # a way to pass the Python main program to the interpreter. The
  232. # bootstrapping script fires up the interpreter with the right
  233. # arguments. os.execve() is used as OSX doesn't like us to
  234. # start a real new process. Also, the executable name must match
  235. # the CFBundleExecutable value in the Info.plist, so we lie
  236. # deliberately with argv[0]. The actual Python executable is
  237. # passed in an environment variable so we can "repair"
  238. # sys.executable later.
  239. #
  240. BOOTSTRAP_SCRIPT = """\
  241. #!%(hashbang)s
  242. import sys, os
  243. execdir = os.path.dirname(sys.argv[0])
  244. executable = os.path.join(execdir, "%(executable)s")
  245. resdir = os.path.join(os.path.dirname(execdir), "Resources")
  246. libdir = os.path.join(os.path.dirname(execdir), "Frameworks")
  247. mainprogram = os.path.join(resdir, "%(mainprogram)s")
  248. if %(optimize)s:
  249. sys.argv.insert(1, '-O')
  250. sys.argv.insert(1, mainprogram)
  251. if %(standalone)s or %(semi_standalone)s:
  252. os.environ["PYTHONPATH"] = resdir
  253. if %(standalone)s:
  254. os.environ["PYTHONHOME"] = resdir
  255. else:
  256. pypath = os.getenv("PYTHONPATH", "")
  257. if pypath:
  258. pypath = ":" + pypath
  259. os.environ["PYTHONPATH"] = resdir + pypath
  260. os.environ["PYTHONEXECUTABLE"] = executable
  261. os.environ["DYLD_LIBRARY_PATH"] = libdir
  262. os.environ["DYLD_FRAMEWORK_PATH"] = libdir
  263. os.execve(executable, sys.argv, os.environ)
  264. """
  265. #
  266. # Optional wrapper that converts "dropped files" into sys.argv values.
  267. #
  268. ARGV_EMULATOR = """\
  269. import argvemulator, os
  270. argvemulator.ArgvCollector().mainloop()
  271. execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
  272. """
  273. #
  274. # When building a standalone app with Python.framework, we need to copy
  275. # a subset from Python.framework to the bundle. The following list
  276. # specifies exactly what items we'll copy.
  277. #
  278. PYTHONFRAMEWORKGOODIES = [
  279. "Python", # the Python core library
  280. "Resources/English.lproj",
  281. "Resources/Info.plist",
  282. ]
  283. def isFramework():
  284. return sys.exec_prefix.find("Python.framework") > 0
  285. LIB = os.path.join(sys.prefix, "lib", "python" + sys.version[:3])
  286. SITE_PACKAGES = os.path.join(LIB, "site-packages")
  287. class AppBuilder(BundleBuilder):
  288. use_zipimport = USE_ZIPIMPORT
  289. # Override type of the bundle.
  290. type = "APPL"
  291. # platform, name of the subfolder of Contents that contains the executable.
  292. platform = "MacOS"
  293. # A Python main program. If this argument is given, the main
  294. # executable in the bundle will be a small wrapper that invokes
  295. # the main program. (XXX Discuss why.)
  296. mainprogram = None
  297. # The main executable. If a Python main program is specified
  298. # the executable will be copied to Resources and be invoked
  299. # by the wrapper program mentioned above. Otherwise it will
  300. # simply be used as the main executable.
  301. executable = None
  302. # The name of the main nib, for Cocoa apps. *Must* be specified
  303. # when building a Cocoa app.
  304. nibname = None
  305. # The name of the icon file to be copied to Resources and used for
  306. # the Finder icon.
  307. iconfile = None
  308. # Symlink the executable instead of copying it.
  309. symlink_exec = 0
  310. # If True, build standalone app.
  311. standalone = 0
  312. # If True, build semi-standalone app (only includes third-party modules).
  313. semi_standalone = 0
  314. # If set, use this for #! lines in stead of sys.executable
  315. python = None
  316. # If True, add a real main program that emulates sys.argv before calling
  317. # mainprogram
  318. argv_emulation = 0
  319. # The following attributes are only used when building a standalone app.
  320. # Exclude these modules.
  321. excludeModules = []
  322. # Include these modules.
  323. includeModules = []
  324. # Include these packages.
  325. includePackages = []
  326. # Strip binaries from debug info.
  327. strip = 0
  328. # Found Python modules: [(name, codeobject, ispkg), ...]
  329. pymodules = []
  330. # Modules that modulefinder couldn't find:
  331. missingModules = []
  332. maybeMissingModules = []
  333. def setup(self):
  334. if ((self.standalone or self.semi_standalone)
  335. and self.mainprogram is None):
  336. raise BundleBuilderError, ("must specify 'mainprogram' when "
  337. "building a standalone application.")
  338. if self.mainprogram is None and self.executable is None:
  339. raise BundleBuilderError, ("must specify either or both of "
  340. "'executable' and 'mainprogram'")
  341. self.execdir = pathjoin("Contents", self.platform)
  342. if self.name is not None:
  343. pass
  344. elif self.mainprogram is not None:
  345. self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
  346. elif self.executable is not None:
  347. self.name = os.path.splitext(os.path.basename(self.executable))[0]
  348. if self.name[-4:] != ".app":
  349. self.name += ".app"
  350. if self.executable is None:
  351. if not self.standalone and not isFramework():
  352. self.symlink_exec = 1
  353. if self.python:
  354. self.executable = self.python
  355. else:
  356. self.executable = sys.executable
  357. if self.nibname:
  358. self.plist.NSMainNibFile = self.nibname
  359. if not hasattr(self.plist, "NSPrincipalClass"):
  360. self.plist.NSPrincipalClass = "NSApplication"
  361. if self.standalone and isFramework():
  362. self.addPythonFramework()
  363. BundleBuilder.setup(self)
  364. self.plist.CFBundleExecutable = self.name
  365. if self.standalone or self.semi_standalone:
  366. self.findDependencies()
  367. def preProcess(self):
  368. resdir = "Contents/Resources"
  369. if self.executable is not None:
  370. if self.mainprogram is None:
  371. execname = self.name
  372. else:
  373. execname = os.path.basename(self.executable)
  374. execpath = pathjoin(self.execdir, execname)
  375. if not self.symlink_exec:
  376. self.files.append((self.destroot + self.executable, execpath))
  377. self.execpath = execpath
  378. if self.mainprogram is not None:
  379. mainprogram = os.path.basename(self.mainprogram)
  380. self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
  381. if self.argv_emulation:
  382. # Change the main program, and create the helper main program (which
  383. # does argv collection and then calls the real main).
  384. # Also update the included modules (if we're creating a standalone
  385. # program) and the plist
  386. realmainprogram = mainprogram
  387. mainprogram = '__argvemulator_' + mainprogram
  388. resdirpath = pathjoin(self.bundlepath, resdir)
  389. mainprogrampath = pathjoin(resdirpath, mainprogram)
  390. makedirs(resdirpath)
  391. open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
  392. if self.standalone or self.semi_standalone:
  393. self.includeModules.append("argvemulator")
  394. self.includeModules.append("os")
  395. if "CFBundleDocumentTypes" not in self.plist:
  396. self.plist["CFBundleDocumentTypes"] = [
  397. { "CFBundleTypeOSTypes" : [
  398. "****",
  399. "fold",
  400. "disk"],
  401. "CFBundleTypeRole": "Viewer"}]
  402. # Write bootstrap script
  403. executable = os.path.basename(self.executable)
  404. execdir = pathjoin(self.bundlepath, self.execdir)
  405. bootstrappath = pathjoin(execdir, self.name)
  406. makedirs(execdir)
  407. if self.standalone or self.semi_standalone:
  408. # XXX we're screwed when the end user has deleted
  409. # /usr/bin/python
  410. hashbang = "/usr/bin/python"
  411. elif self.python:
  412. hashbang = self.python
  413. else:
  414. hashbang = os.path.realpath(sys.executable)
  415. standalone = self.standalone
  416. semi_standalone = self.semi_standalone
  417. optimize = sys.flags.optimize
  418. open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
  419. os.chmod(bootstrappath, 0775)
  420. if self.iconfile is not None:
  421. iconbase = os.path.basename(self.iconfile)
  422. self.plist.CFBundleIconFile = iconbase
  423. self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
  424. def postProcess(self):
  425. if self.standalone or self.semi_standalone:
  426. self.addPythonModules()
  427. if self.strip and not self.symlink:
  428. self.stripBinaries()
  429. if self.symlink_exec and self.executable:
  430. self.message("Symlinking executable %s to %s" % (self.executable,
  431. self.execpath), 2)
  432. dst = pathjoin(self.bundlepath, self.execpath)
  433. makedirs(os.path.dirname(dst))
  434. os.symlink(os.path.abspath(self.executable), dst)
  435. if self.missingModules or self.maybeMissingModules:
  436. self.reportMissing()
  437. def addPythonFramework(self):
  438. # If we're building a standalone app with Python.framework,
  439. # include a minimal subset of Python.framework, *unless*
  440. # Python.framework was specified manually in self.libs.
  441. for lib in self.libs:
  442. if os.path.basename(lib) == "Python.framework":
  443. # a Python.framework was specified as a library
  444. return
  445. frameworkpath = sys.exec_prefix[:sys.exec_prefix.find(
  446. "Python.framework") + len("Python.framework")]
  447. version = sys.version[:3]
  448. frameworkpath = pathjoin(frameworkpath, "Versions", version)
  449. destbase = pathjoin("Contents", "Frameworks", "Python.framework",
  450. "Versions", version)
  451. for item in PYTHONFRAMEWORKGOODIES:
  452. src = pathjoin(frameworkpath, item)
  453. dst = pathjoin(destbase, item)
  454. self.files.append((src, dst))
  455. def _getSiteCode(self):
  456. if self.use_zipimport:
  457. return compile(SITE_PY % {"semi_standalone": self.semi_standalone},
  458. "<-bundlebuilder.py->", "exec")
  459. def addPythonModules(self):
  460. self.message("Adding Python modules", 1)
  461. if self.use_zipimport:
  462. # Create a zip file containing all modules as pyc.
  463. import zipfile
  464. relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
  465. abspath = pathjoin(self.bundlepath, relpath)
  466. zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
  467. for name, code, ispkg in self.pymodules:
  468. self.message("Adding Python module %s" % name, 2)
  469. path, pyc = getPycData(name, code, ispkg)
  470. zf.writestr(path, pyc)
  471. zf.close()
  472. # add site.pyc
  473. sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
  474. "site" + PYC_EXT)
  475. writePyc(self._getSiteCode(), sitepath)
  476. else:
  477. # Create individual .pyc files.
  478. for name, code, ispkg in self.pymodules:
  479. if ispkg:
  480. name += ".__init__"
  481. path = name.split(".")
  482. path = pathjoin("Contents", "Resources", *path) + PYC_EXT
  483. if ispkg:
  484. self.message("Adding Python package %s" % path, 2)
  485. else:
  486. self.message("Adding Python module %s" % path, 2)
  487. abspath = pathjoin(self.bundlepath, path)
  488. makedirs(os.path.dirname(abspath))
  489. writePyc(code, abspath)
  490. def stripBinaries(self):
  491. if not os.path.exists(STRIP_EXEC):
  492. self.message("Error: can't strip binaries: no strip program at "
  493. "%s" % STRIP_EXEC, 0)
  494. else:
  495. import stat
  496. self.message("Stripping binaries", 1)
  497. def walk(top):
  498. for name in os.listdir(top):
  499. path = pathjoin(top, name)
  500. if os.path.islink(path):
  501. continue
  502. if os.path.isdir(path):
  503. walk(path)
  504. else:
  505. mod = os.stat(path)[stat.ST_MODE]
  506. if not (mod & 0100):
  507. continue
  508. relpath = path[len(self.bundlepath):]
  509. self.message("Stripping %s" % relpath, 2)
  510. inf, outf = os.popen4("%s -S \"%s\"" %
  511. (STRIP_EXEC, path))
  512. output = outf.read().strip()
  513. if output:
  514. # usually not a real problem, like when we're
  515. # trying to strip a script
  516. self.message("Problem stripping %s:" % relpath, 3)
  517. self.message(output, 3)
  518. walk(self.bundlepath)
  519. def findDependencies(self):
  520. self.message("Finding module dependencies", 1)
  521. import modulefinder
  522. mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
  523. if self.use_zipimport:
  524. # zipimport imports zlib, must add it manually
  525. mf.import_hook("zlib")
  526. # manually add our own site.py
  527. site = mf.add_module("site")
  528. site.__code__ = self._getSiteCode()
  529. mf.scan_code(site.__code__, site)
  530. # warnings.py gets imported implicitly from C
  531. mf.import_hook("warnings")
  532. includeModules = self.includeModules[:]
  533. for name in self.includePackages:
  534. includeModules.extend(findPackageContents(name).keys())
  535. for name in includeModules:
  536. try:
  537. mf.import_hook(name)
  538. except ImportError:
  539. self.missingModules.append(name)
  540. mf.run_script(self.mainprogram)
  541. modules = mf.modules.items()
  542. modules.sort()
  543. for name, mod in modules:
  544. path = mod.__file__
  545. if path and self.semi_standalone:
  546. # skip the standard library
  547. if path.startswith(LIB) and not path.startswith(SITE_PACKAGES):
  548. continue
  549. if path and mod.__code__ is None:
  550. # C extension
  551. filename = os.path.basename(path)
  552. pathitems = name.split(".")[:-1] + [filename]
  553. dstpath = pathjoin(*pathitems)
  554. if self.use_zipimport:
  555. if name != "zlib":
  556. # neatly pack all extension modules in a subdirectory,
  557. # except zlib, since it's necessary for bootstrapping.
  558. dstpath = pathjoin("ExtensionModules", dstpath)
  559. # Python modules are stored in a Zip archive, but put
  560. # extensions in Contents/Resources/. Add a tiny "loader"
  561. # program in the Zip archive. Due to Thomas Heller.
  562. source = EXT_LOADER % {"name": name, "filename": dstpath}
  563. code = compile(source, "<dynloader for %s>" % name, "exec")
  564. mod.__code__ = code
  565. self.files.append((path, pathjoin("Contents", "Resources", dstpath)))
  566. if mod.__code__ is not None:
  567. ispkg = mod.__path__ is not None
  568. if not self.use_zipimport or name != "site":
  569. # Our site.py is doing the bootstrapping, so we must
  570. # include a real .pyc file if self.use_zipimport is True.
  571. self.pymodules.append((name, mod.__code__, ispkg))
  572. if hasattr(mf, "any_missing_maybe"):
  573. missing, maybe = mf.any_missing_maybe()
  574. else:
  575. missing = mf.any_missing()
  576. maybe = []
  577. self.missingModules.extend(missing)
  578. self.maybeMissingModules.extend(maybe)
  579. def reportMissing(self):
  580. missing = [name for name in self.missingModules
  581. if name not in MAYMISS_MODULES]
  582. if self.maybeMissingModules:
  583. maybe = self.maybeMissingModules
  584. else:
  585. maybe = [name for name in missing if "." in name]
  586. missing = [name for name in missing if "." not in name]
  587. missing.sort()
  588. maybe.sort()
  589. if maybe:
  590. self.message("Warning: couldn't find the following submodules:", 1)
  591. self.message(" (Note that these could be false alarms -- "
  592. "it's not always", 1)
  593. self.message(" possible to distinguish between \"from package "
  594. "import submodule\" ", 1)
  595. self.message(" and \"from package import name\")", 1)
  596. for name in maybe:
  597. self.message(" ? " + name, 1)
  598. if missing:
  599. self.message("Warning: couldn't find the following modules:", 1)
  600. for name in missing:
  601. self.message(" ? " + name, 1)
  602. def report(self):
  603. # XXX something decent
  604. import pprint
  605. pprint.pprint(self.__dict__)
  606. if self.standalone or self.semi_standalone:
  607. self.reportMissing()
  608. #
  609. # Utilities.
  610. #
  611. SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
  612. identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
  613. def findPackageContents(name, searchpath=None):
  614. head = name.split(".")[-1]
  615. if identifierRE.match(head) is None:
  616. return {}
  617. try:
  618. fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
  619. except ImportError:
  620. return {}
  621. modules = {name: None}
  622. if tp == imp.PKG_DIRECTORY and path:
  623. files = os.listdir(path)
  624. for sub in files:
  625. sub, ext = os.path.splitext(sub)
  626. fullname = name + "." + sub
  627. if sub != "__init__" and fullname not in modules:
  628. modules.update(findPackageContents(fullname, [path]))
  629. return modules
  630. def writePyc(code, path):
  631. f = open(path, "wb")
  632. f.write(MAGIC)
  633. f.write("\0" * 4) # don't bother about a time stamp
  634. marshal.dump(code, f)
  635. f.close()
  636. def copy(src, dst, mkdirs=0):
  637. """Copy a file or a directory."""
  638. if mkdirs:
  639. makedirs(os.path.dirname(dst))
  640. if os.path.isdir(src):
  641. shutil.copytree(src, dst, symlinks=1)
  642. else:
  643. shutil.copy2(src, dst)
  644. def copytodir(src, dstdir):
  645. """Copy a file or a directory to an existing directory."""
  646. dst = pathjoin(dstdir, os.path.basename(src))
  647. copy(src, dst)
  648. def makedirs(dir):
  649. """Make all directories leading up to 'dir' including the leaf
  650. directory. Don't moan if any path element already exists."""
  651. try:
  652. os.makedirs(dir)
  653. except OSError, why:
  654. if why.errno != errno.EEXIST:
  655. raise
  656. def symlink(src, dst, mkdirs=0):
  657. """Copy a file or a directory."""
  658. if not os.path.exists(src):
  659. raise IOError, "No such file or directory: '%s'" % src
  660. if mkdirs:
  661. makedirs(os.path.dirname(dst))
  662. os.symlink(os.path.abspath(src), dst)
  663. def pathjoin(*args):
  664. """Safe wrapper for os.path.join: asserts that all but the first
  665. argument are relative paths."""
  666. for seg in args[1:]:
  667. assert seg[0] != "/"
  668. return os.path.join(*args)
  669. cmdline_doc = """\
  670. Usage:
  671. python bundlebuilder.py [options] command
  672. python mybuildscript.py [options] command
  673. Commands:
  674. build build the application
  675. report print a report
  676. Options:
  677. -b, --builddir=DIR the build directory; defaults to "build"
  678. -n, --name=NAME application name
  679. -r, --resource=FILE extra file or folder to be copied to Resources
  680. -f, --file=SRC:DST extra file or folder to be copied into the bundle;
  681. DST must be a path relative to the bundle root
  682. -e, --executable=FILE the executable to be used
  683. -m, --mainprogram=FILE the Python main program
  684. -a, --argv add a wrapper main program to create sys.argv
  685. -p, --plist=FILE .plist file (default: generate one)
  686. --nib=NAME main nib name
  687. -c, --creator=CCCC 4-char creator code (default: '????')
  688. --iconfile=FILE filename of the icon (an .icns file) to be used
  689. as the Finder icon
  690. --bundle-id=ID the CFBundleIdentifier, in reverse-dns format
  691. (eg. org.python.BuildApplet; this is used for
  692. the preferences file name)
  693. -l, --link symlink files/folder instead of copying them
  694. --link-exec symlink the executable instead of copying it
  695. --standalone build a standalone application, which is fully
  696. independent of a Python installation
  697. --semi-standalone build a standalone application, which depends on
  698. an installed Python, yet includes all third-party
  699. modules.
  700. --no-zipimport Do not copy code into a zip file
  701. --python=FILE Python to use in #! line in stead of current Python
  702. --lib=FILE shared library or framework to be copied into
  703. the bundle
  704. -x, --exclude=MODULE exclude module (with --(semi-)standalone)
  705. -i, --include=MODULE include module (with --(semi-)standalone)
  706. --package=PACKAGE include a whole package (with --(semi-)standalone)
  707. --strip strip binaries (remove debug info)
  708. -v, --verbose increase verbosity level
  709. -q, --quiet decrease verbosity level
  710. -h, --help print this message
  711. """
  712. def usage(msg=None):
  713. if msg:
  714. print msg
  715. print cmdline_doc
  716. sys.exit(1)
  717. def main(builder=None):
  718. if builder is None:
  719. builder = AppBuilder(verbosity=1)
  720. shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
  721. longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
  722. "mainprogram=", "creator=", "nib=", "plist=", "link",
  723. "link-exec", "help", "verbose", "quiet", "argv", "standalone",
  724. "exclude=", "include=", "package=", "strip", "iconfile=",
  725. "lib=", "python=", "semi-standalone", "bundle-id=", "destroot="
  726. "no-zipimport"
  727. )
  728. try:
  729. options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
  730. except getopt.error:
  731. usage()
  732. for opt, arg in options:
  733. if opt in ('-b', '--builddir'):
  734. builder.builddir = arg
  735. elif opt in ('-n', '--name'):
  736. builder.name = arg
  737. elif opt in ('-r', '--resource'):
  738. builder.resources.append(os.path.normpath(arg))
  739. elif opt in ('-f', '--file'):
  740. srcdst = arg.split(':')
  741. if len(srcdst) != 2:
  742. usage("-f or --file argument must be two paths, "
  743. "separated by a colon")
  744. builder.files.append(srcdst)
  745. elif opt in ('-e', '--executable'):
  746. builder.executable = arg
  747. elif opt in ('-m', '--mainprogram'):
  748. builder.mainprogram = arg
  749. elif opt in ('-a', '--argv'):
  750. builder.argv_emulation = 1
  751. elif opt in ('-c', '--creator'):
  752. builder.creator = arg
  753. elif opt == '--bundle-id':
  754. builder.bundle_id = arg
  755. elif opt == '--iconfile':
  756. builder.iconfile = arg
  757. elif opt == "--lib":
  758. builder.libs.append(os.path.normpath(arg))
  759. elif opt == "--nib":
  760. builder.nibname = arg
  761. elif opt in ('-p', '--plist'):
  762. builder.plist = Plist.fromFile(arg)
  763. elif opt in ('-l', '--link'):
  764. builder.symlink = 1
  765. elif opt == '--link-exec':
  766. builder.symlink_exec = 1
  767. elif opt in ('-h', '--help'):
  768. usage()
  769. elif opt in ('-v', '--verbose'):
  770. builder.verbosity += 1
  771. elif opt in ('-q', '--quiet'):
  772. builder.verbosity -= 1
  773. elif opt == '--standalone':
  774. builder.standalone = 1
  775. elif opt == '--semi-standalone':
  776. builder.semi_standalone = 1
  777. elif opt == '--python':
  778. builder.python = arg
  779. elif opt in ('-x', '--exclude'):
  780. builder.excludeModules.append(arg)
  781. elif opt in ('-i', '--include'):
  782. builder.includeModules.append(arg)
  783. elif opt == '--package':
  784. builder.includePackages.append(arg)
  785. elif opt == '--strip':
  786. builder.strip = 1
  787. elif opt == '--destroot':
  788. builder.destroot = arg
  789. elif opt == '--no-zipimport':
  790. builder.use_zipimport = False
  791. if len(args) != 1:
  792. usage("Must specify one command ('build', 'report' or 'help')")
  793. command = args[0]
  794. if command == "build":
  795. builder.setup()
  796. builder.build()
  797. elif command == "report":
  798. builder.setup()
  799. builder.report()
  800. elif command == "help":
  801. usage()
  802. else:
  803. usage("Unknown command '%s'" % command)
  804. def buildapp(**kwargs):
  805. builder = AppBuilder(**kwargs)
  806. main(builder)
  807. if __name__ == "__main__":
  808. main()