PageRenderTime 55ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/front/node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py

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