@flun/nodejs-mobile-gyp 1.0.1

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