11cb0ef41Sopenharmony_ci# Copyright 2014 the V8 project authors. All rights reserved.
21cb0ef41Sopenharmony_ci# Use of this source code is governed by a BSD-style license that can be
31cb0ef41Sopenharmony_ci# found in the LICENSE file.
41cb0ef41Sopenharmony_ci"""Small utility function to find depot_tools and add it to the python path.
51cb0ef41Sopenharmony_ci"""
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ci# for py2/py3 compatibility
81cb0ef41Sopenharmony_cifrom __future__ import print_function
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ciimport os
111cb0ef41Sopenharmony_ciimport sys
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci
141cb0ef41Sopenharmony_cidef directory_really_is_depot_tools(directory):
151cb0ef41Sopenharmony_ci  return os.path.isfile(os.path.join(directory, 'gclient.py'))
161cb0ef41Sopenharmony_ci
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_cidef add_depot_tools_to_path():
191cb0ef41Sopenharmony_ci  """Search for depot_tools and add it to sys.path."""
201cb0ef41Sopenharmony_ci  # First look if depot_tools is already in PYTHONPATH.
211cb0ef41Sopenharmony_ci  for i in sys.path:
221cb0ef41Sopenharmony_ci    if i.rstrip(os.sep).endswith('depot_tools'):
231cb0ef41Sopenharmony_ci      if directory_really_is_depot_tools(i):
241cb0ef41Sopenharmony_ci        return i
251cb0ef41Sopenharmony_ci
261cb0ef41Sopenharmony_ci  # Then look if depot_tools is in PATH, common case.
271cb0ef41Sopenharmony_ci  for i in os.environ['PATH'].split(os.pathsep):
281cb0ef41Sopenharmony_ci    if i.rstrip(os.sep).endswith('depot_tools'):
291cb0ef41Sopenharmony_ci      if directory_really_is_depot_tools(i):
301cb0ef41Sopenharmony_ci        sys.path.insert(0, i.rstrip(os.sep))
311cb0ef41Sopenharmony_ci        return i
321cb0ef41Sopenharmony_ci  # Rare case, it's not even in PATH, look upward up to root.
331cb0ef41Sopenharmony_ci  root_dir = os.path.dirname(os.path.abspath(__file__))
341cb0ef41Sopenharmony_ci  previous_dir = os.path.abspath(__file__)
351cb0ef41Sopenharmony_ci  while root_dir and root_dir != previous_dir:
361cb0ef41Sopenharmony_ci    if directory_really_is_depot_tools(os.path.join(root_dir, 'depot_tools')):
371cb0ef41Sopenharmony_ci      i = os.path.join(root_dir, 'depot_tools')
381cb0ef41Sopenharmony_ci      sys.path.insert(0, i)
391cb0ef41Sopenharmony_ci      return i
401cb0ef41Sopenharmony_ci    previous_dir = root_dir
411cb0ef41Sopenharmony_ci    root_dir = os.path.dirname(root_dir)
421cb0ef41Sopenharmony_ci  print('Failed to find depot_tools', file=sys.stderr)
431cb0ef41Sopenharmony_ci  return None
44