@pact-foundation/pact-core 13.4.1-beta.1 → 13.4.1-beta.6

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 (54) hide show
  1. package/binding.gyp +4 -8
  2. package/build/Makefile +352 -0
  3. package/build/binding.Makefile +6 -0
  4. package/build/copy_release_artifacts.target.mk +47 -0
  5. package/build/gyp-mac-tool +777 -0
  6. package/build/pact.target.mk +205 -0
  7. package/build/set_osx_install_name.target.mk +48 -0
  8. package/ffi/libpact_ffi.dylib +0 -0
  9. package/ffi/libpact_ffi.so +0 -0
  10. package/ffi/osxaarch64/libpact_ffi.dylib +0 -0
  11. package/ffi/pact.h +599 -108
  12. package/ffi/pact_ffi.dll +0 -0
  13. package/ffi/pact_ffi.dll.lib +0 -0
  14. package/native/consumer.cc +88 -32
  15. package/package.json +4 -5
  16. package/src/consumer/__testoutput__/foo-consumer-bar-provider.json +255 -0
  17. package/src/consumer/index.d.ts +1 -0
  18. package/src/consumer/index.js +44 -31
  19. package/src/consumer/index.js.map +1 -1
  20. package/src/consumer/types.d.ts +4 -0
  21. package/src/ffi/index.d.ts +1 -6
  22. package/src/ffi/index.js +2 -32
  23. package/src/ffi/index.js.map +1 -1
  24. package/src/ffi/internals/index.d.ts +0 -2
  25. package/src/ffi/internals/index.js +1 -11
  26. package/src/ffi/internals/index.js.map +1 -1
  27. package/src/ffi/internals/types.d.ts +2 -4
  28. package/src/ffi/types.d.ts +12 -0
  29. package/src/ffi/types.js +15 -1
  30. package/src/ffi/types.js.map +1 -1
  31. package/src/publisher.d.ts +1 -0
  32. package/src/publisher.js +11 -4
  33. package/src/publisher.js.map +1 -1
  34. package/src/verifier/nativeVerifier.js +9 -6
  35. package/src/verifier/nativeVerifier.js.map +1 -1
  36. package/src/verifier/types.d.ts +3 -0
  37. package/src/verifier/validateOptions.js +3 -1
  38. package/src/verifier/validateOptions.js.map +1 -1
  39. package/standalone/install.d.ts +1 -1
  40. package/standalone/install.js +1 -1
  41. package/ffi/libpact_ffi.so.gz +0 -0
  42. package/native/consumer.c +0 -210
  43. package/src/ffi/argumentMapper/index.d.ts +0 -2
  44. package/src/ffi/argumentMapper/index.js +0 -47
  45. package/src/ffi/argumentMapper/index.js.map +0 -1
  46. package/src/ffi/argumentMapper/types.d.ts +0 -8
  47. package/src/ffi/argumentMapper/types.js +0 -3
  48. package/src/ffi/argumentMapper/types.js.map +0 -1
  49. package/src/ffi/declarations.d.ts +0 -117
  50. package/src/ffi/declarations.js +0 -66
  51. package/src/ffi/declarations.js.map +0 -1
  52. package/src/verifier/arguments.d.ts +0 -13
  53. package/src/verifier/arguments.js +0 -89
  54. package/src/verifier/arguments.js.map +0 -1
