casbin-async-django-orm-adapter 1.0.0__py3-none-any.whl

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