misc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. try:
  153. relative = Path(path).relative_to(Path.cwd())
  154. except ValueError:
  155. # If the path isn't relative to the CWD, leave it alone
  156. return path
  157. return os.path.join(".", relative)
  158. def backup_dir(dir: str, ext: str = ".bak") -> str:
  159. """Figure out the name of a directory to back up the given dir to
  160. (adding .bak, .bak2, etc)"""
  161. n = 1
  162. extension = ext
  163. while os.path.exists(dir + extension):
  164. n += 1
  165. extension = ext + str(n)
  166. return dir + extension
  167. def ask_path_exists(message: str, options: Iterable[str]) -> str:
  168. for action in os.environ.get("PIP_EXISTS_ACTION", "").split():
  169. if action in options:
  170. return action
  171. return ask(message, options)
  172. def _check_no_input(message: str) -> None:
  173. """Raise an error if no input is allowed."""
  174. if os.environ.get("PIP_NO_INPUT"):
  175. raise Exception(
  176. f"No input was expected ($PIP_NO_INPUT set); question: {message}"
  177. )
  178. def ask(message: str, options: Iterable[str]) -> str:
  179. """Ask the message interactively, with the given possible responses"""
  180. while 1:
  181. _check_no_input(message)
  182. response = input(message)
  183. response = response.strip().lower()
  184. if response not in options:
  185. print(
  186. "Your response ({!r}) was not one of the expected responses: "
  187. "{}".format(response, ", ".join(options))
  188. )
  189. else:
  190. return response
  191. def ask_input(message: str) -> str:
  192. """Ask for input interactively."""
  193. _check_no_input(message)
  194. return input(message)
  195. def ask_password(message: str) -> str:
  196. """Ask for a password interactively."""
  197. _check_no_input(message)
  198. return getpass.getpass(message)
  199. def strtobool(val: str) -> int:
  200. """Convert a string representation of truth to true (1) or false (0).
  201. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  202. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  203. 'val' is anything else.
  204. """
  205. val = val.lower()
  206. if val in ("y", "yes", "t", "true", "on", "1"):
  207. return 1
  208. elif val in ("n", "no", "f", "false", "off", "0"):
  209. return 0
  210. else:
  211. raise ValueError(f"invalid truth value {val!r}")
  212. def format_size(bytes: float) -> str:
  213. if bytes > 1000 * 1000:
  214. return f"{bytes / 1000.0 / 1000:.1f} MB"
  215. elif bytes > 10 * 1000:
  216. return f"{int(bytes / 1000)} kB"
  217. elif bytes > 1000:
  218. return f"{bytes / 1000.0:.1f} kB"
  219. else:
  220. return f"{int(bytes)} bytes"
  221. def tabulate(rows: Iterable[Iterable[Any]]) -> tuple[list[str], list[int]]:
  222. """Return a list of formatted rows and a list of column sizes.
  223. For example::
  224. >>> tabulate([['foobar', 2000], [0xdeadbeef]])
  225. (['foobar 2000', '3735928559'], [10, 4])
  226. """
  227. rows = [tuple(map(str, row)) for row in rows]
  228. sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")]
  229. table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
  230. return table, sizes
  231. def is_installable_dir(path: str) -> bool:
  232. """Is path is a directory containing pyproject.toml or setup.py?
  233. If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for
  234. a legacy setuptools layout by identifying setup.py. We don't check for the
  235. setup.cfg because using it without setup.py is only available for PEP 517
  236. projects, which are already covered by the pyproject.toml check.
  237. """
  238. if not os.path.isdir(path):
  239. return False
  240. if os.path.isfile(os.path.join(path, "pyproject.toml")):
  241. return True
  242. if os.path.isfile(os.path.join(path, "setup.py")):
  243. return True
  244. return False
  245. def read_chunks(
  246. file: BinaryIO, size: int = FILE_CHUNK_SIZE
  247. ) -> Generator[bytes, None, None]:
  248. """Yield pieces of data from a file-like object until EOF."""
  249. while True:
  250. chunk = file.read(size)
  251. if not chunk:
  252. break
  253. yield chunk
  254. def normalize_path(path: str, resolve_symlinks: bool = True) -> str:
  255. """
  256. Convert a path to its canonical, case-normalized, absolute version.
  257. """
  258. path = os.path.expanduser(path)
  259. if resolve_symlinks:
  260. path = os.path.realpath(path)
  261. else:
  262. path = os.path.abspath(path)
  263. return os.path.normcase(path)
  264. def splitext(path: str) -> tuple[str, str]:
  265. """Like os.path.splitext, but take off .tar too"""
  266. base, ext = posixpath.splitext(path)
  267. if base.lower().endswith(".tar"):
  268. ext = base[-4:] + ext
  269. base = base[:-4]
  270. return base, ext
  271. def renames(old: str, new: str) -> None:
  272. """Like os.renames(), but handles renaming across devices."""
  273. # Implementation borrowed from os.renames().
  274. head, tail = os.path.split(new)
  275. if head and tail and not os.path.exists(head):
  276. os.makedirs(head)
  277. shutil.move(old, new)
  278. head, tail = os.path.split(old)
  279. if head and tail:
  280. try:
  281. os.removedirs(head)
  282. except OSError:
  283. pass
  284. def is_local(path: str) -> bool:
  285. """
  286. Return True if path is within sys.prefix, if we're running in a virtualenv.
  287. If we're not in a virtualenv, all paths are considered "local."
  288. Caution: this function assumes the head of path has been normalized
  289. with normalize_path.
  290. """
  291. if not running_under_virtualenv():
  292. return True
  293. return path.startswith(normalize_path(sys.prefix))
  294. def write_output(msg: Any, *args: Any) -> None:
  295. logger.info(msg, *args)
  296. class StreamWrapper(StringIO):
  297. orig_stream: TextIO
  298. @classmethod
  299. def from_stream(cls, orig_stream: TextIO) -> StreamWrapper:
  300. ret = cls()
  301. ret.orig_stream = orig_stream
  302. return ret
  303. # compileall.compile_dir() needs stdout.encoding to print to stdout
  304. # type ignore is because TextIOBase.encoding is writeable
  305. @property
  306. def encoding(self) -> str: # type: ignore
  307. return self.orig_stream.encoding
  308. # Simulates an enum
  309. def enum(*sequential: Any, **named: Any) -> type[Any]:
  310. enums = dict(zip(sequential, range(len(sequential))), **named)
  311. reverse = {value: key for key, value in enums.items()}
  312. enums["reverse_mapping"] = reverse
  313. return type("Enum", (), enums)
  314. def build_netloc(host: str, port: int | None) -> str:
  315. """
  316. Build a netloc from a host-port pair
  317. """
  318. if port is None:
  319. return host
  320. if ":" in host:
  321. # Only wrap host with square brackets when it is IPv6
  322. host = f"[{host}]"
  323. return f"{host}:{port}"
  324. def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
  325. """
  326. Build a full URL from a netloc.
  327. """
  328. if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
  329. # It must be a bare IPv6 address, so wrap it with brackets.
  330. netloc = f"[{netloc}]"
  331. return f"{scheme}://{netloc}"
  332. def parse_netloc(netloc: str) -> tuple[str | None, int | None]:
  333. """
  334. Return the host-port pair from a netloc.
  335. """
  336. url = build_url_from_netloc(netloc)
  337. parsed = urllib.parse.urlparse(url)
  338. return parsed.hostname, parsed.port
  339. def split_auth_from_netloc(netloc: str) -> NetlocTuple:
  340. """
  341. Parse out and remove the auth information from a netloc.
  342. Returns: (netloc, (username, password)).
  343. """
  344. if "@" not in netloc:
  345. return netloc, (None, None)
  346. # Split from the right because that's how urllib.parse.urlsplit()
  347. # behaves if more than one @ is present (which can be checked using
  348. # the password attribute of urlsplit()'s return value).
  349. auth, netloc = netloc.rsplit("@", 1)
  350. pw: str | None = None
  351. if ":" in auth:
  352. # Split from the left because that's how urllib.parse.urlsplit()
  353. # behaves if more than one : is present (which again can be checked
  354. # using the password attribute of the return value)
  355. user, pw = auth.split(":", 1)
  356. else:
  357. user, pw = auth, None
  358. user = urllib.parse.unquote(user)
  359. if pw is not None:
  360. pw = urllib.parse.unquote(pw)
  361. return netloc, (user, pw)
  362. def redact_netloc(netloc: str) -> str:
  363. """
  364. Replace the sensitive data in a netloc with "****", if it exists.
  365. For example:
  366. - "user:pass@example.com" returns "user:****@example.com"
  367. - "accesstoken@example.com" returns "****@example.com"
  368. """
  369. netloc, (user, password) = split_auth_from_netloc(netloc)
  370. if user is None:
  371. return netloc
  372. if password is None:
  373. user = "****"
  374. password = ""
  375. else:
  376. user = urllib.parse.quote(user)
  377. password = ":****"
  378. return f"{user}{password}@{netloc}"
  379. def _transform_url(
  380. url: str, transform_netloc: Callable[[str], tuple[Any, ...]]
  381. ) -> tuple[str, NetlocTuple]:
  382. """Transform and replace netloc in a url.
  383. transform_netloc is a function taking the netloc and returning a
  384. tuple. The first element of this tuple is the new netloc. The
  385. entire tuple is returned.
  386. Returns a tuple containing the transformed url as item 0 and the
  387. original tuple returned by transform_netloc as item 1.
  388. """
  389. purl = urllib.parse.urlsplit(url)
  390. netloc_tuple = transform_netloc(purl.netloc)
  391. # stripped url
  392. url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
  393. surl = urllib.parse.urlunsplit(url_pieces)
  394. return surl, cast("NetlocTuple", netloc_tuple)
  395. def _get_netloc(netloc: str) -> NetlocTuple:
  396. return split_auth_from_netloc(netloc)
  397. def _redact_netloc(netloc: str) -> tuple[str]:
  398. return (redact_netloc(netloc),)
  399. def split_auth_netloc_from_url(
  400. url: str,
  401. ) -> tuple[str, str, tuple[str | None, str | None]]:
  402. """
  403. Parse a url into separate netloc, auth, and url with no auth.
  404. Returns: (url_without_auth, netloc, (username, password))
  405. """
  406. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  407. return url_without_auth, netloc, auth
  408. def remove_auth_from_url(url: str) -> str:
  409. """Return a copy of url with 'username:password@' removed."""
  410. # username/pass params are passed to subversion through flags
  411. # and are not recognized in the url.
  412. return _transform_url(url, _get_netloc)[0]
  413. def redact_auth_from_url(url: str) -> str:
  414. """Replace the password in a given url with ****."""
  415. return _transform_url(url, _redact_netloc)[0]
  416. def redact_auth_from_requirement(req: Requirement) -> str:
  417. """Replace the password in a given requirement url with ****."""
  418. if not req.url:
  419. return str(req)
  420. return str(req).replace(req.url, redact_auth_from_url(req.url))
  421. @dataclass(frozen=True)
  422. class HiddenText:
  423. secret: str
  424. redacted: str
  425. def __repr__(self) -> str:
  426. return f"<HiddenText {str(self)!r}>"
  427. def __str__(self) -> str:
  428. return self.redacted
  429. def __eq__(self, other: object) -> bool:
  430. # Equality is particularly useful for testing.
  431. if type(self) is type(other):
  432. # The string being used for redaction doesn't also have to match,
  433. # just the raw, original string.
  434. return self.secret == cast(HiddenText, other).secret
  435. return NotImplemented
  436. # Disable hashing, since we have a custom __eq__ and don't need hash-ability
  437. # (yet). The only required property of hashing is that objects which compare
  438. # equal have the same hash value.
  439. __hash__ = None # type: ignore[assignment]
  440. def hide_value(value: str) -> HiddenText:
  441. return HiddenText(value, redacted="****")
  442. def hide_url(url: str) -> HiddenText:
  443. redacted = redact_auth_from_url(url)
  444. return HiddenText(url, redacted=redacted)
  445. def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
  446. """Protection of pip.exe from modification on Windows
  447. On Windows, any operation modifying pip should be run as:
  448. python -m pip ...
  449. """
  450. pip_names = [
  451. "pip",
  452. f"pip{sys.version_info.major}",
  453. f"pip{sys.version_info.major}.{sys.version_info.minor}",
  454. ]
  455. # See https://github.com/pypa/pip/issues/1299 for more discussion
  456. should_show_use_python_msg = (
  457. modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
  458. )
  459. if should_show_use_python_msg:
  460. new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
  461. raise CommandError(
  462. "To modify pip, please run the following command:\n{}".format(
  463. " ".join(new_command)
  464. )
  465. )
  466. def check_externally_managed() -> None:
  467. """Check whether the current environment is externally managed.
  468. If the ``EXTERNALLY-MANAGED`` config file is found, the current environment
  469. is considered externally managed, and an ExternallyManagedEnvironment is
  470. raised.
  471. """
  472. if running_under_virtualenv():
  473. return
  474. marker = os.path.join(sysconfig.get_path("stdlib"), "EXTERNALLY-MANAGED")
  475. if not os.path.isfile(marker):
  476. return
  477. raise ExternallyManagedEnvironment.from_config(marker)
  478. def is_console_interactive() -> bool:
  479. """Is this console interactive?"""
  480. return sys.stdin is not None and sys.stdin.isatty()
  481. def hash_file(path: str, blocksize: int = 1 << 20) -> tuple[Any, int]:
  482. """Return (hash, length) for path using hashlib.sha256()"""
  483. h = hashlib.sha256()
  484. length = 0
  485. with open(path, "rb") as f:
  486. for block in read_chunks(f, size=blocksize):
  487. length += len(block)
  488. h.update(block)
  489. return h, length
  490. def pairwise(iterable: Iterable[Any]) -> Iterator[tuple[Any, Any]]:
  491. """
  492. Return paired elements.
  493. For example:
  494. s -> (s0, s1), (s2, s3), (s4, s5), ...
  495. """
  496. iterable = iter(iterable)
  497. return zip_longest(iterable, iterable)
  498. def partition(
  499. pred: Callable[[T], bool], iterable: Iterable[T]
  500. ) -> tuple[Iterable[T], Iterable[T]]:
  501. """
  502. Use a predicate to partition entries into false entries and true entries,
  503. like
  504. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  505. """
  506. t1, t2 = tee(iterable)
  507. return filterfalse(pred, t1), filter(pred, t2)
  508. class ConfiguredBuildBackendHookCaller(BuildBackendHookCaller):
  509. def __init__(
  510. self,
  511. config_holder: Any,
  512. source_dir: str,
  513. build_backend: str,
  514. backend_path: str | None = None,
  515. runner: Callable[..., None] | None = None,
  516. python_executable: str | None = None,
  517. ):
  518. super().__init__(
  519. source_dir, build_backend, backend_path, runner, python_executable
  520. )
  521. self.config_holder = config_holder
  522. def build_wheel(
  523. self,
  524. wheel_directory: str,
  525. config_settings: Mapping[str, Any] | None = None,
  526. metadata_directory: str | None = None,
  527. ) -> str:
  528. cs = self.config_holder.config_settings
  529. return super().build_wheel(
  530. wheel_directory, config_settings=cs, metadata_directory=metadata_directory
  531. )
  532. def build_sdist(
  533. self,
  534. sdist_directory: str,
  535. config_settings: Mapping[str, Any] | None = None,
  536. ) -> str:
  537. cs = self.config_holder.config_settings
  538. return super().build_sdist(sdist_directory, config_settings=cs)
  539. def build_editable(
  540. self,
  541. wheel_directory: str,
  542. config_settings: Mapping[str, Any] | None = None,
  543. metadata_directory: str | None = None,
  544. ) -> str:
  545. cs = self.config_holder.config_settings
  546. return super().build_editable(
  547. wheel_directory, config_settings=cs, metadata_directory=metadata_directory
  548. )
  549. def get_requires_for_build_wheel(
  550. self, config_settings: Mapping[str, Any] | None = None
  551. ) -> Sequence[str]:
  552. cs = self.config_holder.config_settings
  553. return super().get_requires_for_build_wheel(config_settings=cs)
  554. def get_requires_for_build_sdist(
  555. self, config_settings: Mapping[str, Any] | None = None
  556. ) -> Sequence[str]:
  557. cs = self.config_holder.config_settings
  558. return super().get_requires_for_build_sdist(config_settings=cs)
  559. def get_requires_for_build_editable(
  560. self, config_settings: Mapping[str, Any] | None = None
  561. ) -> Sequence[str]:
  562. cs = self.config_holder.config_settings
  563. return super().get_requires_for_build_editable(config_settings=cs)
  564. def prepare_metadata_for_build_wheel(
  565. self,
  566. metadata_directory: str,
  567. config_settings: Mapping[str, Any] | None = None,
  568. _allow_fallback: bool = True,
  569. ) -> str:
  570. cs = self.config_holder.config_settings
  571. return super().prepare_metadata_for_build_wheel(
  572. metadata_directory=metadata_directory,
  573. config_settings=cs,
  574. _allow_fallback=_allow_fallback,
  575. )
  576. def prepare_metadata_for_build_editable(
  577. self,
  578. metadata_directory: str,
  579. config_settings: Mapping[str, Any] | None = None,
  580. _allow_fallback: bool = True,
  581. ) -> str | None:
  582. cs = self.config_holder.config_settings
  583. return super().prepare_metadata_for_build_editable(
  584. metadata_directory=metadata_directory,
  585. config_settings=cs,
  586. _allow_fallback=_allow_fallback,
  587. )
  588. def warn_if_run_as_root() -> None:
  589. """Output a warning for sudo users on Unix.
  590. In a virtual environment, sudo pip still writes to virtualenv.
  591. On Windows, users may run pip as Administrator without issues.
  592. This warning only applies to Unix root users outside of virtualenv.
  593. """
  594. if running_under_virtualenv():
  595. return
  596. if not hasattr(os, "getuid"):
  597. return
  598. # On Windows, there are no "system managed" Python packages. Installing as
  599. # Administrator via pip is the correct way of updating system environments.
  600. #
  601. # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
  602. # checks: https://mypy.readthedocs.io/en/stable/common_issues.html
  603. if sys.platform == "win32" or sys.platform == "cygwin":
  604. return
  605. if os.getuid() != 0:
  606. return
  607. logger.warning(
  608. "Running pip as the 'root' user can result in broken permissions and "
  609. "conflicting behaviour with the system package manager, possibly "
  610. "rendering your system unusable. "
  611. "It is recommended to use a virtual environment instead: "
  612. "https://pip.pypa.io/warnings/venv. "
  613. "Use the --root-user-action option if you know what you are doing and "
  614. "want to suppress this warning."
  615. )