@@ -0,0 +1,777 @@
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 struct
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
+ convert_to_binary = convert_to_binary == "True"
57
+ extension = os.path.splitext(source)[1].lower()
58
+ if os.path.isdir(source):
59
+ # Copy tree.
60
+ # TODO(thakis): This copies file attributes like mtime, while the
61
+ # single-file branch below doesn't. This should probably be changed to
62
+ # be consistent with the single-file branch.
63
+ if os.path.exists(dest):
64
+ shutil.rmtree(dest)
65
+ shutil.copytree(source, dest)
66
+ elif extension == ".xib":
67
+ return self._CopyXIBFile(source, dest)
68
+ elif extension == ".storyboard":
69
+ return self._CopyXIBFile(source, dest)
70
+ elif extension == ".strings" and not convert_to_binary:
71
+ self._CopyStringsFile(source, dest)
72
+ else:
73
+ if os.path.exists(dest):
74
+ os.unlink(dest)
75
+ shutil.copy(source, dest)
76
+
77
+ if convert_to_binary and extension in (".plist", ".strings"):
78
+ self._ConvertToBinary(dest)
79
+
80
+ def _CopyXIBFile(self, source, dest):
81
+ """Compiles a XIB file with ibtool into a binary plist in the bundle."""
82
+
83
+ # ibtool sometimes crashes with relative paths. See crbug.com/314728.
84
+ base = os.path.dirname(os.path.realpath(__file__))
85
+ if os.path.relpath(source):
86
+ source = os.path.join(base, source)
87
+ if os.path.relpath(dest):
88
+ dest = os.path.join(base, dest)
89
+
90
+ args = ["xcrun", "ibtool", "--errors", "--warnings", "--notices"]
91
+
92
+ if os.environ["XCODE_VERSION_ACTUAL"] > "0700":
93
+ args.extend(["--auto-activate-custom-fonts"])
94
+ if "IPHONEOS_DEPLOYMENT_TARGET" in os.environ:
95
+ args.extend(
96
+ [
97
+ "--target-device",
98
+ "iphone",
99
+ "--target-device",
100
+ "ipad",
101
+ "--minimum-deployment-target",
102
+ os.environ["IPHONEOS_DEPLOYMENT_TARGET"],
103
+ ]
104
+ )
105
+ else:
106
+ args.extend(
107
+ [
108
+ "--target-device",
109
+ "mac",
110
+ "--minimum-deployment-target",
111
+ os.environ["MACOSX_DEPLOYMENT_TARGET"],
112
+ ]
113
+ )
114
+
115
+ args.extend(
116
+ ["--output-format", "human-readable-text", "--compile", dest, source]
117
+ )
118
+
119
+ ibtool_section_re = re.compile(r"/\*.*\*/")
120
+ ibtool_re = re.compile(r".*note:.*is clipping its content")
121
+ try:
122
+ stdout = subprocess.check_output(args)
123
+ except subprocess.CalledProcessError as e:
124
+ print(e.output)
125
+ raise
126
+ current_section_header = None
127
+ for line in stdout.splitlines():
128
+ if ibtool_section_re.match(line):
129
+ current_section_header = line
130
+ elif not ibtool_re.match(line):
131
+ if current_section_header:
132
+ print(current_section_header)
133
+ current_section_header = None
134
+ print(line)
135
+ return 0
136
+
137
+ def _ConvertToBinary(self, dest):
138
+ subprocess.check_call(
139
+ ["xcrun", "plutil", "-convert", "binary1", "-o", dest, dest]
140
+ )
141
+
142
+ def _CopyStringsFile(self, source, dest):
143
+ """Copies a .strings file using iconv to reconvert the input into UTF-16."""
144
+ input_code = self._DetectInputEncoding(source) or "UTF-8"
145
+
146
+ # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
147
+ # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
148
+ # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
149
+ # semicolon in dictionary.
150
+ # on invalid files. Do the same kind of validation.
151
+ import CoreFoundation
152
+
153
+ with open(source, "rb") as in_file:
154
+ s = in_file.read()
155
+ d = CoreFoundation.CFDataCreate(None, s, len(s))
156
+ _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
157
+ if error:
158
+ return
159
+
160
+ with open(dest, "wb") as fp:
161
+ fp.write(s.decode(input_code).encode("UTF-16"))
162
+
163
+ def _DetectInputEncoding(self, file_name):
164
+ """Reads the first few bytes from file_name and tries to guess the text
165
+ encoding. Returns None as a guess if it can't detect it."""
166
+ with open(file_name, "rb") as fp:
167
+ try:
168
+ header = fp.read(3)
169
+ except Exception:
170
+ return None
171
+ if header.startswith(b"\xFE\xFF"):
172
+ return "UTF-16"
173
+ elif header.startswith(b"\xFF\xFE"):
174
+ return "UTF-16"
175
+ elif header.startswith(b"\xEF\xBB\xBF"):
176
+ return "UTF-8"
177
+ else:
178
+ return None
179
+
180
+ def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys):
181
+ """Copies the |source| Info.plist to the destination directory |dest|."""
182
+ # Read the source Info.plist into memory.
183
+ with open(source, "r") as fd:
184
+ lines = fd.read()
185
+
186
+ # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
187
+ plist = plistlib.readPlistFromString(lines)
188
+ if keys:
189
+ plist.update(json.loads(keys[0]))
190
+ lines = plistlib.writePlistToString(plist)
191
+
192
+ # Go through all the environment variables and replace them as variables in
193
+ # the file.
194
+ IDENT_RE = re.compile(r"[_/\s]")
195
+ for key in os.environ:
196
+ if key.startswith("_"):
197
+ continue
198
+ evar = "${%s}" % key
199
+ evalue = os.environ[key]
200
+ lines = lines.replace(lines, evar, evalue)
201
+
202
+ # Xcode supports various suffices on environment variables, which are
203
+ # all undocumented. :rfc1034identifier is used in the standard project
204
+ # template these days, and :identifier was used earlier. They are used to
205
+ # convert non-url characters into things that look like valid urls --
206
+ # except that the replacement character for :identifier, '_' isn't valid
207
+ # in a URL either -- oops, hence :rfc1034identifier was born.
208
+ evar = "${%s:identifier}" % key
209
+ evalue = IDENT_RE.sub("_", os.environ[key])
210
+ lines = lines.replace(lines, evar, evalue)
211
+
212
+ evar = "${%s:rfc1034identifier}" % key
213
+ evalue = IDENT_RE.sub("-", os.environ[key])
214
+ lines = lines.replace(lines, evar, evalue)
215
+
216
+ # Remove any keys with values that haven't been replaced.
217
+ lines = lines.splitlines()
218
+ for i in range(len(lines)):
219
+ if lines[i].strip().startswith("<string>${"):
220
+ lines[i] = None
221
+ lines[i - 1] = None
222
+ lines = "\n".join(line for line in lines if line is not None)
223
+
224
+ # Write out the file with variables replaced.
225
+ with open(dest, "w") as fd:
226
+ fd.write(lines)
227
+
228
+ # Now write out PkgInfo file now that the Info.plist file has been
229
+ # "compiled".
230
+ self._WritePkgInfo(dest)
231
+
232
+ if convert_to_binary == "True":
233
+ self._ConvertToBinary(dest)
234
+
235
+ def _WritePkgInfo(self, info_plist):
236
+ """This writes the PkgInfo file from the data stored in Info.plist."""
237
+ plist = plistlib.readPlist(info_plist)
238
+ if not plist:
239
+ return
240
+
241
+ # Only create PkgInfo for executable types.
242
+ package_type = plist["CFBundlePackageType"]
243
+ if package_type != "APPL":
244
+ return
245
+
246
+ # The format of PkgInfo is eight characters, representing the bundle type
247
+ # and bundle signature, each four characters. If that is missing, four
248
+ # '?' characters are used instead.
249
+ signature_code = plist.get("CFBundleSignature", "????")
250
+ if len(signature_code) != 4: # Wrong length resets everything, too.
251
+ signature_code = "?" * 4
252
+
253
+ dest = os.path.join(os.path.dirname(info_plist), "PkgInfo")
254
+ with open(dest, "w") as fp:
255
+ fp.write("%s%s" % (package_type, signature_code))
256
+
257
+ def ExecFlock(self, lockfile, *cmd_list):
258
+ """Emulates the most basic behavior of Linux's flock(1)."""
259
+ # Rely on exception handling to report errors.
260
+ fd = os.open(lockfile, os.O_RDONLY | os.O_NOCTTY | os.O_CREAT, 0o666)
261
+ fcntl.flock(fd, fcntl.LOCK_EX)
262
+ return subprocess.call(cmd_list)
263
+
264
+ def ExecFilterLibtool(self, *cmd_list):
265
+ """Calls libtool and filters out '/path/to/libtool: file: foo.o has no
266
+ symbols'."""
267
+ libtool_re = re.compile(
268
+ r"^.*libtool: (?:for architecture: \S* )?" r"file: .* has no symbols$"
269
+ )
270
+ libtool_re5 = re.compile(
271
+ r"^.*libtool: warning for library: "
272
+ + r".* the table of contents is empty "
273
+ + r"\(no object file members in the library define global symbols\)$"
274
+ )
275
+ env = os.environ.copy()
276
+ # Ref:
277
+ # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c
278
+ # The problem with this flag is that it resets the file mtime on the file to
279
+ # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone.
280
+ env["ZERO_AR_DATE"] = "1"
281
+ libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env)
282
+ _, err = libtoolout.communicate()
283
+ if PY3:
284
+ err = err.decode("utf-8")
285
+ for line in err.splitlines():
286
+ if not libtool_re.match(line) and not libtool_re5.match(line):
287
+ print(line, file=sys.stderr)
288
+ # Unconditionally touch the output .a file on the command line if present
289
+ # and the command succeeded. A bit hacky.
290
+ if not libtoolout.returncode:
291
+ for i in range(len(cmd_list) - 1):
292
+ if cmd_list[i] == "-o" and cmd_list[i + 1].endswith(".a"):
293
+ os.utime(cmd_list[i + 1], None)
294
+ break
295
+ return libtoolout.returncode
296
+
297
+ def ExecPackageIosFramework(self, framework):
298
+ # Find the name of the binary based on the part before the ".framework".
299
+ binary = os.path.basename(framework).split(".")[0]
300
+ module_path = os.path.join(framework, "Modules")
301
+ if not os.path.exists(module_path):
302
+ os.mkdir(module_path)
303
+ module_template = (
304
+ "framework module %s {\n"
305
+ ' umbrella header "%s.h"\n'
306
+ "\n"
307
+ " export *\n"
308
+ " module * { export * }\n"
309
+ "}\n" % (binary, binary)
310
+ )
311
+
312
+ with open(os.path.join(module_path, "module.modulemap"), "w") as module_file:
313
+ module_file.write(module_template)
314
+
315
+ def ExecPackageFramework(self, framework, version):
316
+ """Takes a path to Something.framework and the Current version of that and
317
+ sets up all the symlinks."""
318
+ # Find the name of the binary based on the part before the ".framework".
319
+ binary = os.path.basename(framework).split(".")[0]
320
+
321
+ CURRENT = "Current"
322
+ RESOURCES = "Resources"
323
+ VERSIONS = "Versions"
324
+
325
+ if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
326
+ # Binary-less frameworks don't seem to contain symlinks (see e.g.
327
+ # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
328
+ return
329
+
330
+ # Move into the framework directory to set the symlinks correctly.
331
+ pwd = os.getcwd()
332
+ os.chdir(framework)
333
+
334
+ # Set up the Current version.
335
+ self._Relink(version, os.path.join(VERSIONS, CURRENT))
336
+
337
+ # Set up the root symlinks.
338
+ self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
339
+ self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
340
+
341
+ # Back to where we were before!
342
+ os.chdir(pwd)
343
+
344
+ def _Relink(self, dest, link):
345
+ """Creates a symlink to |dest| named |link|. If |link| already exists,
346
+ it is overwritten."""
347
+ if os.path.lexists(link):
348
+ os.remove(link)
349
+ os.symlink(dest, link)
350
+
351
+ def ExecCompileIosFrameworkHeaderMap(self, out, framework, *all_headers):
352
+ framework_name = os.path.basename(framework).split(".")[0]
353
+ all_headers = [os.path.abspath(header) for header in all_headers]
354
+ filelist = {}
355
+ for header in all_headers:
356
+ filename = os.path.basename(header)
357
+ filelist[filename] = header
358
+ filelist[os.path.join(framework_name, filename)] = header
359
+ WriteHmap(out, filelist)
360
+
361
+ def ExecCopyIosFrameworkHeaders(self, framework, *copy_headers):
362
+ header_path = os.path.join(framework, "Headers")
363
+ if not os.path.exists(header_path):
364
+ os.makedirs(header_path)
365
+ for header in copy_headers:
366
+ shutil.copy(header, os.path.join(header_path, os.path.basename(header)))
367
+
368
+ def ExecCompileXcassets(self, keys, *inputs):
369
+ """Compiles multiple .xcassets files into a single .car file.
370
+
371
+ This invokes 'actool' to compile all the inputs .xcassets files. The
372
+ |keys| arguments is a json-encoded dictionary of extra arguments to
373
+ pass to 'actool' when the asset catalogs contains an application icon
374
+ or a launch image.
375
+
376
+ Note that 'actool' does not create the Assets.car file if the asset
377
+ catalogs does not contains imageset.
378
+ """
379
+ command_line = [
380
+ "xcrun",
381
+ "actool",
382
+ "--output-format",
383
+ "human-readable-text",
384
+ "--compress-pngs",
385
+ "--notices",
386
+ "--warnings",
387
+ "--errors",
388
+ ]
389
+ is_iphone_target = "IPHONEOS_DEPLOYMENT_TARGET" in os.environ
390
+ if is_iphone_target:
391
+ platform = os.environ["CONFIGURATION"].split("-")[-1]
392
+ if platform not in ("iphoneos", "iphonesimulator"):
393
+ platform = "iphonesimulator"
394
+ command_line.extend(
395
+ [
396
+ "--platform",
397
+ platform,
398
+ "--target-device",
399
+ "iphone",
400
+ "--target-device",
401
+ "ipad",
402
+ "--minimum-deployment-target",
403
+ os.environ["IPHONEOS_DEPLOYMENT_TARGET"],
404
+ "--compile",
405
+ os.path.abspath(os.environ["CONTENTS_FOLDER_PATH"]),
406
+ ]
407
+ )
408
+ else:
409
+ command_line.extend(
410
+ [
411
+ "--platform",
412
+ "macosx",
413
+ "--target-device",
414
+ "mac",
415
+ "--minimum-deployment-target",
416
+ os.environ["MACOSX_DEPLOYMENT_TARGET"],
417
+ "--compile",
418
+ os.path.abspath(os.environ["UNLOCALIZED_RESOURCES_FOLDER_PATH"]),
419
+ ]
420
+ )
421
+ if keys:
422
+ keys = json.loads(keys)
423
+ for key, value in keys.items():
424
+ arg_name = "--" + key
425
+ if isinstance(value, bool):
426
+ if value:
427
+ command_line.append(arg_name)
428
+ elif isinstance(value, list):
429
+ for v in value:
430
+ command_line.append(arg_name)
431
+ command_line.append(str(v))
432
+ else:
433
+ command_line.append(arg_name)
434
+ command_line.append(str(value))
435
+ # Note: actool crashes if inputs path are relative, so use os.path.abspath
436
+ # to get absolute path name for inputs.
437
+ command_line.extend(map(os.path.abspath, inputs))
438
+ subprocess.check_call(command_line)
439
+
440
+ def ExecMergeInfoPlist(self, output, *inputs):
441
+ """Merge multiple .plist files into a single .plist file."""
442
+ merged_plist = {}
443
+ for path in inputs:
444
+ plist = self._LoadPlistMaybeBinary(path)
445
+ self._MergePlist(merged_plist, plist)
446
+ plistlib.writePlist(merged_plist, output)
447
+
448
+ def ExecCodeSignBundle(self, key, entitlements, provisioning, path, preserve):
449
+ """Code sign a bundle.
450
+
451
+ This function tries to code sign an iOS bundle, following the same
452
+ algorithm as Xcode:
453
+ 1. pick the provisioning profile that best match the bundle identifier,
454
+ and copy it into the bundle as embedded.mobileprovision,
455
+ 2. copy Entitlements.plist from user or SDK next to the bundle,
456
+ 3. code sign the bundle.
457
+ """
458
+ substitutions, overrides = self._InstallProvisioningProfile(
459
+ provisioning, self._GetCFBundleIdentifier()
460
+ )
461
+ entitlements_path = self._InstallEntitlements(
462
+ entitlements, substitutions, overrides
463
+ )
464
+
465
+ args = ["codesign", "--force", "--sign", key]
466
+ if preserve == "True":
467
+ args.extend(["--deep", "--preserve-metadata=identifier,entitlements"])
468
+ else:
469
+ args.extend(["--entitlements", entitlements_path])
470
+ args.extend(["--timestamp=none", path])
471
+ subprocess.check_call(args)
472
+
473
+ def _InstallProvisioningProfile(self, profile, bundle_identifier):
474
+ """Installs embedded.mobileprovision into the bundle.
475
+
476
+ Args:
477
+ profile: string, optional, short name of the .mobileprovision file
478
+ to use, if empty or the file is missing, the best file installed
479
+ will be used
480
+ bundle_identifier: string, value of CFBundleIdentifier from Info.plist
481
+
482
+ Returns:
483
+ A tuple containing two dictionary: variables substitutions and values
484
+ to overrides when generating the entitlements file.
485
+ """
486
+ source_path, provisioning_data, team_id = self._FindProvisioningProfile(
487
+ profile, bundle_identifier
488
+ )
489
+ target_path = os.path.join(
490
+ os.environ["BUILT_PRODUCTS_DIR"],
491
+ os.environ["CONTENTS_FOLDER_PATH"],
492
+ "embedded.mobileprovision",
493
+ )
494
+ shutil.copy2(source_path, target_path)
495
+ substitutions = self._GetSubstitutions(bundle_identifier, team_id + ".")
496
+ return substitutions, provisioning_data["Entitlements"]
497
+
498
+ def _FindProvisioningProfile(self, profile, bundle_identifier):
499
+ """Finds the .mobileprovision file to use for signing the bundle.
500
+
501
+ Checks all the installed provisioning profiles (or if the user specified
502
+ the PROVISIONING_PROFILE variable, only consult it) and select the most
503
+ specific that correspond to the bundle identifier.
504
+
505
+ Args:
506
+ profile: string, optional, short name of the .mobileprovision file
507
+ to use, if empty or the file is missing, the best file installed
508
+ will be used
509
+ bundle_identifier: string, value of CFBundleIdentifier from Info.plist
510
+
511
+ Returns:
512
+ A tuple of the path to the selected provisioning profile, the data of
513
+ the embedded plist in the provisioning profile and the team identifier
514
+ to use for code signing.
515
+
516
+ Raises:
517
+ SystemExit: if no .mobileprovision can be used to sign the bundle.
518
+ """
519
+ profiles_dir = os.path.join(
520
+ os.environ["HOME"], "Library", "MobileDevice", "Provisioning Profiles"
521
+ )
522
+ if not os.path.isdir(profiles_dir):
523
+ print(
524
+ "cannot find mobile provisioning for %s" % (bundle_identifier),
525
+ file=sys.stderr,
526
+ )
527
+ sys.exit(1)
528
+ provisioning_profiles = None
529
+ if profile:
530
+ profile_path = os.path.join(profiles_dir, profile + ".mobileprovision")
531
+ if os.path.exists(profile_path):
532
+ provisioning_profiles = [profile_path]
533
+ if not provisioning_profiles:
534
+ provisioning_profiles = glob.glob(
535
+ os.path.join(profiles_dir, "*.mobileprovision")
536
+ )
537
+ valid_provisioning_profiles = {}
538
+ for profile_path in provisioning_profiles:
539
+ profile_data = self._LoadProvisioningProfile(profile_path)
540
+ app_id_pattern = profile_data.get("Entitlements", {}).get(
541
+ "application-identifier", ""
542
+ )
543
+ for team_identifier in profile_data.get("TeamIdentifier", []):
544
+ app_id = "%s.%s" % (team_identifier, bundle_identifier)
545
+ if fnmatch.fnmatch(app_id, app_id_pattern):
546
+ valid_provisioning_profiles[app_id_pattern] = (
547
+ profile_path,
548
+ profile_data,
549
+ team_identifier,
550
+ )
551
+ if not valid_provisioning_profiles:
552
+ print(
553
+ "cannot find mobile provisioning for %s" % (bundle_identifier),
554
+ file=sys.stderr,
555
+ )
556
+ sys.exit(1)
557
+ # If the user has multiple provisioning profiles installed that can be
558
+ # used for ${bundle_identifier}, pick the most specific one (ie. the
559
+ # provisioning profile whose pattern is the longest).
560
+ selected_key = max(valid_provisioning_profiles, key=lambda v: len(v))
561
+ return valid_provisioning_profiles[selected_key]
562
+
563
+ def _LoadProvisioningProfile(self, profile_path):
564
+ """Extracts the plist embedded in a provisioning profile.
565
+
566
+ Args:
567
+ profile_path: string, path to the .mobileprovision file
568
+
569
+ Returns:
570
+ Content of the plist embedded in the provisioning profile as a dictionary.
571
+ """
572
+ with tempfile.NamedTemporaryFile() as temp:
573
+ subprocess.check_call(
574
+ ["security", "cms", "-D", "-i", profile_path, "-o", temp.name]
575
+ )
576
+ return self._LoadPlistMaybeBinary(temp.name)
577
+
578
+ def _MergePlist(self, merged_plist, plist):
579
+ """Merge |plist| into |merged_plist|."""
580
+ for key, value in plist.items():
581
+ if isinstance(value, dict):
582
+ merged_value = merged_plist.get(key, {})
583
+ if isinstance(merged_value, dict):
584
+ self._MergePlist(merged_value, value)
585
+ merged_plist[key] = merged_value
586
+ else:
587
+ merged_plist[key] = value
588
+ else:
589
+ merged_plist[key] = value
590
+
591
+ def _LoadPlistMaybeBinary(self, plist_path):
592
+ """Loads into a memory a plist possibly encoded in binary format.
593
+
594
+ This is a wrapper around plistlib.readPlist that tries to convert the
595
+ plist to the XML format if it can't be parsed (assuming that it is in
596
+ the binary format).
597
+
598
+ Args:
599
+ plist_path: string, path to a plist file, in XML or binary format
600
+
601
+ Returns:
602
+ Content of the plist as a dictionary.
603
+ """
604
+ try:
605
+ # First, try to read the file using plistlib that only supports XML,
606
+ # and if an exception is raised, convert a temporary copy to XML and
607
+ # load that copy.
608
+ return plistlib.readPlist(plist_path)
609
+ except Exception:
610
+ pass
611
+ with tempfile.NamedTemporaryFile() as temp:
612
+ shutil.copy2(plist_path, temp.name)
613
+ subprocess.check_call(["plutil", "-convert", "xml1", temp.name])
614
+ return plistlib.readPlist(temp.name)
615
+
616
+ def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
617
+ """Constructs a dictionary of variable substitutions for Entitlements.plist.
618
+
619
+ Args:
620
+ bundle_identifier: string, value of CFBundleIdentifier from Info.plist
621
+ app_identifier_prefix: string, value for AppIdentifierPrefix
622
+
623
+ Returns:
624
+ Dictionary of substitutions to apply when generating Entitlements.plist.
625
+ """
626
+ return {
627
+ "CFBundleIdentifier": bundle_identifier,
628
+ "AppIdentifierPrefix": app_identifier_prefix,
629
+ }
630
+
631
+ def _GetCFBundleIdentifier(self):
632
+ """Extracts CFBundleIdentifier value from Info.plist in the bundle.
633
+
634
+ Returns:
635
+ Value of CFBundleIdentifier in the Info.plist located in the bundle.
636
+ """
637
+ info_plist_path = os.path.join(
638
+ os.environ["TARGET_BUILD_DIR"], os.environ["INFOPLIST_PATH"]
639
+ )
640
+ info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
641
+ return info_plist_data["CFBundleIdentifier"]
642
+
643
+ def _InstallEntitlements(self, entitlements, substitutions, overrides):
644
+ """Generates and install the ${BundleName}.xcent entitlements file.
645
+
646
+ Expands variables "$(variable)" pattern in the source entitlements file,
647
+ add extra entitlements defined in the .mobileprovision file and the copy
648
+ the generated plist to "${BundlePath}.xcent".
649
+
650
+ Args:
651
+ entitlements: string, optional, path to the Entitlements.plist template
652
+ to use, defaults to "${SDKROOT}/Entitlements.plist"
653
+ substitutions: dictionary, variable substitutions
654
+ overrides: dictionary, values to add to the entitlements
655
+
656
+ Returns:
657
+ Path to the generated entitlements file.
658
+ """
659
+ source_path = entitlements
660
+ target_path = os.path.join(
661
+ os.environ["BUILT_PRODUCTS_DIR"], os.environ["PRODUCT_NAME"] + ".xcent"
662
+ )
663
+ if not source_path:
664
+ source_path = os.path.join(os.environ["SDKROOT"], "Entitlements.plist")
665
+ shutil.copy2(source_path, target_path)
666
+ data = self._LoadPlistMaybeBinary(target_path)
667
+ data = self._ExpandVariables(data, substitutions)
668
+ if overrides:
669
+ for key in overrides:
670
+ if key not in data:
671
+ data[key] = overrides[key]
672
+ plistlib.writePlist(data, target_path)
673
+ return target_path
674
+
675
+ def _ExpandVariables(self, data, substitutions):
676
+ """Expands variables "$(variable)" in data.
677
+
678
+ Args:
679
+ data: object, can be either string, list or dictionary
680
+ substitutions: dictionary, variable substitutions to perform
681
+
682
+ Returns:
683
+ Copy of data where each references to "$(variable)" has been replaced
684
+ by the corresponding value found in substitutions, or left intact if
685
+ the key was not found.
686
+ """
687
+ if isinstance(data, str):
688
+ for key, value in substitutions.items():
689
+ data = data.replace("$(%s)" % key, value)
690
+ return data
691
+ if isinstance(data, list):
692
+ return [self._ExpandVariables(v, substitutions) for v in data]
693
+ if isinstance(data, dict):
694
+ return {k: self._ExpandVariables(data[k], substitutions) for k in data}
695
+ return data
696
+
697
+
698
+ def NextGreaterPowerOf2(x):
699
+ return 2 ** (x).bit_length()
700
+
701
+
702
+ def WriteHmap(output_name, filelist):
703
+ """Generates a header map based on |filelist|.
704
+
705
+ Per Mark Mentovai:
706
+ A header map is structured essentially as a hash table, keyed by names used
707
+ in #includes, and providing pathnames to the actual files.
708
+
709
+ The implementation below and the comment above comes from inspecting:
710
+ http://www.opensource.apple.com/source/distcc/distcc-2503/distcc_dist/include_server/headermap.py?txt
711
+ while also looking at the implementation in clang in:
712
+ https://llvm.org/svn/llvm-project/cfe/trunk/lib/Lex/HeaderMap.cpp
713
+ """
714
+ magic = 1751998832
715
+ version = 1
716
+ _reserved = 0
717
+ count = len(filelist)
718
+ capacity = NextGreaterPowerOf2(count)
719
+ strings_offset = 24 + (12 * capacity)
720
+ max_value_length = max(len(value) for value in filelist.values())
721
+
722
+ out = open(output_name, "wb")
723
+ out.write(
724
+ struct.pack(
725
+ "<LHHLLLL",
726
+ magic,
727
+ version,
728
+ _reserved,
729
+ strings_offset,
730
+ count,
731
+ capacity,
732
+ max_value_length,
733
+ )
734
+ )
735
+
736
+ # Create empty hashmap buckets.
737
+ buckets = [None] * capacity
738
+ for file, path in filelist.items():
739
+ key = 0
740
+ for c in file:
741
+ key += ord(c.lower()) * 13
742
+
743
+ # Fill next empty bucket.
744
+ while buckets[key & capacity - 1] is not None:
745
+ key = key + 1
746
+ buckets[key & capacity - 1] = (file, path)
747
+
748
+ next_offset = 1
749
+ for bucket in buckets:
750
+ if bucket is None:
751
+ out.write(struct.pack("<LLL", 0, 0, 0))
752
+ else:
753
+ (file, path) = bucket
754
+ key_offset = next_offset
755
+ prefix_offset = key_offset + len(file) + 1
756
+ suffix_offset = prefix_offset + len(os.path.dirname(path) + os.sep) + 1
757
+ next_offset = suffix_offset + len(os.path.basename(path)) + 1
758
+ out.write(struct.pack("<LLL", key_offset, prefix_offset, suffix_offset))
759
+
760
+ # Pad byte since next offset starts at 1.
761
+ out.write(struct.pack("<x"))
762
+
763
+ for bucket in buckets:
764
+ if bucket is not None:
765
+ (file, path) = bucket
766
+ out.write(struct.pack("<%ds" % len(file), file))
767
+ out.write(struct.pack("<s", "\0"))
768
+ base = os.path.dirname(path) + os.sep
769
+ out.write(struct.pack("<%ds" % len(base), base))
770
+ out.write(struct.pack("<s", "\0"))
771
+ path = os.path.basename(path)
772
+ out.write(struct.pack("<%ds" % len(path), path))
773
+ out.write(struct.pack("<s", "\0"))
774
+
775
+
776
+ if __name__ == "__main__":
777
+ sys.exit(main(sys.argv[1:]))