misc.py 23 KB

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