1
0

misc.py 23 KB

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