misc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. from __future__ import annotations
  2. import errno
  3. import getpass
  4. import hashlib
  5. import logging
  6. import os
  7. import posixpath
  8. import shutil
  9. import stat
  10. import sys
  11. import sysconfig
  12. import urllib.parse
  13. from collections.abc import Generator, Iterable, Iterator, Mapping, Sequence
  14. from dataclasses import dataclass
  15. from functools import partial
  16. from io import StringIO
  17. from itertools import filterfalse, tee, zip_longest
  18. from pathlib import Path
  19. from types import FunctionType, TracebackType
  20. from typing import (
  21. Any,
  22. BinaryIO,
  23. Callable,
  24. Optional,
  25. TextIO,
  26. TypeVar,
  27. cast,
  28. )
  29. from pip._vendor.packaging.requirements import Requirement
  30. from pip._vendor.pyproject_hooks import BuildBackendHookCaller
  31. from pip import __version__
  32. from pip._internal.exceptions import CommandError, ExternallyManagedEnvironment
  33. from pip._internal.locations import get_major_minor_version
  34. from pip._internal.utils.compat import WINDOWS
  35. from pip._internal.utils.retry import retry
  36. from pip._internal.utils.virtualenv import running_under_virtualenv
  37. __all__ = [
  38. "rmtree",
  39. "display_path",
  40. "backup_dir",
  41. "ask",
  42. "splitext",
  43. "format_size",
  44. "is_installable_dir",
  45. "normalize_path",
  46. "renames",
  47. "get_prog",
  48. "ensure_dir",
  49. "remove_auth_from_url",
  50. "check_externally_managed",
  51. "ConfiguredBuildBackendHookCaller",
  52. ]
  53. logger = logging.getLogger(__name__)
  54. T = TypeVar("T")
  55. ExcInfo = tuple[type[BaseException], BaseException, TracebackType]
  56. VersionInfo = tuple[int, int, int]
  57. NetlocTuple = tuple[str, tuple[Optional[str], Optional[str]]]
  58. OnExc = Callable[[FunctionType, Path, BaseException], Any]
  59. OnErr = Callable[[FunctionType, Path, ExcInfo], Any]
  60. FILE_CHUNK_SIZE = 1024 * 1024
  61. def get_pip_version() -> str:
  62. pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
  63. pip_pkg_dir = os.path.abspath(pip_pkg_dir)
  64. return f"pip {__version__} from {pip_pkg_dir} (python {get_major_minor_version()})"
  65. def normalize_version_info(py_version_info: tuple[int, ...]) -> tuple[int, int, int]:
  66. """
  67. Convert a tuple of ints representing a Python version to one of length
  68. three.
  69. :param py_version_info: a tuple of ints representing a Python version,
  70. or None to specify no version. The tuple can have any length.
  71. :return: a tuple of length three if `py_version_info` is non-None.
  72. Otherwise, return `py_version_info` unchanged (i.e. None).
  73. """
  74. if len(py_version_info) < 3:
  75. py_version_info += (3 - len(py_version_info)) * (0,)
  76. elif len(py_version_info) > 3:
  77. py_version_info = py_version_info[:3]
  78. return cast("VersionInfo", py_version_info)
  79. def ensure_dir(path: str) -> None:
  80. """os.path.makedirs without EEXIST."""
  81. try:
  82. os.makedirs(path)
  83. except OSError as e:
  84. # Windows can raise spurious ENOTEMPTY errors. See #6426.
  85. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
  86. raise
  87. def get_prog() -> str:
  88. try:
  89. prog = os.path.basename(sys.argv[0])
  90. if prog in ("__main__.py", "-c"):
  91. return f"{sys.executable} -m pip"
  92. else:
  93. return prog
  94. except (AttributeError, TypeError, IndexError):
  95. pass
  96. return "pip"
  97. # Retry every half second for up to 3 seconds
  98. @retry(stop_after_delay=3, wait=0.5)
  99. def rmtree(dir: str, ignore_errors: bool = False, onexc: OnExc | None = None) -> None:
  100. if ignore_errors:
  101. onexc = _onerror_ignore
  102. if onexc is None:
  103. onexc = _onerror_reraise
  104. handler: OnErr = partial(rmtree_errorhandler, onexc=onexc)
  105. if sys.version_info >= (3, 12):
  106. # See https://docs.python.org/3.12/whatsnew/3.12.html#shutil.
  107. shutil.rmtree(dir, onexc=handler) # type: ignore
  108. else:
  109. shutil.rmtree(dir, onerror=handler) # type: ignore
  110. def _onerror_ignore(*_args: Any) -> None:
  111. pass
  112. def _onerror_reraise(*_args: Any) -> None:
  113. raise # noqa: PLE0704 - Bare exception used to reraise existing exception
  114. def rmtree_errorhandler(
  115. func: FunctionType,
  116. path: Path,
  117. exc_info: ExcInfo | BaseException,
  118. *,
  119. onexc: OnExc = _onerror_reraise,
  120. ) -> None:
  121. """
  122. `rmtree` error handler to 'force' a file remove (i.e. like `rm -f`).
  123. * If a file is readonly then it's write flag is set and operation is
  124. retried.
  125. * `onerror` is the original callback from `rmtree(... onerror=onerror)`
  126. that is chained at the end if the "rm -f" still fails.
  127. """
  128. try:
  129. st_mode = os.stat(path).st_mode
  130. except OSError:
  131. # it's equivalent to os.path.exists
  132. return
  133. if not st_mode & stat.S_IWRITE:
  134. # convert to read/write
  135. try:
  136. os.chmod(path, st_mode | stat.S_IWRITE)
  137. except OSError:
  138. pass
  139. else:
  140. # use the original function to repeat the operation
  141. try:
  142. func(path)
  143. return
  144. except OSError:
  145. pass
  146. if not isinstance(exc_info, BaseException):
  147. _, exc_info, _ = exc_info
  148. onexc(func, path, exc_info)
  149. def display_path(path: str) -> str:
  150. """Gives the display value for a given path, making it relative to cwd
  151. if possible."""
  152. path = os.path.normcase(os.path.abspath(path))
  153. if path.startswith(os.getcwd() + os.path.sep):
  154. path = "." + path[len(os.getcwd()) :]
  155. return path
  156. def backup_dir(dir: str, ext: str = ".bak") -> str:
  157. """Figure out the name of a directory to back up the given dir to
  158. (adding .bak, .bak2, etc)"""
  159. n = 1
  160. extension = ext
  161. while os.path.exists(dir + extension):
  162. n += 1
  163. extension = ext + str(n)
  164. return dir + extension
  165. def ask_path_exists(message: str, options: Iterable[str]) -> str:
  166. for action in os.environ.get("PIP_EXISTS_ACTION", "").split():
  167. if action in options:
  168. return action
  169. return ask(message, options)
  170. def _check_no_input(message: str) -> None:
  171. """Raise an error if no input is allowed."""
  172. if os.environ.get("PIP_NO_INPUT"):
  173. raise Exception(
  174. f"No input was expected ($PIP_NO_INPUT set); question: {message}"
  175. )
  176. def ask(message: str, options: Iterable[str]) -> str:
  177. """Ask the message interactively, with the given possible responses"""
  178. while 1:
  179. _check_no_input(message)
  180. response = input(message)
  181. response = response.strip().lower()
  182. if response not in options:
  183. print(
  184. "Your response ({!r}) was not one of the expected responses: "
  185. "{}".format(response, ", ".join(options))
  186. )
  187. else:
  188. return response
  189. def ask_input(message: str) -> str:
  190. """Ask for input interactively."""
  191. _check_no_input(message)
  192. return input(message)
  193. def ask_password(message: str) -> str:
  194. """Ask for a password interactively."""
  195. _check_no_input(message)
  196. return getpass.getpass(message)
  197. def strtobool(val: str) -> int:
  198. """Convert a string representation of truth to true (1) or false (0).
  199. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  200. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  201. 'val' is anything else.
  202. """
  203. val = val.lower()
  204. if val in ("y", "yes", "t", "true", "on", "1"):
  205. return 1
  206. elif val in ("n", "no", "f", "false", "off", "0"):
  207. return 0
  208. else:
  209. raise ValueError(f"invalid truth value {val!r}")
  210. def format_size(bytes: float) -> str:
  211. if bytes > 1000 * 1000:
  212. return f"{bytes / 1000.0 / 1000:.1f} MB"
  213. elif bytes > 10 * 1000:
  214. return f"{int(bytes / 1000)} kB"
  215. elif bytes > 1000:
  216. return f"{bytes / 1000.0:.1f} kB"
  217. else:
  218. return f"{int(bytes)} bytes"
  219. def tabulate(rows: Iterable[Iterable[Any]]) -> tuple[list[str], list[int]]:
  220. """Return a list of formatted rows and a list of column sizes.
  221. For example::
  222. >>> tabulate([['foobar', 2000], [0xdeadbeef]])
  223. (['foobar 2000', '3735928559'], [10, 4])
  224. """
  225. rows = [tuple(map(str, row)) for row in rows]
  226. sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")]
  227. table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
  228. return table, sizes
  229. def is_installable_dir(path: str) -> bool:
  230. """Is path is a directory containing pyproject.toml or setup.py?
  231. If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for
  232. a legacy setuptools layout by identifying setup.py. We don't check for the
  233. setup.cfg because using it without setup.py is only available for PEP 517
  234. projects, which are already covered by the pyproject.toml check.
  235. """
  236. if not os.path.isdir(path):
  237. return False
  238. if os.path.isfile(os.path.join(path, "pyproject.toml")):
  239. return True
  240. if os.path.isfile(os.path.join(path, "setup.py")):
  241. return True
  242. return False
  243. def read_chunks(
  244. file: BinaryIO, size: int = FILE_CHUNK_SIZE
  245. ) -> Generator[bytes, None, None]:
  246. """Yield pieces of data from a file-like object until EOF."""
  247. while True:
  248. chunk = file.read(size)
  249. if not chunk:
  250. break
  251. yield chunk
  252. def normalize_path(path: str, resolve_symlinks: bool = True) -> str:
  253. """
  254. Convert a path to its canonical, case-normalized, absolute version.
  255. """
  256. path = os.path.expanduser(path)
  257. if resolve_symlinks:
  258. path = os.path.realpath(path)
  259. else:
  260. path = os.path.abspath(path)
  261. return os.path.normcase(path)
  262. def splitext(path: str) -> tuple[str, str]:
  263. """Like os.path.splitext, but take off .tar too"""
  264. base, ext = posixpath.splitext(path)
  265. if base.lower().endswith(".tar"):
  266. ext = base[-4:] + ext
  267. base = base[:-4]
  268. return base, ext
  269. def renames(old: str, new: str) -> None:
  270. """Like os.renames(), but handles renaming across devices."""
  271. # Implementation borrowed from os.renames().
  272. head, tail = os.path.split(new)
  273. if head and tail and not os.path.exists(head):
  274. os.makedirs(head)
  275. shutil.move(old, new)
  276. head, tail = os.path.split(old)
  277. if head and tail:
  278. try:
  279. os.removedirs(head)
  280. except OSError:
  281. pass
  282. def is_local(path: str) -> bool:
  283. """
  284. Return True if path is within sys.prefix, if we're running in a virtualenv.
  285. If we're not in a virtualenv, all paths are considered "local."
  286. Caution: this function assumes the head of path has been normalized
  287. with normalize_path.
  288. """
  289. if not running_under_virtualenv():
  290. return True
  291. return path.startswith(normalize_path(sys.prefix))
  292. def write_output(msg: Any, *args: Any) -> None:
  293. logger.info(msg, *args)
  294. class StreamWrapper(StringIO):
  295. orig_stream: TextIO
  296. @classmethod
  297. def from_stream(cls, orig_stream: TextIO) -> StreamWrapper:
  298. ret = cls()
  299. ret.orig_stream = orig_stream
  300. return ret
  301. # compileall.compile_dir() needs stdout.encoding to print to stdout
  302. # type ignore is because TextIOBase.encoding is writeable
  303. @property
  304. def encoding(self) -> str: # type: ignore
  305. return self.orig_stream.encoding
  306. # Simulates an enum
  307. def enum(*sequential: Any, **named: Any) -> type[Any]:
  308. enums = dict(zip(sequential, range(len(sequential))), **named)
  309. reverse = {value: key for key, value in enums.items()}
  310. enums["reverse_mapping"] = reverse
  311. return type("Enum", (), enums)
  312. def build_netloc(host: str, port: int | None) -> str:
  313. """
  314. Build a netloc from a host-port pair
  315. """
  316. if port is None:
  317. return host
  318. if ":" in host:
  319. # Only wrap host with square brackets when it is IPv6
  320. host = f"[{host}]"
  321. return f"{host}:{port}"
  322. def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
  323. """
  324. Build a full URL from a netloc.
  325. """
  326. if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
  327. # It must be a bare IPv6 address, so wrap it with brackets.
  328. netloc = f"[{netloc}]"
  329. return f"{scheme}://{netloc}"
  330. def parse_netloc(netloc: str) -> tuple[str | None, int | None]:
  331. """
  332. Return the host-port pair from a netloc.
  333. """
  334. url = build_url_from_netloc(netloc)
  335. parsed = urllib.parse.urlparse(url)
  336. return parsed.hostname, parsed.port
  337. def split_auth_from_netloc(netloc: str) -> NetlocTuple:
  338. """
  339. Parse out and remove the auth information from a netloc.
  340. Returns: (netloc, (username, password)).
  341. """
  342. if "@" not in netloc:
  343. return netloc, (None, None)
  344. # Split from the right because that's how urllib.parse.urlsplit()
  345. # behaves if more than one @ is present (which can be checked using
  346. # the password attribute of urlsplit()'s return value).
  347. auth, netloc = netloc.rsplit("@", 1)
  348. pw: str | None = None
  349. if ":" in auth:
  350. # Split from the left because that's how urllib.parse.urlsplit()
  351. # behaves if more than one : is present (which again can be checked
  352. # using the password attribute of the return value)
  353. user, pw = auth.split(":", 1)
  354. else:
  355. user, pw = auth, None
  356. user = urllib.parse.unquote(user)
  357. if pw is not None:
  358. pw = urllib.parse.unquote(pw)
  359. return netloc, (user, pw)
  360. def redact_netloc(netloc: str) -> str:
  361. """
  362. Replace the sensitive data in a netloc with "****", if it exists.
  363. For example:
  364. - "user:pass@example.com" returns "user:****@example.com"
  365. - "accesstoken@example.com" returns "****@example.com"
  366. """
  367. netloc, (user, password) = split_auth_from_netloc(netloc)
  368. if user is None:
  369. return netloc
  370. if password is None:
  371. user = "****"
  372. password = ""
  373. else:
  374. user = urllib.parse.quote(user)
  375. password = ":****"
  376. return f"{user}{password}@{netloc}"
  377. def _transform_url(
  378. url: str, transform_netloc: Callable[[str], tuple[Any, ...]]
  379. ) -> tuple[str, NetlocTuple]:
  380. """Transform and replace netloc in a url.
  381. transform_netloc is a function taking the netloc and returning a
  382. tuple. The first element of this tuple is the new netloc. The
  383. entire tuple is returned.
  384. Returns a tuple containing the transformed url as item 0 and the
  385. original tuple returned by transform_netloc as item 1.
  386. """
  387. purl = urllib.parse.urlsplit(url)
  388. netloc_tuple = transform_netloc(purl.netloc)
  389. # stripped url
  390. url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
  391. surl = urllib.parse.urlunsplit(url_pieces)
  392. return surl, cast("NetlocTuple", netloc_tuple)
  393. def _get_netloc(netloc: str) -> NetlocTuple:
  394. return split_auth_from_netloc(netloc)
  395. def _redact_netloc(netloc: str) -> tuple[str]:
  396. return (redact_netloc(netloc),)
  397. def split_auth_netloc_from_url(
  398. url: str,
  399. ) -> tuple[str, str, tuple[str | None, str | None]]:
  400. """
  401. Parse a url into separate netloc, auth, and url with no auth.
  402. Returns: (url_without_auth, netloc, (username, password))
  403. """
  404. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  405. return url_without_auth, netloc, auth
  406. def remove_auth_from_url(url: str) -> str:
  407. """Return a copy of url with 'username:password@' removed."""
  408. # username/pass params are passed to subversion through flags
  409. # and are not recognized in the url.
  410. return _transform_url(url, _get_netloc)[0]
  411. def redact_auth_from_url(url: str) -> str:
  412. """Replace the password in a given url with ****."""
  413. return _transform_url(url, _redact_netloc)[0]
  414. def redact_auth_from_requirement(req: Requirement) -> str:
  415. """Replace the password in a given requirement url with ****."""
  416. if not req.url:
  417. return str(req)
  418. return str(req).replace(req.url, redact_auth_from_url(req.url))
  419. @dataclass(frozen=True)
  420. class HiddenText:
  421. secret: str
  422. redacted: str
  423. def __repr__(self) -> str:
  424. return f"<HiddenText {str(self)!r}>"
  425. def __str__(self) -> str:
  426. return self.redacted
  427. # This is useful for testing.
  428. def __eq__(self, other: Any) -> bool:
  429. if type(self) is not type(other):
  430. return False
  431. # The string being used for redaction doesn't also have to match,
  432. # just the raw, original string.
  433. return self.secret == other.secret
  434. def hide_value(value: str) -> HiddenText:
  435. return HiddenText(value, redacted="****")
  436. def hide_url(url: str) -> HiddenText:
  437. redacted = redact_auth_from_url(url)
  438. return HiddenText(url, redacted=redacted)
  439. def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
  440. """Protection of pip.exe from modification on Windows
  441. On Windows, any operation modifying pip should be run as:
  442. python -m pip ...
  443. """
  444. pip_names = [
  445. "pip",
  446. f"pip{sys.version_info.major}",
  447. f"pip{sys.version_info.major}.{sys.version_info.minor}",
  448. ]
  449. # See https://github.com/pypa/pip/issues/1299 for more discussion
  450. should_show_use_python_msg = (
  451. modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
  452. )
  453. if should_show_use_python_msg:
  454. new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
  455. raise CommandError(
  456. "To modify pip, please run the following command:\n{}".format(
  457. " ".join(new_command)
  458. )
  459. )
  460. def check_externally_managed() -> None:
  461. """Check whether the current environment is externally managed.
  462. If the ``EXTERNALLY-MANAGED`` config file is found, the current environment
  463. is considered externally managed, and an ExternallyManagedEnvironment is
  464. raised.
  465. """
  466. if running_under_virtualenv():
  467. return
  468. marker = os.path.join(sysconfig.get_path("stdlib"), "EXTERNALLY-MANAGED")
  469. if not os.path.isfile(marker):
  470. return
  471. raise ExternallyManagedEnvironment.from_config(marker)
  472. def is_console_interactive() -> bool:
  473. """Is this console interactive?"""
  474. return sys.stdin is not None and sys.stdin.isatty()
  475. def hash_file(path: str, blocksize: int = 1 << 20) -> tuple[Any, int]:
  476. """Return (hash, length) for path using hashlib.sha256()"""
  477. h = hashlib.sha256()
  478. length = 0
  479. with open(path, "rb") as f:
  480. for block in read_chunks(f, size=blocksize):
  481. length += len(block)
  482. h.update(block)
  483. return h, length
  484. def pairwise(iterable: Iterable[Any]) -> Iterator[tuple[Any, Any]]:
  485. """
  486. Return paired elements.
  487. For example:
  488. s -> (s0, s1), (s2, s3), (s4, s5), ...
  489. """
  490. iterable = iter(iterable)
  491. return zip_longest(iterable, iterable)
  492. def partition(
  493. pred: Callable[[T], bool], iterable: Iterable[T]
  494. ) -> tuple[Iterable[T], Iterable[T]]:
  495. """
  496. Use a predicate to partition entries into false entries and true entries,
  497. like
  498. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  499. """
  500. t1, t2 = tee(iterable)
  501. return filterfalse(pred, t1), filter(pred, t2)
  502. class ConfiguredBuildBackendHookCaller(BuildBackendHookCaller):
  503. def __init__(
  504. self,
  505. config_holder: Any,
  506. source_dir: str,
  507. build_backend: str,
  508. backend_path: str | None = None,
  509. runner: Callable[..., None] | None = None,
  510. python_executable: str | None = None,
  511. ):
  512. super().__init__(
  513. source_dir, build_backend, backend_path, runner, python_executable
  514. )
  515. self.config_holder = config_holder
  516. def build_wheel(
  517. self,
  518. wheel_directory: str,
  519. config_settings: Mapping[str, Any] | None = None,
  520. metadata_directory: str | None = None,
  521. ) -> str:
  522. cs = self.config_holder.config_settings
  523. return super().build_wheel(
  524. wheel_directory, config_settings=cs, metadata_directory=metadata_directory
  525. )
  526. def build_sdist(
  527. self,
  528. sdist_directory: str,
  529. config_settings: Mapping[str, Any] | None = None,
  530. ) -> str:
  531. cs = self.config_holder.config_settings
  532. return super().build_sdist(sdist_directory, config_settings=cs)
  533. def build_editable(
  534. self,
  535. wheel_directory: str,
  536. config_settings: Mapping[str, Any] | None = None,
  537. metadata_directory: str | None = None,
  538. ) -> str:
  539. cs = self.config_holder.config_settings
  540. return super().build_editable(
  541. wheel_directory, config_settings=cs, metadata_directory=metadata_directory
  542. )
  543. def get_requires_for_build_wheel(
  544. self, config_settings: Mapping[str, Any] | None = None
  545. ) -> Sequence[str]:
  546. cs = self.config_holder.config_settings
  547. return super().get_requires_for_build_wheel(config_settings=cs)
  548. def get_requires_for_build_sdist(
  549. self, config_settings: Mapping[str, Any] | None = None
  550. ) -> Sequence[str]:
  551. cs = self.config_holder.config_settings
  552. return super().get_requires_for_build_sdist(config_settings=cs)
  553. def get_requires_for_build_editable(
  554. self, config_settings: Mapping[str, Any] | None = None
  555. ) -> Sequence[str]:
  556. cs = self.config_holder.config_settings
  557. return super().get_requires_for_build_editable(config_settings=cs)
  558. def prepare_metadata_for_build_wheel(
  559. self,
  560. metadata_directory: str,
  561. config_settings: Mapping[str, Any] | None = None,
  562. _allow_fallback: bool = True,
  563. ) -> str:
  564. cs = self.config_holder.config_settings
  565. return super().prepare_metadata_for_build_wheel(
  566. metadata_directory=metadata_directory,
  567. config_settings=cs,
  568. _allow_fallback=_allow_fallback,
  569. )
  570. def prepare_metadata_for_build_editable(
  571. self,
  572. metadata_directory: str,
  573. config_settings: Mapping[str, Any] | None = None,
  574. _allow_fallback: bool = True,
  575. ) -> str | None:
  576. cs = self.config_holder.config_settings
  577. return super().prepare_metadata_for_build_editable(
  578. metadata_directory=metadata_directory,
  579. config_settings=cs,
  580. _allow_fallback=_allow_fallback,
  581. )
  582. def warn_if_run_as_root() -> None:
  583. """Output a warning for sudo users on Unix.
  584. In a virtual environment, sudo pip still writes to virtualenv.
  585. On Windows, users may run pip as Administrator without issues.
  586. This warning only applies to Unix root users outside of virtualenv.
  587. """
  588. if running_under_virtualenv():
  589. return
  590. if not hasattr(os, "getuid"):
  591. return
  592. # On Windows, there are no "system managed" Python packages. Installing as
  593. # Administrator via pip is the correct way of updating system environments.
  594. #
  595. # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
  596. # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
  597. if sys.platform == "win32" or sys.platform == "cygwin":
  598. return
  599. if os.getuid() != 0:
  600. return
  601. logger.warning(
  602. "Running pip as the 'root' user can result in broken permissions and "
  603. "conflicting behaviour with the system package manager, possibly "
  604. "rendering your system unusable. "
  605. "It is recommended to use a virtual environment instead: "
  606. "https://pip.pypa.io/warnings/venv. "
  607. "Use the --root-user-action option if you know what you are doing and "
  608. "want to suppress this warning."
  609. )