@pact-foundation/pact-core 13.4.1-beta.11 → 13.4.1-beta.12

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.
@@ -19,7 +19,7 @@ import os
19
19
  import plistlib
20
20
  import re
21
21
  import shutil
22
- import struct
22
+ import string
23
23
  import subprocess
24
24
  import sys
25
25
  import tempfile
@@ -28,345 +28,276 @@ PY3 = bytes != str
28
28
 
29
29
 
30
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)
31
+ executor = MacTool()
32
+ exit_code = executor.Dispatch(args)
33
+ if exit_code is not None:
34
+ sys.exit(exit_code)
35
35
 
36
36
 
37
37
  class MacTool(object):
38
- """This class performs all the Mac tooling steps. The methods can either be
38
+ """This class performs all the Mac tooling steps. The methods can either be
39
39
  executed directly, or dispatched from an argument list."""
40
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")
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
45
 
46
- method = "Exec%s" % self._CommandifyName(args[0])
47
- return getattr(self, method)(*args[1:])
46
+ method = "Exec%s" % self._CommandifyName(args[0])
47
+ return getattr(self, method)(*args[1:])
48
48
 
49
- def _CommandifyName(self, name_string):
50
- """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
51
- return name_string.title().replace("-", "")
49
+ def _CommandifyName(self, name_string):
50
+ """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
51
+ return name_string.title().replace('-', '')
52
52
 
53
- def ExecCopyBundleResource(self, source, dest, convert_to_binary):
54
- """Copies a resource file to the bundle/Resources directory, performing any
53
+ def ExecCopyBundleResource(self, source, dest, convert_to_binary):
54
+ """Copies a resource file to the bundle/Resources directory, performing any
55
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
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
165
129
  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
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
266
235
  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
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
317
265
  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]
266
+ # Find the name of the binary based on the part before the ".framework".
267
+ binary = os.path.basename(framework).split('.')[0]
320
268
 
321
- CURRENT = "Current"
322
- RESOURCES = "Resources"
323
- VERSIONS = "Versions"
269
+ CURRENT = 'Current'
270
+ RESOURCES = 'Resources'
271
+ VERSIONS = 'Versions'
324
272
 
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
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
329
277
 
330
- # Move into the framework directory to set the symlinks correctly.
331
- pwd = os.getcwd()
332
- os.chdir(framework)
278
+ # Move into the framework directory to set the symlinks correctly.
279
+ pwd = os.getcwd()
280
+ os.chdir(framework)
333
281
 
334
- # Set up the Current version.
335
- self._Relink(version, os.path.join(VERSIONS, CURRENT))
282
+ # Set up the Current version.
283
+ self._Relink(version, os.path.join(VERSIONS, CURRENT))
336
284
 
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)
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)
340
288
 
341
- # Back to where we were before!
342
- os.chdir(pwd)
289
+ # Back to where we were before!
290
+ os.chdir(pwd)
343
291
 
344
- def _Relink(self, dest, link):
345
- """Creates a symlink to |dest| named |link|. If |link| already exists,
292
+ def _Relink(self, dest, link):
293
+ """Creates a symlink to |dest| named |link|. If |link| already exists,
346
294
  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.
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.
370
301
 
371
302
  This invokes 'actool' to compile all the inputs .xcassets files. The
372
303
  |keys| arguments is a json-encoded dictionary of extra arguments to
@@ -376,102 +307,101 @@ class MacTool(object):
376
307
  Note that 'actool' does not create the Assets.car file if the asset
377
308
  catalogs does not contains imageset.
378
309
  """
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
- )
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))
408
343
  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.
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.
450
361
 
451
362
  This function tries to code sign an iOS bundle, following the same
452
363
  algorithm as Xcode:
453
- 1. pick the provisioning profile that best match the bundle identifier,
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,
454
366
  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.
367
+ 3. copy Entitlements.plist from user or SDK next to the bundle,
368
+ 4. code sign the bundle.
457
369
  """
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)
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.
472
384
 
473
- def _InstallProvisioningProfile(self, profile, bundle_identifier):
474
- """Installs embedded.mobileprovision into the bundle.
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.
475
405
 
476
406
  Args:
477
407
  profile: string, optional, short name of the .mobileprovision file
@@ -483,20 +413,18 @@ class MacTool(object):
483
413
  A tuple containing two dictionary: variables substitutions and values
484
414
  to overrides when generating the entitlements file.
485
415
  """
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.
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.
500
428
 
501
429
  Checks all the installed provisioning profiles (or if the user specified
502
430
  the PROVISIONING_PROFILE variable, only consult it) and select the most
@@ -516,52 +444,40 @@ class MacTool(object):
516
444
  Raises:
517
445
  SystemExit: if no .mobileprovision can be used to sign the bundle.
518
446
  """
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.
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.
565
481
 
566
482
  Args:
567
483
  profile_path: string, path to the .mobileprovision file
@@ -569,27 +485,26 @@ class MacTool(object):
569
485
  Returns:
570
486
  Content of the plist embedded in the provisioning profile as a dictionary.
571
487
  """
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.
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.
593
508
 
594
509
  This is a wrapper around plistlib.readPlist that tries to convert the
595
510
  plist to the XML format if it can't be parsed (assuming that it is in
@@ -601,20 +516,20 @@ class MacTool(object):
601
516
  Returns:
602
517
  Content of the plist as a dictionary.
603
518
  """
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.
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.
618
533
 
619
534
  Args:
620
535
  bundle_identifier: string, value of CFBundleIdentifier from Info.plist
@@ -623,25 +538,25 @@ class MacTool(object):
623
538
  Returns:
624
539
  Dictionary of substitutions to apply when generating Entitlements.plist.
625
540
  """
626
- return {
627
- "CFBundleIdentifier": bundle_identifier,
628
- "AppIdentifierPrefix": app_identifier_prefix,
629
- }
541
+ return {
542
+ 'CFBundleIdentifier': bundle_identifier,
543
+ 'AppIdentifierPrefix': app_identifier_prefix,
544
+ }
630
545
 
631
- def _GetCFBundleIdentifier(self):
632
- """Extracts CFBundleIdentifier value from Info.plist in the bundle.
546
+ def _GetCFBundleIdentifier(self):
547
+ """Extracts CFBundleIdentifier value from Info.plist in the bundle.
633
548
 
634
549
  Returns:
635
550
  Value of CFBundleIdentifier in the Info.plist located in the bundle.
636
551
  """
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"]
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']
642
557
 
643
- def _InstallEntitlements(self, entitlements, substitutions, overrides):
644
- """Generates and install the ${BundleName}.xcent entitlements file.
558
+ def _InstallEntitlements(self, entitlements, substitutions, overrides):
559
+ """Generates and install the ${BundleName}.xcent entitlements file.
645
560
 
646
561
  Expands variables "$(variable)" pattern in the source entitlements file,
647
562
  add extra entitlements defined in the .mobileprovision file and the copy
@@ -656,24 +571,26 @@ class MacTool(object):
656
571
  Returns:
657
572
  Path to the generated entitlements file.
658
573
  """
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.
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.
677
594
 
678
595
  Args:
679
596
  data: object, can be either string, list or dictionary
@@ -684,94 +601,15 @@ class MacTool(object):
684
601
  by the corresponding value found in substitutions, or left intact if
685
602
  the key was not found.
686
603
  """
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:]))
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:]))