common.py 22 KB

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