osx.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2021, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. import os
  12. import plistlib
  13. import shutil
  14. from PyInstaller.compat import is_darwin
  15. from PyInstaller.building.api import EXE, COLLECT
  16. from PyInstaller.building.datastruct import Target, TOC, logger
  17. from PyInstaller.building.utils import _check_path_overlap, _rmtree, \
  18. add_suffix_to_extension, checkCache
  19. if is_darwin:
  20. import PyInstaller.utils.osx as osxutils
  21. class BUNDLE(Target):
  22. def __init__(self, *args, **kws):
  23. from PyInstaller.config import CONF
  24. # BUNDLE only has a sense under Mac OS X, it's a noop on other platforms
  25. if not is_darwin:
  26. return
  27. # get a path to a .icns icon for the app bundle.
  28. self.icon = kws.get('icon')
  29. if not self.icon:
  30. # --icon not specified; use the default in the pyinstaller folder
  31. self.icon = os.path.join(os.path.dirname(os.path.dirname(__file__)),
  32. 'bootloader', 'images', 'icon-windowed.icns')
  33. else:
  34. # user gave an --icon=path. If it is relative, make it
  35. # relative to the spec file location.
  36. if not os.path.isabs(self.icon):
  37. self.icon = os.path.join(CONF['specpath'], self.icon)
  38. # ensure icon path is absolute
  39. self.icon = os.path.abspath(self.icon)
  40. Target.__init__(self)
  41. # .app bundle is created in DISTPATH.
  42. self.name = kws.get('name', None)
  43. base_name = os.path.basename(self.name)
  44. self.name = os.path.join(CONF['distpath'], base_name)
  45. self.appname = os.path.splitext(base_name)[0]
  46. self.version = kws.get("version", "0.0.0")
  47. self.toc = TOC()
  48. self.strip = False
  49. self.upx = False
  50. self.console = True
  51. self.target_arch = None
  52. self.codesign_identity = None
  53. self.entitlements_file = None
  54. # .app bundle identifier for Code Signing
  55. self.bundle_identifier = kws.get('bundle_identifier')
  56. if not self.bundle_identifier:
  57. # Fallback to appname.
  58. self.bundle_identifier = self.appname
  59. self.info_plist = kws.get('info_plist', None)
  60. for arg in args:
  61. if isinstance(arg, EXE):
  62. self.toc.append((os.path.basename(arg.name), arg.name, arg.typ))
  63. self.toc.extend(arg.dependencies)
  64. self.strip = arg.strip
  65. self.upx = arg.upx
  66. self.upx_exclude = arg.upx_exclude
  67. self.console = arg.console
  68. self.target_arch = arg.target_arch
  69. self.codesign_identity = arg.codesign_identity
  70. self.entitlements_file = arg.entitlements_file
  71. elif isinstance(arg, TOC):
  72. self.toc.extend(arg)
  73. # TOC doesn't have a strip or upx attribute, so there is no way for us to
  74. # tell which cache we should draw from.
  75. elif isinstance(arg, COLLECT):
  76. self.toc.extend(arg.toc)
  77. self.strip = arg.strip_binaries
  78. self.upx = arg.upx_binaries
  79. self.upx_exclude = arg.upx_exclude
  80. self.console = arg.console
  81. self.target_arch = arg.target_arch
  82. self.codesign_identity = arg.codesign_identity
  83. self.entitlements_file = arg.entitlements_file
  84. else:
  85. logger.info("unsupported entry %s", arg.__class__.__name__)
  86. # Now, find values for app filepath (name), app name (appname), and name
  87. # of the actual executable (exename) from the first EXECUTABLE item in
  88. # toc, which might have come from a COLLECT too (not from an EXE).
  89. for inm, name, typ in self.toc:
  90. if typ == "EXECUTABLE":
  91. self.exename = name
  92. break
  93. self.__postinit__()
  94. _GUTS = (
  95. # BUNDLE always builds, just want the toc to be written out
  96. ('toc', None),
  97. )
  98. def _check_guts(self, data, last_build):
  99. # BUNDLE always needs to be executed, since it will clean the output
  100. # directory anyway to make sure there is no existing cruft accumulating
  101. return 1
  102. def assemble(self):
  103. if _check_path_overlap(self.name) and os.path.isdir(self.name):
  104. _rmtree(self.name)
  105. logger.info("Building BUNDLE %s", self.tocbasename)
  106. # Create a minimal Mac bundle structure
  107. os.makedirs(os.path.join(self.name, "Contents", "MacOS"))
  108. os.makedirs(os.path.join(self.name, "Contents", "Resources"))
  109. os.makedirs(os.path.join(self.name, "Contents", "Frameworks"))
  110. # Copy icns icon to Resources directory.
  111. if os.path.exists(self.icon):
  112. shutil.copy(self.icon, os.path.join(self.name, 'Contents', 'Resources'))
  113. else:
  114. logger.warning("icon not found %s", self.icon)
  115. # Key/values for a minimal Info.plist file
  116. info_plist_dict = {"CFBundleDisplayName": self.appname,
  117. "CFBundleName": self.appname,
  118. # Required by 'codesign' utility.
  119. # The value for CFBundleIdentifier is used as the default unique
  120. # name of your program for Code Signing purposes.
  121. # It even identifies the APP for access to restricted OS X areas
  122. # like Keychain.
  123. #
  124. # The identifier used for signing must be globally unique. The usal
  125. # form for this identifier is a hierarchical name in reverse DNS
  126. # notation, starting with the toplevel domain, followed by the
  127. # company name, followed by the department within the company, and
  128. # ending with the product name. Usually in the form:
  129. # com.mycompany.department.appname
  130. # Cli option --osx-bundle-identifier sets this value.
  131. "CFBundleIdentifier": self.bundle_identifier,
  132. "CFBundleExecutable":
  133. os.path.basename(self.exename),
  134. "CFBundleIconFile": os.path.basename(self.icon),
  135. "CFBundleInfoDictionaryVersion": "6.0",
  136. "CFBundlePackageType": "APPL",
  137. "CFBundleShortVersionString": self.version,
  138. }
  139. # Set some default values.
  140. # But they still can be overwritten by the user.
  141. if self.console:
  142. # Setting EXE console=True implies LSBackgroundOnly=True.
  143. info_plist_dict['LSBackgroundOnly'] = True
  144. else:
  145. # Let's use high resolution by default.
  146. info_plist_dict['NSHighResolutionCapable'] = True
  147. # Merge info_plist settings from spec file
  148. if isinstance(self.info_plist, dict) and self.info_plist:
  149. info_plist_dict.update(self.info_plist)
  150. plist_filename = os.path.join(self.name, "Contents", "Info.plist")
  151. with open(plist_filename, "wb") as plist_fh:
  152. plistlib.dump(info_plist_dict, plist_fh)
  153. links = []
  154. _QT_BASE_PATH = {'PySide2', 'PySide6', 'PyQt5', 'PySide6'}
  155. for inm, fnm, typ in self.toc:
  156. # Adjust name for extensions, if applicable
  157. inm, fnm, typ = add_suffix_to_extension(inm, fnm, typ)
  158. # Copy files from cache. This ensures that are used files with relative
  159. # paths to dynamic library dependencies (@executable_path)
  160. base_path = inm.split('/', 1)[0]
  161. if typ in ('EXTENSION', 'BINARY'):
  162. fnm = checkCache(fnm, strip=self.strip, upx=self.upx,
  163. upx_exclude=self.upx_exclude, dist_nm=inm,
  164. target_arch=self.target_arch,
  165. codesign_identity=self.codesign_identity,
  166. entitlements_file=self.entitlements_file)
  167. # Add most data files to a list for symlinking later.
  168. if typ == 'DATA' and base_path not in _QT_BASE_PATH:
  169. links.append((inm, fnm))
  170. else:
  171. tofnm = os.path.join(self.name, "Contents", "MacOS", inm)
  172. todir = os.path.dirname(tofnm)
  173. if not os.path.exists(todir):
  174. os.makedirs(todir)
  175. if os.path.isdir(fnm):
  176. # beacuse shutil.copy2() is the default copy function
  177. # for shutil.copytree, this will also copy file metadata
  178. shutil.copytree(fnm, tofnm)
  179. else:
  180. shutil.copy(fnm, tofnm)
  181. logger.info('Moving BUNDLE data files to Resource directory')
  182. # Mac OS X Code Signing does not work when .app bundle contains
  183. # data files in dir ./Contents/MacOS.
  184. #
  185. # Put all data files in ./Resources and create symlinks in ./MacOS.
  186. bin_dir = os.path.join(self.name, 'Contents', 'MacOS')
  187. res_dir = os.path.join(self.name, 'Contents', 'Resources')
  188. for inm, fnm in links:
  189. tofnm = os.path.join(res_dir, inm)
  190. todir = os.path.dirname(tofnm)
  191. if not os.path.exists(todir):
  192. os.makedirs(todir)
  193. if os.path.isdir(fnm):
  194. # beacuse shutil.copy2() is the default copy function
  195. # for shutil.copytree, this will also copy file metadata
  196. shutil.copytree(fnm, tofnm)
  197. else:
  198. shutil.copy(fnm, tofnm)
  199. base_path = os.path.split(inm)[0]
  200. if base_path:
  201. if not os.path.exists(os.path.join(bin_dir, inm)):
  202. path = ''
  203. for part in iter(base_path.split(os.path.sep)):
  204. # Build path from previous path and the next part of the base path
  205. path = os.path.join(path, part)
  206. try:
  207. relative_source_path = os.path.relpath(os.path.join(res_dir, path),
  208. os.path.split(os.path.join(bin_dir, path))[0])
  209. dest_path = os.path.join(bin_dir, path)
  210. os.symlink(relative_source_path, dest_path)
  211. break
  212. except FileExistsError:
  213. pass
  214. if not os.path.exists(os.path.join(bin_dir, inm)):
  215. relative_source_path = os.path.relpath(os.path.join(res_dir, inm),
  216. os.path.split(os.path.join(bin_dir, inm))[0])
  217. dest_path = os.path.join(bin_dir, inm)
  218. os.symlink(relative_source_path, dest_path)
  219. else: # If path is empty, e.g., a top level file, try to just symlink the file
  220. os.symlink(os.path.relpath(os.path.join(res_dir, inm),
  221. os.path.split(os.path.join(bin_dir, inm))[0]),
  222. os.path.join(bin_dir, inm))
  223. # Sign the bundle
  224. logger.info('Signing the BUNDLE...')
  225. try:
  226. osxutils.sign_binary(self.name, self.codesign_identity,
  227. self.entitlements_file, deep=True)
  228. except Exception as e:
  229. logger.warning("Error while signing the bundle: %s", e)
  230. logger.warning("You will need to sign the bundle manually!")
  231. logger.info("Building BUNDLE %s completed successfully.",
  232. self.tocbasename)