6fe1f3f1cf22699c8fb374ed943fcd55e0b3e7eee40887ccbd2d8a2514c32abb69d762baef73f7bfc0589b3391b11ca88c613225bccaf6eeede5772569c134 24 KB

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