You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

934 lines
33 KiB

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