@graphprotocol/graph-cli 0.25.2 → 0.26.1

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