__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. from __future__ import annotations
  2. import functools
  3. import logging
  4. import os
  5. import pathlib
  6. import sys
  7. import sysconfig
  8. from pip._internal.models.scheme import SCHEME_KEYS, Scheme
  9. from pip._internal.utils.compat import WINDOWS
  10. from pip._internal.utils.deprecation import deprecated
  11. from pip._internal.utils.virtualenv import running_under_virtualenv
  12. from . import _sysconfig
  13. from .base import (
  14. USER_CACHE_DIR,
  15. get_major_minor_version,
  16. get_src_prefix,
  17. is_osx_framework,
  18. site_packages,
  19. user_site,
  20. )
  21. __all__ = [
  22. "USER_CACHE_DIR",
  23. "get_bin_prefix",
  24. "get_bin_user",
  25. "get_major_minor_version",
  26. "get_platlib",
  27. "get_purelib",
  28. "get_scheme",
  29. "get_src_prefix",
  30. "site_packages",
  31. "user_site",
  32. ]
  33. logger = logging.getLogger(__name__)
  34. _PLATLIBDIR: str = getattr(sys, "platlibdir", "lib")
  35. _USE_SYSCONFIG_DEFAULT = sys.version_info >= (3, 10)
  36. def _should_use_sysconfig() -> bool:
  37. """This function determines the value of _USE_SYSCONFIG.
  38. By default, pip uses sysconfig on Python 3.10+.
  39. But Python distributors can override this decision by setting:
  40. sysconfig._PIP_USE_SYSCONFIG = True / False
  41. Rationale in https://github.com/pypa/pip/issues/10647
  42. This is a function for testability, but should be constant during any one
  43. run.
  44. """
  45. return bool(getattr(sysconfig, "_PIP_USE_SYSCONFIG", _USE_SYSCONFIG_DEFAULT))
  46. _USE_SYSCONFIG = _should_use_sysconfig()
  47. if not _USE_SYSCONFIG:
  48. # Import distutils lazily to avoid deprecation warnings,
  49. # but import it soon enough that it is in memory and available during
  50. # a pip reinstall.
  51. from . import _distutils
  52. # Be noisy about incompatibilities if this platforms "should" be using
  53. # sysconfig, but is explicitly opting out and using distutils instead.
  54. if _USE_SYSCONFIG_DEFAULT and not _USE_SYSCONFIG:
  55. _MISMATCH_LEVEL = logging.WARNING
  56. else:
  57. _MISMATCH_LEVEL = logging.DEBUG
  58. def _looks_like_bpo_44860() -> bool:
  59. """The resolution to bpo-44860 will change this incorrect platlib.
  60. See <https://bugs.python.org/issue44860>.
  61. """
  62. from distutils.command.install import INSTALL_SCHEMES
  63. try:
  64. unix_user_platlib = INSTALL_SCHEMES["unix_user"]["platlib"]
  65. except KeyError:
  66. return False
  67. return unix_user_platlib == "$usersite"
  68. def _looks_like_red_hat_patched_platlib_purelib(scheme: dict[str, str]) -> bool:
  69. platlib = scheme["platlib"]
  70. if "/$platlibdir/" in platlib:
  71. platlib = platlib.replace("/$platlibdir/", f"/{_PLATLIBDIR}/")
  72. if "/lib64/" not in platlib:
  73. return False
  74. unpatched = platlib.replace("/lib64/", "/lib/")
  75. return unpatched.replace("$platbase/", "$base/") == scheme["purelib"]
  76. @functools.cache
  77. def _looks_like_red_hat_lib() -> bool:
  78. """Red Hat patches platlib in unix_prefix and unix_home, but not purelib.
  79. This is the only way I can see to tell a Red Hat-patched Python.
  80. """
  81. from distutils.command.install import INSTALL_SCHEMES
  82. return all(
  83. k in INSTALL_SCHEMES
  84. and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])
  85. for k in ("unix_prefix", "unix_home")
  86. )
  87. @functools.cache
  88. def _looks_like_debian_scheme() -> bool:
  89. """Debian adds two additional schemes."""
  90. from distutils.command.install import INSTALL_SCHEMES
  91. return "deb_system" in INSTALL_SCHEMES and "unix_local" in INSTALL_SCHEMES
  92. @functools.cache
  93. def _looks_like_red_hat_scheme() -> bool:
  94. """Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.
  95. Red Hat's ``00251-change-user-install-location.patch`` changes the install
  96. command's ``prefix`` and ``exec_prefix`` to append ``"/local"``. This is
  97. (fortunately?) done quite unconditionally, so we create a default command
  98. object without any configuration to detect this.
  99. """
  100. from distutils.command.install import install
  101. from distutils.dist import Distribution
  102. cmd = install(Distribution())
  103. cmd.finalize_options()
  104. return (
  105. cmd.exec_prefix == f"{os.path.normpath(sys.exec_prefix)}/local"
  106. and cmd.prefix == f"{os.path.normpath(sys.prefix)}/local"
  107. )
  108. @functools.cache
  109. def _looks_like_slackware_scheme() -> bool:
  110. """Slackware patches sysconfig but fails to patch distutils and site.
  111. Slackware changes sysconfig's user scheme to use ``"lib64"`` for the lib
  112. path, but does not do the same to the site module.
  113. """
  114. if user_site is None: # User-site not available.
  115. return False
  116. try:
  117. paths = sysconfig.get_paths(scheme="posix_user", expand=False)
  118. except KeyError: # User-site not available.
  119. return False
  120. return "/lib64/" in paths["purelib"] and "/lib64/" not in user_site
  121. @functools.cache
  122. def _looks_like_msys2_mingw_scheme() -> bool:
  123. """MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.
  124. However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is
  125. likely going to be included in their 3.10 release, so we ignore the warning.
  126. See msys2/MINGW-packages#9319.
  127. MSYS2 MINGW's patch uses lowercase ``"lib"`` instead of the usual uppercase,
  128. and is missing the final ``"site-packages"``.
  129. """
  130. paths = sysconfig.get_paths("nt", expand=False)
  131. return all(
  132. "Lib" not in p and "lib" in p and not p.endswith("site-packages")
  133. for p in (paths[key] for key in ("platlib", "purelib"))
  134. )
  135. @functools.cache
  136. def _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None:
  137. issue_url = "https://github.com/pypa/pip/issues/10151"
  138. message = (
  139. "Value for %s does not match. Please report this to <%s>"
  140. "\ndistutils: %s"
  141. "\nsysconfig: %s"
  142. )
  143. logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new)
  144. def _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool:
  145. if old == new:
  146. return False
  147. _warn_mismatched(old, new, key=key)
  148. return True
  149. @functools.cache
  150. def _log_context(
  151. *,
  152. user: bool = False,
  153. home: str | None = None,
  154. root: str | None = None,
  155. prefix: str | None = None,
  156. ) -> None:
  157. parts = [
  158. "Additional context:",
  159. "user = %r",
  160. "home = %r",
  161. "root = %r",
  162. "prefix = %r",
  163. ]
  164. logger.log(_MISMATCH_LEVEL, "\n".join(parts), user, home, root, prefix)
  165. def get_scheme(
  166. dist_name: str,
  167. user: bool = False,
  168. home: str | None = None,
  169. root: str | None = None,
  170. isolated: bool = False,
  171. prefix: str | None = None,
  172. ) -> Scheme:
  173. new = _sysconfig.get_scheme(
  174. dist_name,
  175. user=user,
  176. home=home,
  177. root=root,
  178. isolated=isolated,
  179. prefix=prefix,
  180. )
  181. if _USE_SYSCONFIG:
  182. return new
  183. old = _distutils.get_scheme(
  184. dist_name,
  185. user=user,
  186. home=home,
  187. root=root,
  188. isolated=isolated,
  189. prefix=prefix,
  190. )
  191. warning_contexts = []
  192. for k in SCHEME_KEYS:
  193. old_v = pathlib.Path(getattr(old, k))
  194. new_v = pathlib.Path(getattr(new, k))
  195. if old_v == new_v:
  196. continue
  197. # distutils incorrectly put PyPy packages under ``site-packages/python``
  198. # in the ``posix_home`` scheme, but PyPy devs said they expect the
  199. # directory name to be ``pypy`` instead. So we treat this as a bug fix
  200. # and not warn about it. See bpo-43307 and python/cpython#24628.
  201. skip_pypy_special_case = (
  202. sys.implementation.name == "pypy"
  203. and home is not None
  204. and k in ("platlib", "purelib")
  205. and old_v.parent == new_v.parent
  206. and old_v.name.startswith("python")
  207. and new_v.name.startswith("pypy")
  208. )
  209. if skip_pypy_special_case:
  210. continue
  211. # sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in
  212. # the ``include`` value, but distutils's ``headers`` does. We'll let
  213. # CPython decide whether this is a bug or feature. See bpo-43948.
  214. skip_osx_framework_user_special_case = (
  215. user
  216. and is_osx_framework()
  217. and k == "headers"
  218. and old_v.parent.parent == new_v.parent
  219. and old_v.parent.name.startswith("python")
  220. )
  221. if skip_osx_framework_user_special_case:
  222. continue
  223. # On Red Hat and derived Linux distributions, distutils is patched to
  224. # use "lib64" instead of "lib" for platlib.
  225. if k == "platlib" and _looks_like_red_hat_lib():
  226. continue
  227. # On Python 3.9+, sysconfig's posix_user scheme sets platlib against
  228. # sys.platlibdir, but distutils's unix_user incorrectly continues
  229. # using the same $usersite for both platlib and purelib. This creates a
  230. # mismatch when sys.platlibdir is not "lib".
  231. skip_bpo_44860 = (
  232. user
  233. and k == "platlib"
  234. and not WINDOWS
  235. and _PLATLIBDIR != "lib"
  236. and _looks_like_bpo_44860()
  237. )
  238. if skip_bpo_44860:
  239. continue
  240. # Slackware incorrectly patches posix_user to use lib64 instead of lib,
  241. # but not usersite to match the location.
  242. skip_slackware_user_scheme = (
  243. user
  244. and k in ("platlib", "purelib")
  245. and not WINDOWS
  246. and _looks_like_slackware_scheme()
  247. )
  248. if skip_slackware_user_scheme:
  249. continue
  250. # Both Debian and Red Hat patch Python to place the system site under
  251. # /usr/local instead of /usr. Debian also places lib in dist-packages
  252. # instead of site-packages, but the /usr/local check should cover it.
  253. skip_linux_system_special_case = (
  254. not (user or home or prefix or running_under_virtualenv())
  255. and old_v.parts[1:3] == ("usr", "local")
  256. and len(new_v.parts) > 1
  257. and new_v.parts[1] == "usr"
  258. and (len(new_v.parts) < 3 or new_v.parts[2] != "local")
  259. and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme())
  260. )
  261. if skip_linux_system_special_case:
  262. continue
  263. # MSYS2 MINGW's sysconfig patch does not include the "site-packages"
  264. # part of the path. This is incorrect and will be fixed in MSYS.
  265. skip_msys2_mingw_bug = (
  266. WINDOWS and k in ("platlib", "purelib") and _looks_like_msys2_mingw_scheme()
  267. )
  268. if skip_msys2_mingw_bug:
  269. continue
  270. # CPython's POSIX install script invokes pip (via ensurepip) against the
  271. # interpreter located in the source tree, not the install site. This
  272. # triggers special logic in sysconfig that's not present in distutils.
  273. # https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194
  274. skip_cpython_build = (
  275. sysconfig.is_python_build(check_home=True)
  276. and not WINDOWS
  277. and k in ("headers", "include", "platinclude")
  278. )
  279. if skip_cpython_build:
  280. continue
  281. warning_contexts.append((old_v, new_v, f"scheme.{k}"))
  282. if not warning_contexts:
  283. return old
  284. # Check if this path mismatch is caused by distutils config files. Those
  285. # files will no longer work once we switch to sysconfig, so this raises a
  286. # deprecation message for them.
  287. default_old = _distutils.distutils_scheme(
  288. dist_name,
  289. user,
  290. home,
  291. root,
  292. isolated,
  293. prefix,
  294. ignore_config_files=True,
  295. )
  296. if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS):
  297. deprecated(
  298. reason=(
  299. "Configuring installation scheme with distutils config files "
  300. "is deprecated and will no longer work in the near future. If you "
  301. "are using a Homebrew or Linuxbrew Python, please see discussion "
  302. "at https://github.com/Homebrew/homebrew-core/issues/76621"
  303. ),
  304. replacement=None,
  305. gone_in=None,
  306. )
  307. return old
  308. # Post warnings about this mismatch so user can report them back.
  309. for old_v, new_v, key in warning_contexts:
  310. _warn_mismatched(old_v, new_v, key=key)
  311. _log_context(user=user, home=home, root=root, prefix=prefix)
  312. return old
  313. def get_bin_prefix() -> str:
  314. new = _sysconfig.get_bin_prefix()
  315. if _USE_SYSCONFIG:
  316. return new
  317. old = _distutils.get_bin_prefix()
  318. if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="bin_prefix"):
  319. _log_context()
  320. return old
  321. def get_bin_user() -> str:
  322. return _sysconfig.get_scheme("", user=True).scripts
  323. def _looks_like_deb_system_dist_packages(value: str) -> bool:
  324. """Check if the value is Debian's APT-controlled dist-packages.
  325. Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the
  326. default package path controlled by APT, but does not patch ``sysconfig`` to
  327. do the same. This is similar to the bug worked around in ``get_scheme()``,
  328. but here the default is ``deb_system`` instead of ``unix_local``. Ultimately
  329. we can't do anything about this Debian bug, and this detection allows us to
  330. skip the warning when needed.
  331. """
  332. if not _looks_like_debian_scheme():
  333. return False
  334. if value == "/usr/lib/python3/dist-packages":
  335. return True
  336. return False
  337. def get_purelib() -> str:
  338. """Return the default pure-Python lib location."""
  339. new = _sysconfig.get_purelib()
  340. if _USE_SYSCONFIG:
  341. return new
  342. old = _distutils.get_purelib()
  343. if _looks_like_deb_system_dist_packages(old):
  344. return old
  345. if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="purelib"):
  346. _log_context()
  347. return old
  348. def get_platlib() -> str:
  349. """Return the default platform-shared lib location."""
  350. new = _sysconfig.get_platlib()
  351. if _USE_SYSCONFIG:
  352. return new
  353. from . import _distutils
  354. old = _distutils.get_platlib()
  355. if _looks_like_deb_system_dist_packages(old):
  356. return old
  357. if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key="platlib"):
  358. _log_context()
  359. return old