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