locations.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. """Locations where we look for configs, install stuff, etc"""
  2. # The following comment should be removed at some point in the future.
  3. # mypy: strict-optional=False
  4. # mypy: disallow-untyped-defs=False
  5. from __future__ import absolute_import
  6. import os
  7. import os.path
  8. import platform
  9. import site
  10. import sys
  11. import sysconfig
  12. from distutils import sysconfig as distutils_sysconfig
  13. from distutils.command.install import SCHEME_KEYS # type: ignore
  14. from pip._internal.utils import appdirs
  15. from pip._internal.utils.compat import WINDOWS
  16. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  17. from pip._internal.utils.virtualenv import running_under_virtualenv
  18. if MYPY_CHECK_RUNNING:
  19. from typing import Any, Union, Dict, List, Optional
  20. # Application Directories
  21. USER_CACHE_DIR = appdirs.user_cache_dir("pip")
  22. def get_major_minor_version():
  23. # type: () -> str
  24. """
  25. Return the major-minor version of the current Python as a string, e.g.
  26. "3.7" or "3.10".
  27. """
  28. return '{}.{}'.format(*sys.version_info)
  29. def get_src_prefix():
  30. if running_under_virtualenv():
  31. src_prefix = os.path.join(sys.prefix, 'src')
  32. else:
  33. # FIXME: keep src in cwd for now (it is not a temporary folder)
  34. try:
  35. src_prefix = os.path.join(os.getcwd(), 'src')
  36. except OSError:
  37. # In case the current working directory has been renamed or deleted
  38. sys.exit(
  39. "The folder you are executing pip from can no longer be found."
  40. )
  41. # under macOS + virtualenv sys.prefix is not properly resolved
  42. # it is something like /path/to/python/bin/..
  43. return os.path.abspath(src_prefix)
  44. # FIXME doesn't account for venv linked to global site-packages
  45. site_packages = sysconfig.get_path("purelib") # type: Optional[str]
  46. # This is because of a bug in PyPy's sysconfig module, see
  47. # https://bitbucket.org/pypy/pypy/issues/2506/sysconfig-returns-incorrect-paths
  48. # for more information.
  49. if platform.python_implementation().lower() == "pypy":
  50. site_packages = distutils_sysconfig.get_python_lib()
  51. try:
  52. # Use getusersitepackages if this is present, as it ensures that the
  53. # value is initialised properly.
  54. user_site = site.getusersitepackages()
  55. except AttributeError:
  56. user_site = site.USER_SITE
  57. if WINDOWS:
  58. bin_py = os.path.join(sys.prefix, 'Scripts')
  59. bin_user = os.path.join(user_site, 'Scripts')
  60. # buildout uses 'bin' on Windows too?
  61. if not os.path.exists(bin_py):
  62. bin_py = os.path.join(sys.prefix, 'bin')
  63. bin_user = os.path.join(user_site, 'bin')
  64. else:
  65. bin_py = os.path.join(sys.prefix, 'bin')
  66. bin_user = os.path.join(user_site, 'bin')
  67. # Forcing to use /usr/local/bin for standard macOS framework installs
  68. # Also log to ~/Library/Logs/ for use with the Console.app log viewer
  69. if sys.platform[:6] == 'darwin' and sys.prefix[:16] == '/System/Library/':
  70. bin_py = '/usr/local/bin'
  71. def distutils_scheme(dist_name, user=False, home=None, root=None,
  72. isolated=False, prefix=None):
  73. # type:(str, bool, str, str, bool, str) -> dict
  74. """
  75. Return a distutils install scheme
  76. """
  77. from distutils.dist import Distribution
  78. scheme = {}
  79. if isolated:
  80. extra_dist_args = {"script_args": ["--no-user-cfg"]}
  81. else:
  82. extra_dist_args = {}
  83. dist_args = {'name': dist_name} # type: Dict[str, Union[str, List[str]]]
  84. dist_args.update(extra_dist_args)
  85. d = Distribution(dist_args)
  86. # Ignoring, typeshed issue reported python/typeshed/issues/2567
  87. d.parse_config_files()
  88. # NOTE: Ignoring type since mypy can't find attributes on 'Command'
  89. i = d.get_command_obj('install', create=True) # type: Any
  90. assert i is not None
  91. # NOTE: setting user or home has the side-effect of creating the home dir
  92. # or user base for installations during finalize_options()
  93. # ideally, we'd prefer a scheme class that has no side-effects.
  94. assert not (user and prefix), "user={} prefix={}".format(user, prefix)
  95. assert not (home and prefix), "home={} prefix={}".format(home, prefix)
  96. i.user = user or i.user
  97. if user or home:
  98. i.prefix = ""
  99. i.prefix = prefix or i.prefix
  100. i.home = home or i.home
  101. i.root = root or i.root
  102. i.finalize_options()
  103. for key in SCHEME_KEYS:
  104. scheme[key] = getattr(i, 'install_' + key)
  105. # install_lib specified in setup.cfg should install *everything*
  106. # into there (i.e. it takes precedence over both purelib and
  107. # platlib). Note, i.install_lib is *always* set after
  108. # finalize_options(); we only want to override here if the user
  109. # has explicitly requested it hence going back to the config
  110. # Ignoring, typeshed issue reported python/typeshed/issues/2567
  111. if 'install_lib' in d.get_option_dict('install'): # type: ignore
  112. scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))
  113. if running_under_virtualenv():
  114. scheme['headers'] = os.path.join(
  115. sys.prefix,
  116. 'include',
  117. 'site',
  118. 'python{}'.format(get_major_minor_version()),
  119. dist_name,
  120. )
  121. if root is not None:
  122. path_no_drive = os.path.splitdrive(
  123. os.path.abspath(scheme["headers"]))[1]
  124. scheme["headers"] = os.path.join(
  125. root,
  126. path_no_drive[1:],
  127. )
  128. return scheme