gyp-mac-tool 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. #!/usr/bin/env python
  2. # Generated by gyp. Do not edit.
  3. # Copyright (c) 2012 Google Inc. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """Utility functions to perform Xcode-style build steps.
  7. These functions are executed via gyp-mac-tool when using the Makefile generator.
  8. """
  9. from __future__ import print_function
  10. import fcntl
  11. import fnmatch
  12. import glob
  13. import json
  14. import os
  15. import plistlib
  16. import re
  17. import shutil
  18. import string
  19. import subprocess
  20. import sys
  21. import tempfile
  22. PY3 = bytes != str
  23. def main(args):
  24. executor = MacTool()
  25. exit_code = executor.Dispatch(args)
  26. if exit_code is not None:
  27. sys.exit(exit_code)
  28. class MacTool(object):
  29. """This class performs all the Mac tooling steps. The methods can either be
  30. executed directly, or dispatched from an argument list."""
  31. def Dispatch(self, args):
  32. """Dispatches a string command to a method."""
  33. if len(args) < 1:
  34. raise Exception("Not enough arguments")
  35. method = "Exec%s" % self._CommandifyName(args[0])
  36. return getattr(self, method)(*args[1:])
  37. def _CommandifyName(self, name_string):
  38. """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
  39. return name_string.title().replace('-', '')
  40. def ExecCopyBundleResource(self, source, dest, convert_to_binary):
  41. """Copies a resource file to the bundle/Resources directory, performing any
  42. necessary compilation on each resource."""
  43. extension = os.path.splitext(source)[1].lower()
  44. if os.path.isdir(source):
  45. # Copy tree.
  46. # TODO(thakis): This copies file attributes like mtime, while the
  47. # single-file branch below doesn't. This should probably be changed to
  48. # be consistent with the single-file branch.
  49. if os.path.exists(dest):
  50. shutil.rmtree(dest)
  51. shutil.copytree(source, dest)
  52. elif extension == '.xib':
  53. return self._CopyXIBFile(source, dest)
  54. elif extension == '.storyboard':
  55. return self._CopyXIBFile(source, dest)
  56. elif extension == '.strings':
  57. self._CopyStringsFile(source, dest, convert_to_binary)
  58. else:
  59. shutil.copy(source, dest)
  60. def _CopyXIBFile(self, source, dest):
  61. """Compiles a XIB file with ibtool into a binary plist in the bundle."""
  62. # ibtool sometimes crashes with relative paths. See crbug.com/314728.
  63. base = os.path.dirname(os.path.realpath(__file__))
  64. if os.path.relpath(source):
  65. source = os.path.join(base, source)
  66. if os.path.relpath(dest):
  67. dest = os.path.join(base, dest)
  68. args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices',
  69. '--output-format', 'human-readable-text', '--compile', dest, source]
  70. ibtool_section_re = re.compile(r'/\*.*\*/')
  71. ibtool_re = re.compile(r'.*note:.*is clipping its content')
  72. ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE)
  73. current_section_header = None
  74. for line in ibtoolout.stdout:
  75. if ibtool_section_re.match(line):
  76. current_section_header = line
  77. elif not ibtool_re.match(line):
  78. if current_section_header:
  79. sys.stdout.write(current_section_header)
  80. current_section_header = None
  81. sys.stdout.write(line)
  82. return ibtoolout.returncode
  83. def _ConvertToBinary(self, dest):
  84. subprocess.check_call([
  85. 'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest])
  86. def _CopyStringsFile(self, source, dest, convert_to_binary):
  87. """Copies a .strings file using iconv to reconvert the input into UTF-16."""
  88. input_code = self._DetectInputEncoding(source) or "UTF-8"
  89. # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
  90. # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
  91. # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
  92. # semicolon in dictionary.
  93. # on invalid files. Do the same kind of validation.
  94. import CoreFoundation
  95. s = open(source, 'rb').read()
  96. d = CoreFoundation.CFDataCreate(None, s, len(s))
  97. _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
  98. if error:
  99. return
  100. fp = open(dest, 'wb')
  101. fp.write(s.decode(input_code).encode('UTF-16'))
  102. fp.close()
  103. if convert_to_binary == 'True':
  104. self._ConvertToBinary(dest)
  105. def _DetectInputEncoding(self, file_name):
  106. """Reads the first few bytes from file_name and tries to guess the text
  107. encoding. Returns None as a guess if it can't detect it."""
  108. fp = open(file_name, 'rb')
  109. try:
  110. header = fp.read(3)
  111. except Exception:
  112. fp.close()
  113. return None
  114. fp.close()
  115. if header.startswith("\xFE\xFF"):
  116. return "UTF-16"
  117. elif header.startswith("\xFF\xFE"):
  118. return "UTF-16"
  119. elif header.startswith("\xEF\xBB\xBF"):
  120. return "UTF-8"
  121. else:
  122. return None
  123. def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys):
  124. """Copies the |source| Info.plist to the destination directory |dest|."""
  125. # Read the source Info.plist into memory.
  126. fd = open(source, 'r')
  127. lines = fd.read()
  128. fd.close()
  129. # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
  130. plist = plistlib.readPlistFromString(lines)
  131. if keys:
  132. plist = dict(plist.items() + json.loads(keys[0]).items())
  133. lines = plistlib.writePlistToString(plist)
  134. # Go through all the environment variables and replace them as variables in
  135. # the file.
  136. IDENT_RE = re.compile(r'[/\s]')
  137. for key in os.environ:
  138. if key.startswith('_'):
  139. continue
  140. evar = '${%s}' % key
  141. evalue = os.environ[key]
  142. lines = string.replace(lines, evar, evalue)
  143. # Xcode supports various suffices on environment variables, which are
  144. # all undocumented. :rfc1034identifier is used in the standard project
  145. # template these days, and :identifier was used earlier. They are used to
  146. # convert non-url characters into things that look like valid urls --
  147. # except that the replacement character for :identifier, '_' isn't valid
  148. # in a URL either -- oops, hence :rfc1034identifier was born.
  149. evar = '${%s:identifier}' % key
  150. evalue = IDENT_RE.sub('_', os.environ[key])
  151. lines = string.replace(lines, evar, evalue)
  152. evar = '${%s:rfc1034identifier}' % key
  153. evalue = IDENT_RE.sub('-', os.environ[key])
  154. lines = string.replace(lines, evar, evalue)
  155. # Remove any keys with values that haven't been replaced.
  156. lines = lines.split('\n')
  157. for i in range(len(lines)):
  158. if lines[i].strip().startswith("<string>${"):
  159. lines[i] = None
  160. lines[i - 1] = None
  161. lines = '\n'.join(filter(lambda x: x is not None, lines))
  162. # Write out the file with variables replaced.
  163. fd = open(dest, 'w')
  164. fd.write(lines)
  165. fd.close()
  166. # Now write out PkgInfo file now that the Info.plist file has been
  167. # "compiled".
  168. self._WritePkgInfo(dest)
  169. if convert_to_binary == 'True':
  170. self._ConvertToBinary(dest)
  171. def _WritePkgInfo(self, info_plist):
  172. """This writes the PkgInfo file from the data stored in Info.plist."""
  173. plist = plistlib.readPlist(info_plist)
  174. if not plist:
  175. return
  176. # Only create PkgInfo for executable types.
  177. package_type = plist['CFBundlePackageType']
  178. if package_type != 'APPL':
  179. return
  180. # The format of PkgInfo is eight characters, representing the bundle type
  181. # and bundle signature, each four characters. If that is missing, four
  182. # '?' characters are used instead.
  183. signature_code = plist.get('CFBundleSignature', '????')
  184. if len(signature_code) != 4: # Wrong length resets everything, too.
  185. signature_code = '?' * 4
  186. dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo')
  187. fp = open(dest, 'w')
  188. fp.write('%s%s' % (package_type, signature_code))
  189. fp.close()
  190. def ExecFlock(self, lockfile, *cmd_list):
  191. """Emulates the most basic behavior of Linux's flock(1)."""
  192. # Rely on exception handling to report errors.
  193. fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
  194. fcntl.flock(fd, fcntl.LOCK_EX)
  195. return subprocess.call(cmd_list)
  196. def ExecFilterLibtool(self, *cmd_list):
  197. """Calls libtool and filters out '/path/to/libtool: file: foo.o has no
  198. symbols'."""
  199. libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$')
  200. libtool_re5 = re.compile(
  201. r'^.*libtool: warning for library: ' +
  202. r'.* the table of contents is empty ' +
  203. r'\(no object file members in the library define global symbols\)$')
  204. env = os.environ.copy()
  205. # Ref:
  206. # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c
  207. # The problem with this flag is that it resets the file mtime on the file to
  208. # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone.
  209. env['ZERO_AR_DATE'] = '1'
  210. libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env)
  211. _, err = libtoolout.communicate()
  212. if PY3:
  213. err = err.decode('utf-8')
  214. for line in err.splitlines():
  215. if not libtool_re.match(line) and not libtool_re5.match(line):
  216. print(line, file=sys.stderr)
  217. # Unconditionally touch the output .a file on the command line if present
  218. # and the command succeeded. A bit hacky.
  219. if not libtoolout.returncode:
  220. for i in range(len(cmd_list) - 1):
  221. if cmd_list[i] == "-o" and cmd_list[i+1].endswith('.a'):
  222. os.utime(cmd_list[i+1], None)
  223. break
  224. return libtoolout.returncode
  225. def ExecPackageFramework(self, framework, version):
  226. """Takes a path to Something.framework and the Current version of that and
  227. sets up all the symlinks."""
  228. # Find the name of the binary based on the part before the ".framework".
  229. binary = os.path.basename(framework).split('.')[0]
  230. CURRENT = 'Current'
  231. RESOURCES = 'Resources'
  232. VERSIONS = 'Versions'
  233. if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
  234. # Binary-less frameworks don't seem to contain symlinks (see e.g.
  235. # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
  236. return
  237. # Move into the framework directory to set the symlinks correctly.
  238. pwd = os.getcwd()
  239. os.chdir(framework)
  240. # Set up the Current version.
  241. self._Relink(version, os.path.join(VERSIONS, CURRENT))
  242. # Set up the root symlinks.
  243. self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
  244. self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
  245. # Back to where we were before!
  246. os.chdir(pwd)
  247. def _Relink(self, dest, link):
  248. """Creates a symlink to |dest| named |link|. If |link| already exists,
  249. it is overwritten."""
  250. if os.path.lexists(link):
  251. os.remove(link)
  252. os.symlink(dest, link)
  253. def ExecCompileXcassets(self, keys, *inputs):
  254. """Compiles multiple .xcassets files into a single .car file.
  255. This invokes 'actool' to compile all the inputs .xcassets files. The
  256. |keys| arguments is a json-encoded dictionary of extra arguments to
  257. pass to 'actool' when the asset catalogs contains an application icon
  258. or a launch image.
  259. Note that 'actool' does not create the Assets.car file if the asset
  260. catalogs does not contains imageset.
  261. """
  262. command_line = [
  263. 'xcrun', 'actool', '--output-format', 'human-readable-text',
  264. '--compress-pngs', '--notices', '--warnings', '--errors',
  265. ]
  266. is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ
  267. if is_iphone_target:
  268. platform = os.environ['CONFIGURATION'].split('-')[-1]
  269. if platform not in ('iphoneos', 'iphonesimulator'):
  270. platform = 'iphonesimulator'
  271. command_line.extend([
  272. '--platform', platform, '--target-device', 'iphone',
  273. '--target-device', 'ipad', '--minimum-deployment-target',
  274. os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile',
  275. os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']),
  276. ])
  277. else:
  278. command_line.extend([
  279. '--platform', 'macosx', '--target-device', 'mac',
  280. '--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'],
  281. '--compile',
  282. os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']),
  283. ])
  284. if keys:
  285. keys = json.loads(keys)
  286. for key, value in keys.items():
  287. arg_name = '--' + key
  288. if isinstance(value, bool):
  289. if value:
  290. command_line.append(arg_name)
  291. elif isinstance(value, list):
  292. for v in value:
  293. command_line.append(arg_name)
  294. command_line.append(str(v))
  295. else:
  296. command_line.append(arg_name)
  297. command_line.append(str(value))
  298. # Note: actool crashes if inputs path are relative, so use os.path.abspath
  299. # to get absolute path name for inputs.
  300. command_line.extend(map(os.path.abspath, inputs))
  301. subprocess.check_call(command_line)
  302. def ExecMergeInfoPlist(self, output, *inputs):
  303. """Merge multiple .plist files into a single .plist file."""
  304. merged_plist = {}
  305. for path in inputs:
  306. plist = self._LoadPlistMaybeBinary(path)
  307. self._MergePlist(merged_plist, plist)
  308. plistlib.writePlist(merged_plist, output)
  309. def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning):
  310. """Code sign a bundle.
  311. This function tries to code sign an iOS bundle, following the same
  312. algorithm as Xcode:
  313. 1. copy ResourceRules.plist from the user or the SDK into the bundle,
  314. 2. pick the provisioning profile that best match the bundle identifier,
  315. and copy it into the bundle as embedded.mobileprovision,
  316. 3. copy Entitlements.plist from user or SDK next to the bundle,
  317. 4. code sign the bundle.
  318. """
  319. resource_rules_path = self._InstallResourceRules(resource_rules)
  320. substitutions, overrides = self._InstallProvisioningProfile(
  321. provisioning, self._GetCFBundleIdentifier())
  322. entitlements_path = self._InstallEntitlements(
  323. entitlements, substitutions, overrides)
  324. subprocess.check_call([
  325. 'codesign', '--force', '--sign', key, '--resource-rules',
  326. resource_rules_path, '--entitlements', entitlements_path,
  327. os.path.join(
  328. os.environ['TARGET_BUILD_DIR'],
  329. os.environ['FULL_PRODUCT_NAME'])])
  330. def _InstallResourceRules(self, resource_rules):
  331. """Installs ResourceRules.plist from user or SDK into the bundle.
  332. Args:
  333. resource_rules: string, optional, path to the ResourceRules.plist file
  334. to use, default to "${SDKROOT}/ResourceRules.plist"
  335. Returns:
  336. Path to the copy of ResourceRules.plist into the bundle.
  337. """
  338. source_path = resource_rules
  339. target_path = os.path.join(
  340. os.environ['BUILT_PRODUCTS_DIR'],
  341. os.environ['CONTENTS_FOLDER_PATH'],
  342. 'ResourceRules.plist')
  343. if not source_path:
  344. source_path = os.path.join(
  345. os.environ['SDKROOT'], 'ResourceRules.plist')
  346. shutil.copy2(source_path, target_path)
  347. return target_path
  348. def _InstallProvisioningProfile(self, profile, bundle_identifier):
  349. """Installs embedded.mobileprovision into the bundle.
  350. Args:
  351. profile: string, optional, short name of the .mobileprovision file
  352. to use, if empty or the file is missing, the best file installed
  353. will be used
  354. bundle_identifier: string, value of CFBundleIdentifier from Info.plist
  355. Returns:
  356. A tuple containing two dictionary: variables substitutions and values
  357. to overrides when generating the entitlements file.
  358. """
  359. source_path, provisioning_data, team_id = self._FindProvisioningProfile(
  360. profile, bundle_identifier)
  361. target_path = os.path.join(
  362. os.environ['BUILT_PRODUCTS_DIR'],
  363. os.environ['CONTENTS_FOLDER_PATH'],
  364. 'embedded.mobileprovision')
  365. shutil.copy2(source_path, target_path)
  366. substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.')
  367. return substitutions, provisioning_data['Entitlements']
  368. def _FindProvisioningProfile(self, profile, bundle_identifier):
  369. """Finds the .mobileprovision file to use for signing the bundle.
  370. Checks all the installed provisioning profiles (or if the user specified
  371. the PROVISIONING_PROFILE variable, only consult it) and select the most
  372. specific that correspond to the bundle identifier.
  373. Args:
  374. profile: string, optional, short name of the .mobileprovision file
  375. to use, if empty or the file is missing, the best file installed
  376. will be used
  377. bundle_identifier: string, value of CFBundleIdentifier from Info.plist
  378. Returns:
  379. A tuple of the path to the selected provisioning profile, the data of
  380. the embedded plist in the provisioning profile and the team identifier
  381. to use for code signing.
  382. Raises:
  383. SystemExit: if no .mobileprovision can be used to sign the bundle.
  384. """
  385. profiles_dir = os.path.join(
  386. os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles')
  387. if not os.path.isdir(profiles_dir):
  388. print('cannot find mobile provisioning for %s' % (bundle_identifier), file=sys.stderr)
  389. sys.exit(1)
  390. provisioning_profiles = None
  391. if profile:
  392. profile_path = os.path.join(profiles_dir, profile + '.mobileprovision')
  393. if os.path.exists(profile_path):
  394. provisioning_profiles = [profile_path]
  395. if not provisioning_profiles:
  396. provisioning_profiles = glob.glob(
  397. os.path.join(profiles_dir, '*.mobileprovision'))
  398. valid_provisioning_profiles = {}
  399. for profile_path in provisioning_profiles:
  400. profile_data = self._LoadProvisioningProfile(profile_path)
  401. app_id_pattern = profile_data.get(
  402. 'Entitlements', {}).get('application-identifier', '')
  403. for team_identifier in profile_data.get('TeamIdentifier', []):
  404. app_id = '%s.%s' % (team_identifier, bundle_identifier)
  405. if fnmatch.fnmatch(app_id, app_id_pattern):
  406. valid_provisioning_profiles[app_id_pattern] = (
  407. profile_path, profile_data, team_identifier)
  408. if not valid_provisioning_profiles:
  409. print('cannot find mobile provisioning for %s' % (bundle_identifier), file=sys.stderr)
  410. sys.exit(1)
  411. # If the user has multiple provisioning profiles installed that can be
  412. # used for ${bundle_identifier}, pick the most specific one (ie. the
  413. # provisioning profile whose pattern is the longest).
  414. selected_key = max(valid_provisioning_profiles, key=lambda v: len(v))
  415. return valid_provisioning_profiles[selected_key]
  416. def _LoadProvisioningProfile(self, profile_path):
  417. """Extracts the plist embedded in a provisioning profile.
  418. Args:
  419. profile_path: string, path to the .mobileprovision file
  420. Returns:
  421. Content of the plist embedded in the provisioning profile as a dictionary.
  422. """
  423. with tempfile.NamedTemporaryFile() as temp:
  424. subprocess.check_call([
  425. 'security', 'cms', '-D', '-i', profile_path, '-o', temp.name])
  426. return self._LoadPlistMaybeBinary(temp.name)
  427. def _MergePlist(self, merged_plist, plist):
  428. """Merge |plist| into |merged_plist|."""
  429. for key, value in plist.items():
  430. if isinstance(value, dict):
  431. merged_value = merged_plist.get(key, {})
  432. if isinstance(merged_value, dict):
  433. self._MergePlist(merged_value, value)
  434. merged_plist[key] = merged_value
  435. else:
  436. merged_plist[key] = value
  437. else:
  438. merged_plist[key] = value
  439. def _LoadPlistMaybeBinary(self, plist_path):
  440. """Loads into a memory a plist possibly encoded in binary format.
  441. This is a wrapper around plistlib.readPlist that tries to convert the
  442. plist to the XML format if it can't be parsed (assuming that it is in
  443. the binary format).
  444. Args:
  445. plist_path: string, path to a plist file, in XML or binary format
  446. Returns:
  447. Content of the plist as a dictionary.
  448. """
  449. try:
  450. # First, try to read the file using plistlib that only supports XML,
  451. # and if an exception is raised, convert a temporary copy to XML and
  452. # load that copy.
  453. return plistlib.readPlist(plist_path)
  454. except:
  455. pass
  456. with tempfile.NamedTemporaryFile() as temp:
  457. shutil.copy2(plist_path, temp.name)
  458. subprocess.check_call(['plutil', '-convert', 'xml1', temp.name])
  459. return plistlib.readPlist(temp.name)
  460. def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
  461. """Constructs a dictionary of variable substitutions for Entitlements.plist.
  462. Args:
  463. bundle_identifier: string, value of CFBundleIdentifier from Info.plist
  464. app_identifier_prefix: string, value for AppIdentifierPrefix
  465. Returns:
  466. Dictionary of substitutions to apply when generating Entitlements.plist.
  467. """
  468. return {
  469. 'CFBundleIdentifier': bundle_identifier,
  470. 'AppIdentifierPrefix': app_identifier_prefix,
  471. }
  472. def _GetCFBundleIdentifier(self):
  473. """Extracts CFBundleIdentifier value from Info.plist in the bundle.
  474. Returns:
  475. Value of CFBundleIdentifier in the Info.plist located in the bundle.
  476. """
  477. info_plist_path = os.path.join(
  478. os.environ['TARGET_BUILD_DIR'],
  479. os.environ['INFOPLIST_PATH'])
  480. info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
  481. return info_plist_data['CFBundleIdentifier']
  482. def _InstallEntitlements(self, entitlements, substitutions, overrides):
  483. """Generates and install the ${BundleName}.xcent entitlements file.
  484. Expands variables "$(variable)" pattern in the source entitlements file,
  485. add extra entitlements defined in the .mobileprovision file and the copy
  486. the generated plist to "${BundlePath}.xcent".
  487. Args:
  488. entitlements: string, optional, path to the Entitlements.plist template
  489. to use, defaults to "${SDKROOT}/Entitlements.plist"
  490. substitutions: dictionary, variable substitutions
  491. overrides: dictionary, values to add to the entitlements
  492. Returns:
  493. Path to the generated entitlements file.
  494. """
  495. source_path = entitlements
  496. target_path = os.path.join(
  497. os.environ['BUILT_PRODUCTS_DIR'],
  498. os.environ['PRODUCT_NAME'] + '.xcent')
  499. if not source_path:
  500. source_path = os.path.join(
  501. os.environ['SDKROOT'],
  502. 'Entitlements.plist')
  503. shutil.copy2(source_path, target_path)
  504. data = self._LoadPlistMaybeBinary(target_path)
  505. data = self._ExpandVariables(data, substitutions)
  506. if overrides:
  507. for key in overrides:
  508. if key not in data:
  509. data[key] = overrides[key]
  510. plistlib.writePlist(data, target_path)
  511. return target_path
  512. def _ExpandVariables(self, data, substitutions):
  513. """Expands variables "$(variable)" in data.
  514. Args:
  515. data: object, can be either string, list or dictionary
  516. substitutions: dictionary, variable substitutions to perform
  517. Returns:
  518. Copy of data where each references to "$(variable)" has been replaced
  519. by the corresponding value found in substitutions, or left intact if
  520. the key was not found.
  521. """
  522. if isinstance(data, str):
  523. for key, value in substitutions.items():
  524. data = data.replace('$(%s)' % key, value)
  525. return data
  526. if isinstance(data, list):
  527. return [self._ExpandVariables(v, substitutions) for v in data]
  528. if isinstance(data, dict):
  529. return {k: self._ExpandVariables(data[k], substitutions) for k in data}
  530. return data
  531. if __name__ == '__main__':
  532. sys.exit(main(sys.argv[1:]))