a zip code crypto-currency system good for red ONLY

gyp-mac-tool 23KB

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