osx.py 12 KB

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