gclient_paths.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # Copyright 2019 The Chromium Authors. 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. # This file is imported by various thin wrappers (around gn, clang-format, ...),
  5. # so it's meant to import very quickly. To keep it that way don't add more
  6. # code, and even more importantly don't add more toplevel import statements,
  7. # particularly for modules that are not builtin (see sys.builtin_modules_names,
  8. # os isn't built in, but it's essential to this file).
  9. import functools
  10. import logging
  11. import os
  12. import sys
  13. import gclient_utils
  14. import subprocess2
  15. # TODO: Should fix these warnings.
  16. # pylint: disable=line-too-long
  17. @functools.lru_cache
  18. def FindGclientRoot(from_dir, filename='.gclient'):
  19. """Tries to find the gclient root."""
  20. real_from_dir = os.path.abspath(from_dir)
  21. path = real_from_dir
  22. while not os.path.exists(os.path.join(path, filename)):
  23. split_path = os.path.split(path)
  24. if not split_path[1]:
  25. return None
  26. path = split_path[0]
  27. logging.info('Found gclient root at ' + path)
  28. if path == real_from_dir:
  29. return path
  30. # If we did not find the file in the current directory, make sure we are in
  31. # a sub directory that is controlled by this configuration.
  32. entries_filename = os.path.join(path, filename + '_entries')
  33. if not os.path.exists(entries_filename):
  34. # If .gclient_entries does not exist, a previous call to gclient sync
  35. # might have failed. In that case, we cannot verify that the .gclient
  36. # is the one we want to use. In order to not to cause too much trouble,
  37. # just issue a warning and return the path anyway.
  38. print(
  39. "%s missing, %s file in parent directory %s might not be the file "
  40. "you want to use." % (entries_filename, filename, path),
  41. file=sys.stderr)
  42. return path
  43. entries_content = gclient_utils.FileRead(entries_filename)
  44. scope = {}
  45. try:
  46. exec(entries_content, scope)
  47. except (SyntaxError, Exception) as e:
  48. gclient_utils.SyntaxErrorToError(filename, e)
  49. all_directories = scope['entries'].keys()
  50. path_to_check = os.path.relpath(real_from_dir, path)
  51. while path_to_check:
  52. if path_to_check in all_directories:
  53. return path
  54. path_to_check = os.path.dirname(path_to_check)
  55. return None
  56. @functools.lru_cache
  57. def _GetPrimarySolutionPathInternal(cwd):
  58. gclient_root = FindGclientRoot(cwd)
  59. if gclient_root:
  60. # Some projects' top directory is not named 'src'.
  61. source_dir_name = GetGClientPrimarySolutionName(gclient_root) or 'src'
  62. return os.path.join(gclient_root, source_dir_name)
  63. # Some projects might not use .gclient. Try to see whether we're in a git
  64. # checkout that contains a 'buildtools' subdir.
  65. top_dir = cwd
  66. try:
  67. top_dir = subprocess2.check_output(
  68. ['git', 'rev-parse', '--show-toplevel'], stderr=subprocess2.DEVNULL)
  69. top_dir = top_dir.decode('utf-8', 'replace')
  70. top_dir = os.path.normpath(top_dir.strip())
  71. except subprocess2.CalledProcessError:
  72. pass
  73. if os.path.exists(os.path.join(top_dir, 'buildtools')):
  74. return top_dir
  75. return None
  76. def GetPrimarySolutionPath():
  77. """Returns the full path to the primary solution. (gclient_root + src)"""
  78. return _GetPrimarySolutionPathInternal(os.getcwd())
  79. @functools.lru_cache
  80. def _GetBuildtoolsPathInternal(cwd, override):
  81. if override is not None:
  82. return override
  83. primary_solution = GetPrimarySolutionPath()
  84. if not primary_solution:
  85. return None
  86. buildtools_path = os.path.join(primary_solution, 'buildtools')
  87. if os.path.exists(buildtools_path):
  88. return buildtools_path
  89. # buildtools may be in the gclient root.
  90. gclient_root = FindGclientRoot(os.getcwd())
  91. buildtools_path = os.path.join(gclient_root, 'buildtools')
  92. if os.path.exists(buildtools_path):
  93. return buildtools_path
  94. return None
  95. def GetBuildtoolsPath():
  96. """Returns the full path to the buildtools directory.
  97. This is based on the root of the checkout containing the current directory."""
  98. # Overriding the build tools path by environment is highly unsupported and
  99. # may break without warning. Do not rely on this for anything important.
  100. override = os.environ.get('CHROMIUM_BUILDTOOLS_PATH')
  101. return _GetBuildtoolsPathInternal(os.getcwd(), override)
  102. def GetBuildtoolsPlatformBinaryPath():
  103. """Returns the full path to the binary directory for the current platform."""
  104. buildtools_path = GetBuildtoolsPath()
  105. if not buildtools_path:
  106. return None
  107. if sys.platform.startswith(('cygwin', 'win')):
  108. subdir = 'win'
  109. elif sys.platform == 'darwin':
  110. subdir = 'mac'
  111. elif sys.platform.startswith('linux'):
  112. subdir = 'linux64'
  113. else:
  114. raise gclient_utils.Error('Unknown platform: ' + sys.platform)
  115. return os.path.join(buildtools_path, subdir)
  116. def GetExeSuffix():
  117. """Returns '' or '.exe' depending on how executables work on this platform."""
  118. if sys.platform.startswith(('cygwin', 'win')):
  119. return '.exe'
  120. return ''
  121. @functools.lru_cache
  122. def GetGClientPrimarySolutionName(gclient_root_dir_path):
  123. """Returns the name of the primary solution in the .gclient file specified."""
  124. gclient_config_file = os.path.join(gclient_root_dir_path, '.gclient')
  125. gclient_config_contents = gclient_utils.FileRead(gclient_config_file)
  126. env = {}
  127. exec(gclient_config_contents, env)
  128. solutions = env.get('solutions', [])
  129. if solutions:
  130. return solutions[0].get('name')
  131. return None