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,709 @@
1
+ # Copyright (c) 2012 Google Inc. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ import errno
6
+ import filecmp
7
+ import os.path
8
+ import re
9
+ import shlex
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ from collections.abc import MutableSet
14
+
15
+
16
+ # A minimal memoizing decorator. It'll blow up if the args aren't immutable,
17
+ # among other "problems".
18
+ class memoize:
19
+ def __init__(self, func):
20
+ self.func = func
21
+ self.cache = {}
22
+
23
+ def __call__(self, *args):
24
+ try:
25
+ return self.cache[args]
26
+ except KeyError:
27
+ result = self.func(*args)
28
+ self.cache[args] = result
29
+ return result
30
+
31
+
32
+ class GypError(Exception):
33
+ """Error class representing an error, which is to be presented
34
+ to the user. The main entry point will catch and display this.
35
+ """
36
+
37
+
38
+
39
+ def ExceptionAppend(e, msg):
40
+ """Append a message to the given exception's message."""
41
+ if not e.args:
42
+ e.args = (msg,)
43
+ elif len(e.args) == 1:
44
+ e.args = (str(e.args[0]) + " " + msg,)
45
+ else:
46
+ e.args = (str(e.args[0]) + " " + msg,) + e.args[1:]
47
+
48
+
49
+ def FindQualifiedTargets(target, qualified_list):
50
+ """
51
+ Given a list of qualified targets, return the qualified targets for the
52
+ specified |target|.
53
+ """
54
+ return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target]
55
+
56
+
57
+ def ParseQualifiedTarget(target):
58
+ # Splits a qualified target into a build file, target name and toolset.
59
+
60
+ # NOTE: rsplit is used to disambiguate the Windows drive letter separator.
61
+ target_split = target.rsplit(":", 1)
62
+ if len(target_split) == 2:
63
+ [build_file, target] = target_split
64
+ else:
65
+ build_file = None
66
+
67
+ target_split = target.rsplit("#", 1)
68
+ if len(target_split) == 2:
69
+ [target, toolset] = target_split
70
+ else:
71
+ toolset = None
72
+
73
+ return [build_file, target, toolset]
74
+
75
+
76
+ def ResolveTarget(build_file, target, toolset):
77
+ # This function resolves a target into a canonical form:
78
+ # - a fully defined build file, either absolute or relative to the current
79
+ # directory
80
+ # - a target name
81
+ # - a toolset
82
+ #
83
+ # build_file is the file relative to which 'target' is defined.
84
+ # target is the qualified target.
85
+ # toolset is the default toolset for that target.
86
+ [parsed_build_file, target, parsed_toolset] = ParseQualifiedTarget(target)
87
+
88
+ if parsed_build_file:
89
+ if build_file:
90
+ # If a relative path, parsed_build_file is relative to the directory
91
+ # containing build_file. If build_file is not in the current directory,
92
+ # parsed_build_file is not a usable path as-is. Resolve it by
93
+ # interpreting it as relative to build_file. If parsed_build_file is
94
+ # absolute, it is usable as a path regardless of the current directory,
95
+ # and os.path.join will return it as-is.
96
+ build_file = os.path.normpath(
97
+ os.path.join(os.path.dirname(build_file), parsed_build_file)
98
+ )
99
+ # Further (to handle cases like ../cwd), make it relative to cwd)
100
+ if not os.path.isabs(build_file):
101
+ build_file = RelativePath(build_file, ".")
102
+ else:
103
+ build_file = parsed_build_file
104
+
105
+ if parsed_toolset:
106
+ toolset = parsed_toolset
107
+
108
+ return [build_file, target, toolset]
109
+
110
+
111
+ def BuildFile(fully_qualified_target):
112
+ # Extracts the build file from the fully qualified target.
113
+ return ParseQualifiedTarget(fully_qualified_target)[0]
114
+
115
+
116
+ def GetEnvironFallback(var_list, default):
117
+ """Look up a key in the environment, with fallback to secondary keys
118
+ and finally falling back to a default value."""
119
+ for var in var_list:
120
+ if var in os.environ:
121
+ return os.environ[var]
122
+ return default
123
+
124
+
125
+ def QualifiedTarget(build_file, target, toolset):
126
+ # "Qualified" means the file that a target was defined in and the target
127
+ # name, separated by a colon, suffixed by a # and the toolset name:
128
+ # /path/to/file.gyp:target_name#toolset
129
+ fully_qualified = build_file + ":" + target
130
+ if toolset:
131
+ fully_qualified = fully_qualified + "#" + toolset
132
+ return fully_qualified
133
+
134
+
135
+ @memoize
136
+ def RelativePath(path, relative_to, follow_path_symlink=True):
137
+ # Assuming both |path| and |relative_to| are relative to the current
138
+ # directory, returns a relative path that identifies path relative to
139
+ # relative_to.
140
+ # If |follow_symlink_path| is true (default) and |path| is a symlink, then
141
+ # this method returns a path to the real file represented by |path|. If it is
142
+ # false, this method returns a path to the symlink. If |path| is not a
143
+ # symlink, this option has no effect.
144
+
145
+ # Convert to normalized (and therefore absolute paths).
146
+ path = os.path.realpath(path) if follow_path_symlink else os.path.abspath(path)
147
+ relative_to = os.path.realpath(relative_to)
148
+
149
+ # On Windows, we can't create a relative path to a different drive, so just
150
+ # use the absolute path.
151
+ if sys.platform == "win32" and (
152
+ os.path.splitdrive(path)[0].lower()
153
+ != os.path.splitdrive(relative_to)[0].lower()
154
+ ):
155
+ return path
156
+
157
+ # Split the paths into components.
158
+ path_split = path.split(os.path.sep)
159
+ relative_to_split = relative_to.split(os.path.sep)
160
+
161
+ # Determine how much of the prefix the two paths share.
162
+ prefix_len = len(os.path.commonprefix([path_split, relative_to_split]))
163
+
164
+ # Put enough ".." components to back up out of relative_to to the common
165
+ # prefix, and then append the part of path_split after the common prefix.
166
+ relative_split = [os.path.pardir] * (
167
+ len(relative_to_split) - prefix_len
168
+ ) + path_split[prefix_len:]
169
+
170
+ if len(relative_split) == 0:
171
+ # The paths were the same.
172
+ return ""
173
+
174
+ # Turn it back into a string and we're done.
175
+ return os.path.join(*relative_split)
176
+
177
+
178
+ @memoize
179
+ def InvertRelativePath(path, toplevel_dir=None):
180
+ """Given a path like foo/bar that is relative to toplevel_dir, return
181
+ the inverse relative path back to the toplevel_dir.
182
+
183
+ E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
184
+ should always produce the empty string, unless the path contains symlinks.
185
+ """
186
+ if not path:
187
+ return path
188
+ toplevel_dir = "." if toplevel_dir is None else toplevel_dir
189
+ return RelativePath(toplevel_dir, os.path.join(toplevel_dir, path))
190
+
191
+
192
+ def FixIfRelativePath(path, relative_to):
193
+ # Like RelativePath but returns |path| unchanged if it is absolute.
194
+ if os.path.isabs(path):
195
+ return path
196
+ return RelativePath(path, relative_to)
197
+
198
+
199
+ def UnrelativePath(path, relative_to):
200
+ # Assuming that |relative_to| is relative to the current directory, and |path|
201
+ # is a path relative to the dirname of |relative_to|, returns a path that
202
+ # identifies |path| relative to the current directory.
203
+ rel_dir = os.path.dirname(relative_to)
204
+ return os.path.normpath(os.path.join(rel_dir, path))
205
+
206
+
207
+ # re objects used by EncodePOSIXShellArgument. See IEEE 1003.1 XCU.2.2 at
208
+ # http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_02
209
+ # and the documentation for various shells.
210
+
211
+ # _quote is a pattern that should match any argument that needs to be quoted
212
+ # with double-quotes by EncodePOSIXShellArgument. It matches the following
213
+ # characters appearing anywhere in an argument:
214
+ # \t, \n, space parameter separators
215
+ # # comments
216
+ # $ expansions (quoted to always expand within one argument)
217
+ # % called out by IEEE 1003.1 XCU.2.2
218
+ # & job control
219
+ # ' quoting
220
+ # (, ) subshell execution
221
+ # *, ?, [ pathname expansion
222
+ # ; command delimiter
223
+ # <, >, | redirection
224
+ # = assignment
225
+ # {, } brace expansion (bash)
226
+ # ~ tilde expansion
227
+ # It also matches the empty string, because "" (or '') is the only way to
228
+ # represent an empty string literal argument to a POSIX shell.
229
+ #
230
+ # This does not match the characters in _escape, because those need to be
231
+ # backslash-escaped regardless of whether they appear in a double-quoted
232
+ # string.
233
+ _quote = re.compile("[\t\n #$%&'()*;<=>?[{|}~]|^$")
234
+
235
+ # _escape is a pattern that should match any character that needs to be
236
+ # escaped with a backslash, whether or not the argument matched the _quote
237
+ # pattern. _escape is used with re.sub to backslash anything in _escape's
238
+ # first match group, hence the (parentheses) in the regular expression.
239
+ #
240
+ # _escape matches the following characters appearing anywhere in an argument:
241
+ # " to prevent POSIX shells from interpreting this character for quoting
242
+ # \ to prevent POSIX shells from interpreting this character for escaping
243
+ # ` to prevent POSIX shells from interpreting this character for command
244
+ # substitution
245
+ # Missing from this list is $, because the desired behavior of
246
+ # EncodePOSIXShellArgument is to permit parameter (variable) expansion.
247
+ #
248
+ # Also missing from this list is !, which bash will interpret as the history
249
+ # expansion character when history is enabled. bash does not enable history
250
+ # by default in non-interactive shells, so this is not thought to be a problem.
251
+ # ! was omitted from this list because bash interprets "\!" as a literal string
252
+ # including the backslash character (avoiding history expansion but retaining
253
+ # the backslash), which would not be correct for argument encoding. Handling
254
+ # this case properly would also be problematic because bash allows the history
255
+ # character to be changed with the histchars shell variable. Fortunately,
256
+ # as history is not enabled in non-interactive shells and
257
+ # EncodePOSIXShellArgument is only expected to encode for non-interactive
258
+ # shells, there is no room for error here by ignoring !.
259
+ _escape = re.compile(r'(["\\`])')
260
+
261
+
262
+ def EncodePOSIXShellArgument(argument):
263
+ """Encodes |argument| suitably for consumption by POSIX shells.
264
+
265
+ argument may be quoted and escaped as necessary to ensure that POSIX shells
266
+ treat the returned value as a literal representing the argument passed to
267
+ this function. Parameter (variable) expansions beginning with $ are allowed
268
+ to remain intact without escaping the $, to allow the argument to contain
269
+ references to variables to be expanded by the shell.
270
+ """
271
+
272
+ if not isinstance(argument, str):
273
+ argument = str(argument)
274
+
275
+ quote = '"' if _quote.search(argument) else ""
276
+
277
+ encoded = quote + re.sub(_escape, r"\\\1", argument) + quote
278
+
279
+ return encoded
280
+
281
+
282
+ def EncodePOSIXShellList(list):
283
+ """Encodes |list| suitably for consumption by POSIX shells.
284
+
285
+ Returns EncodePOSIXShellArgument for each item in list, and joins them
286
+ together using the space character as an argument separator.
287
+ """
288
+
289
+ encoded_arguments = []
290
+ for argument in list:
291
+ encoded_arguments.append(EncodePOSIXShellArgument(argument))
292
+ return " ".join(encoded_arguments)
293
+
294
+
295
+ def DeepDependencyTargets(target_dicts, roots):
296
+ """Returns the recursive list of target dependencies."""
297
+ dependencies = set()
298
+ pending = set(roots)
299
+ while pending:
300
+ # Pluck out one.
301
+ r = pending.pop()
302
+ # Skip if visited already.
303
+ if r in dependencies:
304
+ continue
305
+ # Add it.
306
+ dependencies.add(r)
307
+ # Add its children.
308
+ spec = target_dicts[r]
309
+ pending.update(set(spec.get("dependencies", [])))
310
+ pending.update(set(spec.get("dependencies_original", [])))
311
+ return list(dependencies - set(roots))
312
+
313
+
314
+ def BuildFileTargets(target_list, build_file):
315
+ """From a target_list, returns the subset from the specified build_file.
316
+ """
317
+ return [p for p in target_list if BuildFile(p) == build_file]
318
+
319
+
320
+ def AllTargets(target_list, target_dicts, build_file):
321
+ """Returns all targets (direct and dependencies) for the specified build_file.
322
+ """
323
+ bftargets = BuildFileTargets(target_list, build_file)
324
+ deptargets = DeepDependencyTargets(target_dicts, bftargets)
325
+ return bftargets + deptargets
326
+
327
+
328
+ def WriteOnDiff(filename):
329
+ """Write to a file only if the new contents differ.
330
+
331
+ Arguments:
332
+ filename: name of the file to potentially write to.
333
+ Returns:
334
+ A file like object which will write to temporary file and only overwrite
335
+ the target if it differs (on close).
336
+ """
337
+
338
+ class Writer:
339
+ """Wrapper around file which only covers the target if it differs."""
340
+
341
+ def __init__(self):
342
+ # On Cygwin remove the "dir" argument
343
+ # `C:` prefixed paths are treated as relative,
344
+ # consequently ending up with current dir "/cygdrive/c/..."
345
+ # being prefixed to those, which was
346
+ # obviously a non-existent path,
347
+ # for example: "/cygdrive/c/<some folder>/C:\<my win style abs path>".
348
+ # For more details see:
349
+ # https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp
350
+ base_temp_dir = "" if IsCygwin() else os.path.dirname(filename)
351
+ # Pick temporary file.
352
+ tmp_fd, self.tmp_path = tempfile.mkstemp(
353
+ suffix=".tmp",
354
+ prefix=os.path.split(filename)[1] + ".gyp.",
355
+ dir=base_temp_dir,
356
+ )
357
+ try:
358
+ self.tmp_file = os.fdopen(tmp_fd, "wb")
359
+ except Exception:
360
+ # Don't leave turds behind.
361
+ os.unlink(self.tmp_path)
362
+ raise
363
+
364
+ def __getattr__(self, attrname):
365
+ # Delegate everything else to self.tmp_file
366
+ return getattr(self.tmp_file, attrname)
367
+
368
+ def close(self):
369
+ try:
370
+ # Close tmp file.
371
+ self.tmp_file.close()
372
+ # Determine if different.
373
+ same = False
374
+ try:
375
+ same = filecmp.cmp(self.tmp_path, filename, False)
376
+ except OSError as e:
377
+ if e.errno != errno.ENOENT:
378
+ raise
379
+
380
+ if same:
381
+ # The new file is identical to the old one, just get rid of the new
382
+ # one.
383
+ os.unlink(self.tmp_path)
384
+ else:
385
+ # The new file is different from the old one,
386
+ # or there is no old one.
387
+ # Rename the new file to the permanent name.
388
+ #
389
+ # tempfile.mkstemp uses an overly restrictive mode, resulting in a
390
+ # file that can only be read by the owner, regardless of the umask.
391
+ # There's no reason to not respect the umask here,
392
+ # which means that an extra hoop is required
393
+ # to fetch it and reset the new file's mode.
394
+ #
395
+ # No way to get the umask without setting a new one? Set a safe one
396
+ # and then set it back to the old value.
397
+ umask = os.umask(0o77)
398
+ os.umask(umask)
399
+ os.chmod(self.tmp_path, 0o666 & ~umask)
400
+ if sys.platform == "win32" and os.path.exists(filename):
401
+ # NOTE: on windows (but not cygwin) rename will not replace an
402
+ # existing file, so it must be preceded with a remove.
403
+ # Sadly there is no way to make the switch atomic.
404
+ os.remove(filename)
405
+ os.rename(self.tmp_path, filename)
406
+ except Exception:
407
+ # Don't leave turds behind.
408
+ os.unlink(self.tmp_path)
409
+ raise
410
+
411
+ def write(self, s):
412
+ self.tmp_file.write(s.encode("utf-8"))
413
+
414
+ return Writer()
415
+
416
+
417
+ def EnsureDirExists(path):
418
+ """Make sure the directory for |path| exists."""
419
+ try:
420
+ os.makedirs(os.path.dirname(path))
421
+ except OSError:
422
+ pass
423
+
424
+ def GetCrossCompilerPredefines(): # -> dict
425
+ cmd = []
426
+
427
+ # shlex.split() will eat '\' in posix mode, but
428
+ # setting posix=False will preserve extra '"' cause CreateProcess fail on Windows
429
+ # this makes '\' in %CC_target% and %CFLAGS% work
430
+ def replace_sep(s):
431
+ return s.replace(os.sep, "/") if os.sep != "/" else s
432
+
433
+ if CC := os.environ.get("CC_target") or os.environ.get("CC"):
434
+ cmd += shlex.split(replace_sep(CC))
435
+ if CFLAGS := os.environ.get("CFLAGS"):
436
+ cmd += shlex.split(replace_sep(CFLAGS))
437
+ elif CXX := os.environ.get("CXX_target") or os.environ.get("CXX"):
438
+ cmd += shlex.split(replace_sep(CXX))
439
+ if CXXFLAGS := os.environ.get("CXXFLAGS"):
440
+ cmd += shlex.split(replace_sep(CXXFLAGS))
441
+ else:
442
+ return {}
443
+
444
+ if sys.platform == "win32":
445
+ fd, input = tempfile.mkstemp(suffix=".c")
446
+ real_cmd = [*cmd, "-dM", "-E", "-x", "c", input]
447
+ try:
448
+ os.close(fd)
449
+ stdout = subprocess.run(
450
+ real_cmd, shell=True,
451
+ capture_output=True, check=True
452
+ ).stdout
453
+ finally:
454
+ os.unlink(input)
455
+ else:
456
+ input = "/dev/null"
457
+ real_cmd = [*cmd, "-dM", "-E", "-x", "c", input]
458
+ stdout = subprocess.run(
459
+ real_cmd, shell=False,
460
+ capture_output=True, check=True
461
+ ).stdout
462
+
463
+ defines = {}
464
+ lines = stdout.decode("utf-8").replace("\r\n", "\n").split("\n")
465
+ for line in lines:
466
+ if (line or "").startswith("#define "):
467
+ _, key, *value = line.split(" ")
468
+ defines[key] = " ".join(value)
469
+ return defines
470
+
471
+ def GetFlavorByPlatform():
472
+ """Returns |params.flavor| if it's set, the system's default flavor else."""
473
+ flavors = {
474
+ "cygwin": "win",
475
+ "win32": "win",
476
+ "darwin": "mac",
477
+ }
478
+
479
+ if sys.platform in flavors:
480
+ return flavors[sys.platform]
481
+ if sys.platform.startswith("sunos"):
482
+ return "solaris"
483
+ if sys.platform.startswith(("dragonfly", "freebsd")):
484
+ return "freebsd"
485
+ if sys.platform.startswith("openbsd"):
486
+ return "openbsd"
487
+ if sys.platform.startswith("netbsd"):
488
+ return "netbsd"
489
+ if sys.platform.startswith("aix"):
490
+ return "aix"
491
+ if sys.platform.startswith(("os390", "zos")):
492
+ return "zos"
493
+ if sys.platform == "os400":
494
+ return "os400"
495
+
496
+ return "linux"
497
+
498
+ def GetFlavor(params):
499
+ if "flavor" in params:
500
+ return params["flavor"]
501
+
502
+ defines = GetCrossCompilerPredefines()
503
+ if "__EMSCRIPTEN__" in defines:
504
+ return "emscripten"
505
+ if "__wasm__" in defines:
506
+ return "wasi" if "__wasi__" in defines else "wasm"
507
+
508
+ return GetFlavorByPlatform()
509
+
510
+
511
+ def CopyTool(flavor, out_path, generator_flags={}):
512
+ """Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
513
+ to |out_path|."""
514
+ # aix and solaris just need flock emulation. mac and win use more complicated
515
+ # support scripts.
516
+ prefix = {
517
+ "aix": "flock",
518
+ "os400": "flock",
519
+ "solaris": "flock",
520
+ "mac": "mac",
521
+ "ios": "mac",
522
+ "win": "win",
523
+ }.get(flavor, None)
524
+ if not prefix:
525
+ return
526
+
527
+ # Slurp input file.
528
+ source_path = os.path.join(
529
+ os.path.dirname(os.path.abspath(__file__)), "%s_tool.py" % prefix
530
+ )
531
+ with open(source_path) as source_file:
532
+ source = source_file.readlines()
533
+
534
+ # Set custom header flags.
535
+ header = "# Generated by gyp. Do not edit.\n"
536
+ mac_toolchain_dir = generator_flags.get("mac_toolchain_dir", None)
537
+ if flavor == "mac" and mac_toolchain_dir:
538
+ header += "import os;\nos.environ['DEVELOPER_DIR']='%s'\n" % mac_toolchain_dir
539
+
540
+ # Add header and write it out.
541
+ tool_path = os.path.join(out_path, "gyp-%s-tool" % prefix)
542
+ with open(tool_path, "w") as tool_file:
543
+ tool_file.write("".join([source[0], header] + source[1:]))
544
+
545
+ # Make file executable.
546
+ os.chmod(tool_path, 0o755)
547
+
548
+
549
+ # From Alex Martelli,
550
+ # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
551
+ # ASPN: Python Cookbook: Remove duplicates from a sequence
552
+ # First comment, dated 2001/10/13.
553
+ # (Also in the printed Python Cookbook.)
554
+
555
+
556
+ def uniquer(seq, idfun=lambda x: x):
557
+ seen = {}
558
+ result = []
559
+ for item in seq:
560
+ marker = idfun(item)
561
+ if marker in seen:
562
+ continue
563
+ seen[marker] = 1
564
+ result.append(item)
565
+ return result
566
+
567
+
568
+ # Based on http://code.activestate.com/recipes/576694/.
569
+ class OrderedSet(MutableSet):
570
+ def __init__(self, iterable=None):
571
+ self.end = end = []
572
+ end += [None, end, end] # sentinel node for doubly linked list
573
+ self.map = {} # key --> [key, prev, next]
574
+ if iterable is not None:
575
+ self |= iterable
576
+
577
+ def __len__(self):
578
+ return len(self.map)
579
+
580
+ def __contains__(self, key):
581
+ return key in self.map
582
+
583
+ def add(self, key):
584
+ if key not in self.map:
585
+ end = self.end
586
+ curr = end[1]
587
+ curr[2] = end[1] = self.map[key] = [key, curr, end]
588
+
589
+ def discard(self, key):
590
+ if key in self.map:
591
+ key, prev_item, next_item = self.map.pop(key)
592
+ prev_item[2] = next_item
593
+ next_item[1] = prev_item
594
+
595
+ def __iter__(self):
596
+ end = self.end
597
+ curr = end[2]
598
+ while curr is not end:
599
+ yield curr[0]
600
+ curr = curr[2]
601
+
602
+ def __reversed__(self):
603
+ end = self.end
604
+ curr = end[1]
605
+ while curr is not end:
606
+ yield curr[0]
607
+ curr = curr[1]
608
+
609
+ # The second argument is an addition that causes a pylint warning.
610
+ def pop(self, last=True): # pylint: disable=W0221
611
+ if not self:
612
+ raise KeyError("set is empty")
613
+ key = self.end[1][0] if last else self.end[2][0]
614
+ self.discard(key)
615
+ return key
616
+
617
+ def __repr__(self):
618
+ if not self:
619
+ return f"{self.__class__.__name__}()"
620
+ return f"{self.__class__.__name__}({list(self)!r})"
621
+
622
+ def __eq__(self, other):
623
+ if isinstance(other, OrderedSet):
624
+ return len(self) == len(other) and list(self) == list(other)
625
+ return set(self) == set(other)
626
+
627
+ # Extensions to the recipe.
628
+ def update(self, iterable):
629
+ for i in iterable:
630
+ if i not in self:
631
+ self.add(i)
632
+
633
+
634
+ class CycleError(Exception):
635
+ """An exception raised when an unexpected cycle is detected."""
636
+
637
+ def __init__(self, nodes):
638
+ self.nodes = nodes
639
+
640
+ def __str__(self):
641
+ return "CycleError: cycle involving: " + str(self.nodes)
642
+
643
+
644
+ def TopologicallySorted(graph, get_edges):
645
+ r"""Topologically sort based on a user provided edge definition.
646
+
647
+ Args:
648
+ graph: A list of node names.
649
+ get_edges: A function mapping from node name to a hashable collection
650
+ of node names which this node has outgoing edges to.
651
+ Returns:
652
+ A list containing all of the node in graph in topological order.
653
+ It is assumed that calling get_edges once for each node and caching is
654
+ cheaper than repeatedly calling get_edges.
655
+ Raises:
656
+ CycleError in the event of a cycle.
657
+ Example:
658
+ graph = {'a': '$(b) $(c)', 'b': 'hi', 'c': '$(b)'}
659
+ def GetEdges(node):
660
+ return re.findall(r'\$\(([^))]\)', graph[node])
661
+ print TopologicallySorted(graph.keys(), GetEdges)
662
+ ==>
663
+ ['a', 'c', b']
664
+ """
665
+ get_edges = memoize(get_edges)
666
+ visited = set()
667
+ visiting = set()
668
+ ordered_nodes = []
669
+
670
+ def Visit(node):
671
+ if node in visiting:
672
+ raise CycleError(visiting)
673
+ if node in visited:
674
+ return
675
+ visited.add(node)
676
+ visiting.add(node)
677
+ for neighbor in get_edges(node):
678
+ Visit(neighbor)
679
+ visiting.remove(node)
680
+ ordered_nodes.insert(0, node)
681
+
682
+ for node in sorted(graph):
683
+ Visit(node)
684
+ return ordered_nodes
685
+
686
+
687
+ def CrossCompileRequested():
688
+ # TODO: figure out how to not build extra host objects in the
689
+ # non-cross-compile case when this is enabled, and enable unconditionally.
690
+ return (
691
+ os.environ.get("GYP_CROSSCOMPILE")
692
+ or os.environ.get("AR_host")
693
+ or os.environ.get("CC_host")
694
+ or os.environ.get("CXX_host")
695
+ or os.environ.get("AR_target")
696
+ or os.environ.get("CC_target")
697
+ or os.environ.get("CXX_target")
698
+ )
699
+
700
+
701
+ def IsCygwin():
702
+ try:
703
+ out = subprocess.Popen(
704
+ "uname", stdout=subprocess.PIPE, stderr=subprocess.STDOUT
705
+ )
706
+ stdout = out.communicate()[0].decode("utf-8")
707
+ return "CYGWIN" in str(stdout)
708
+ except Exception:
709
+ return False