misc.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. # The following comment should be removed at some point in the future.
  2. # mypy: strict-optional=False
  3. import contextlib
  4. import errno
  5. import getpass
  6. import hashlib
  7. import io
  8. import logging
  9. import os
  10. import posixpath
  11. import shutil
  12. import stat
  13. import sys
  14. import urllib.parse
  15. from io import StringIO
  16. from itertools import filterfalse, tee, zip_longest
  17. from types import TracebackType
  18. from typing import (
  19. Any,
  20. BinaryIO,
  21. Callable,
  22. ContextManager,
  23. Iterable,
  24. Iterator,
  25. List,
  26. Optional,
  27. TextIO,
  28. Tuple,
  29. Type,
  30. TypeVar,
  31. cast,
  32. )
  33. from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed
  34. from pip import __version__
  35. from pip._internal.exceptions import CommandError
  36. from pip._internal.locations import get_major_minor_version
  37. from pip._internal.utils.compat import WINDOWS
  38. from pip._internal.utils.virtualenv import running_under_virtualenv
  39. __all__ = [
  40. "rmtree",
  41. "display_path",
  42. "backup_dir",
  43. "ask",
  44. "splitext",
  45. "format_size",
  46. "is_installable_dir",
  47. "normalize_path",
  48. "renames",
  49. "get_prog",
  50. "captured_stdout",
  51. "ensure_dir",
  52. "remove_auth_from_url",
  53. ]
  54. logger = logging.getLogger(__name__)
  55. T = TypeVar("T")
  56. ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType]
  57. VersionInfo = Tuple[int, int, int]
  58. NetlocTuple = Tuple[str, Tuple[Optional[str], Optional[str]]]
  59. def get_pip_version() -> str:
  60. pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
  61. pip_pkg_dir = os.path.abspath(pip_pkg_dir)
  62. return "pip {} from {} (python {})".format(
  63. __version__,
  64. pip_pkg_dir,
  65. get_major_minor_version(),
  66. )
  67. def normalize_version_info(py_version_info: Tuple[int, ...]) -> Tuple[int, int, int]:
  68. """
  69. Convert a tuple of ints representing a Python version to one of length
  70. three.
  71. :param py_version_info: a tuple of ints representing a Python version,
  72. or None to specify no version. The tuple can have any length.
  73. :return: a tuple of length three if `py_version_info` is non-None.
  74. Otherwise, return `py_version_info` unchanged (i.e. None).
  75. """
  76. if len(py_version_info) < 3:
  77. py_version_info += (3 - len(py_version_info)) * (0,)
  78. elif len(py_version_info) > 3:
  79. py_version_info = py_version_info[:3]
  80. return cast("VersionInfo", py_version_info)
  81. def ensure_dir(path: str) -> None:
  82. """os.path.makedirs without EEXIST."""
  83. try:
  84. os.makedirs(path)
  85. except OSError as e:
  86. # Windows can raise spurious ENOTEMPTY errors. See #6426.
  87. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
  88. raise
  89. def get_prog() -> str:
  90. try:
  91. prog = os.path.basename(sys.argv[0])
  92. if prog in ("__main__.py", "-c"):
  93. return f"{sys.executable} -m pip"
  94. else:
  95. return prog
  96. except (AttributeError, TypeError, IndexError):
  97. pass
  98. return "pip"
  99. # Retry every half second for up to 3 seconds
  100. # Tenacity raises RetryError by default, explicitly raise the original exception
  101. @retry(reraise=True, stop=stop_after_delay(3), wait=wait_fixed(0.5))
  102. def rmtree(dir: str, ignore_errors: bool = False) -> None:
  103. shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler)
  104. def rmtree_errorhandler(func: Callable[..., Any], path: str, exc_info: ExcInfo) -> None:
  105. """On Windows, the files in .svn are read-only, so when rmtree() tries to
  106. remove them, an exception is thrown. We catch that here, remove the
  107. read-only attribute, and hopefully continue without problems."""
  108. try:
  109. has_attr_readonly = not (os.stat(path).st_mode & stat.S_IWRITE)
  110. except OSError:
  111. # it's equivalent to os.path.exists
  112. return
  113. if has_attr_readonly:
  114. # convert to read/write
  115. os.chmod(path, stat.S_IWRITE)
  116. # use the original function to repeat the operation
  117. func(path)
  118. return
  119. else:
  120. raise
  121. def display_path(path: str) -> str:
  122. """Gives the display value for a given path, making it relative to cwd
  123. if possible."""
  124. path = os.path.normcase(os.path.abspath(path))
  125. if path.startswith(os.getcwd() + os.path.sep):
  126. path = "." + path[len(os.getcwd()) :]
  127. return path
  128. def backup_dir(dir: str, ext: str = ".bak") -> str:
  129. """Figure out the name of a directory to back up the given dir to
  130. (adding .bak, .bak2, etc)"""
  131. n = 1
  132. extension = ext
  133. while os.path.exists(dir + extension):
  134. n += 1
  135. extension = ext + str(n)
  136. return dir + extension
  137. def ask_path_exists(message: str, options: Iterable[str]) -> str:
  138. for action in os.environ.get("PIP_EXISTS_ACTION", "").split():
  139. if action in options:
  140. return action
  141. return ask(message, options)
  142. def _check_no_input(message: str) -> None:
  143. """Raise an error if no input is allowed."""
  144. if os.environ.get("PIP_NO_INPUT"):
  145. raise Exception(
  146. f"No input was expected ($PIP_NO_INPUT set); question: {message}"
  147. )
  148. def ask(message: str, options: Iterable[str]) -> str:
  149. """Ask the message interactively, with the given possible responses"""
  150. while 1:
  151. _check_no_input(message)
  152. response = input(message)
  153. response = response.strip().lower()
  154. if response not in options:
  155. print(
  156. "Your response ({!r}) was not one of the expected responses: "
  157. "{}".format(response, ", ".join(options))
  158. )
  159. else:
  160. return response
  161. def ask_input(message: str) -> str:
  162. """Ask for input interactively."""
  163. _check_no_input(message)
  164. return input(message)
  165. def ask_password(message: str) -> str:
  166. """Ask for a password interactively."""
  167. _check_no_input(message)
  168. return getpass.getpass(message)
  169. def strtobool(val: str) -> int:
  170. """Convert a string representation of truth to true (1) or false (0).
  171. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  172. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  173. 'val' is anything else.
  174. """
  175. val = val.lower()
  176. if val in ("y", "yes", "t", "true", "on", "1"):
  177. return 1
  178. elif val in ("n", "no", "f", "false", "off", "0"):
  179. return 0
  180. else:
  181. raise ValueError(f"invalid truth value {val!r}")
  182. def format_size(bytes: float) -> str:
  183. if bytes > 1000 * 1000:
  184. return "{:.1f} MB".format(bytes / 1000.0 / 1000)
  185. elif bytes > 10 * 1000:
  186. return "{} kB".format(int(bytes / 1000))
  187. elif bytes > 1000:
  188. return "{:.1f} kB".format(bytes / 1000.0)
  189. else:
  190. return "{} bytes".format(int(bytes))
  191. def tabulate(rows: Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]:
  192. """Return a list of formatted rows and a list of column sizes.
  193. For example::
  194. >>> tabulate([['foobar', 2000], [0xdeadbeef]])
  195. (['foobar 2000', '3735928559'], [10, 4])
  196. """
  197. rows = [tuple(map(str, row)) for row in rows]
  198. sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")]
  199. table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
  200. return table, sizes
  201. def is_installable_dir(path: str) -> bool:
  202. """Is path is a directory containing pyproject.toml or setup.py?
  203. If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for
  204. a legacy setuptools layout by identifying setup.py. We don't check for the
  205. setup.cfg because using it without setup.py is only available for PEP 517
  206. projects, which are already covered by the pyproject.toml check.
  207. """
  208. if not os.path.isdir(path):
  209. return False
  210. if os.path.isfile(os.path.join(path, "pyproject.toml")):
  211. return True
  212. if os.path.isfile(os.path.join(path, "setup.py")):
  213. return True
  214. return False
  215. def read_chunks(file: BinaryIO, size: int = io.DEFAULT_BUFFER_SIZE) -> Iterator[bytes]:
  216. """Yield pieces of data from a file-like object until EOF."""
  217. while True:
  218. chunk = file.read(size)
  219. if not chunk:
  220. break
  221. yield chunk
  222. def normalize_path(path: str, resolve_symlinks: bool = True) -> str:
  223. """
  224. Convert a path to its canonical, case-normalized, absolute version.
  225. """
  226. path = os.path.expanduser(path)
  227. if resolve_symlinks:
  228. path = os.path.realpath(path)
  229. else:
  230. path = os.path.abspath(path)
  231. return os.path.normcase(path)
  232. def splitext(path: str) -> Tuple[str, str]:
  233. """Like os.path.splitext, but take off .tar too"""
  234. base, ext = posixpath.splitext(path)
  235. if base.lower().endswith(".tar"):
  236. ext = base[-4:] + ext
  237. base = base[:-4]
  238. return base, ext
  239. def renames(old: str, new: str) -> None:
  240. """Like os.renames(), but handles renaming across devices."""
  241. # Implementation borrowed from os.renames().
  242. head, tail = os.path.split(new)
  243. if head and tail and not os.path.exists(head):
  244. os.makedirs(head)
  245. shutil.move(old, new)
  246. head, tail = os.path.split(old)
  247. if head and tail:
  248. try:
  249. os.removedirs(head)
  250. except OSError:
  251. pass
  252. def is_local(path: str) -> bool:
  253. """
  254. Return True if this is a path pip is allowed to modify.
  255. If we're in a virtualenv, sys.prefix points to the virtualenv's
  256. prefix; only sys.prefix is considered local.
  257. If we're not in a virtualenv, in general we can modify anything.
  258. However, if the OS vendor has configured distutils to install
  259. somewhere other than sys.prefix (which could be a subdirectory of
  260. sys.prefix, e.g. /usr/local), we consider sys.prefix itself nonlocal
  261. and the domain of the OS vendor. (In other words, everything _other
  262. than_ sys.prefix is considered local.)
  263. Caution: this function assumes the head of path has been normalized
  264. with normalize_path.
  265. """
  266. path = normalize_path(path)
  267. # Hard-coded becouse PyPy uses a different sys.prefix on Debian
  268. prefix = '/usr'
  269. if running_under_virtualenv():
  270. return path.startswith(normalize_path(sys.prefix))
  271. else:
  272. from pip._internal.locations import get_scheme
  273. from pip._internal.models.scheme import SCHEME_KEYS
  274. if path.startswith(prefix):
  275. scheme = get_scheme("")
  276. for key in SCHEME_KEYS:
  277. local_path = getattr(scheme, key)
  278. if path.startswith(normalize_path(local_path)):
  279. return True
  280. return False
  281. else:
  282. return True
  283. def write_output(msg: Any, *args: Any) -> None:
  284. logger.info(msg, *args)
  285. class StreamWrapper(StringIO):
  286. orig_stream: TextIO = None
  287. @classmethod
  288. def from_stream(cls, orig_stream: TextIO) -> "StreamWrapper":
  289. cls.orig_stream = orig_stream
  290. return cls()
  291. # compileall.compile_dir() needs stdout.encoding to print to stdout
  292. # https://github.com/python/mypy/issues/4125
  293. @property
  294. def encoding(self): # type: ignore
  295. return self.orig_stream.encoding
  296. @contextlib.contextmanager
  297. def captured_output(stream_name: str) -> Iterator[StreamWrapper]:
  298. """Return a context manager used by captured_stdout/stdin/stderr
  299. that temporarily replaces the sys stream *stream_name* with a StringIO.
  300. Taken from Lib/support/__init__.py in the CPython repo.
  301. """
  302. orig_stdout = getattr(sys, stream_name)
  303. setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
  304. try:
  305. yield getattr(sys, stream_name)
  306. finally:
  307. setattr(sys, stream_name, orig_stdout)
  308. def captured_stdout() -> ContextManager[StreamWrapper]:
  309. """Capture the output of sys.stdout:
  310. with captured_stdout() as stdout:
  311. print('hello')
  312. self.assertEqual(stdout.getvalue(), 'hello\n')
  313. Taken from Lib/support/__init__.py in the CPython repo.
  314. """
  315. return captured_output("stdout")
  316. def captured_stderr() -> ContextManager[StreamWrapper]:
  317. """
  318. See captured_stdout().
  319. """
  320. return captured_output("stderr")
  321. # Simulates an enum
  322. def enum(*sequential: Any, **named: Any) -> Type[Any]:
  323. enums = dict(zip(sequential, range(len(sequential))), **named)
  324. reverse = {value: key for key, value in enums.items()}
  325. enums["reverse_mapping"] = reverse
  326. return type("Enum", (), enums)
  327. def build_netloc(host: str, port: Optional[int]) -> str:
  328. """
  329. Build a netloc from a host-port pair
  330. """
  331. if port is None:
  332. return host
  333. if ":" in host:
  334. # Only wrap host with square brackets when it is IPv6
  335. host = f"[{host}]"
  336. return f"{host}:{port}"
  337. def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
  338. """
  339. Build a full URL from a netloc.
  340. """
  341. if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
  342. # It must be a bare IPv6 address, so wrap it with brackets.
  343. netloc = f"[{netloc}]"
  344. return f"{scheme}://{netloc}"
  345. def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]:
  346. """
  347. Return the host-port pair from a netloc.
  348. """
  349. url = build_url_from_netloc(netloc)
  350. parsed = urllib.parse.urlparse(url)
  351. return parsed.hostname, parsed.port
  352. def split_auth_from_netloc(netloc: str) -> NetlocTuple:
  353. """
  354. Parse out and remove the auth information from a netloc.
  355. Returns: (netloc, (username, password)).
  356. """
  357. if "@" not in netloc:
  358. return netloc, (None, None)
  359. # Split from the right because that's how urllib.parse.urlsplit()
  360. # behaves if more than one @ is present (which can be checked using
  361. # the password attribute of urlsplit()'s return value).
  362. auth, netloc = netloc.rsplit("@", 1)
  363. pw: Optional[str] = None
  364. if ":" in auth:
  365. # Split from the left because that's how urllib.parse.urlsplit()
  366. # behaves if more than one : is present (which again can be checked
  367. # using the password attribute of the return value)
  368. user, pw = auth.split(":", 1)
  369. else:
  370. user, pw = auth, None
  371. user = urllib.parse.unquote(user)
  372. if pw is not None:
  373. pw = urllib.parse.unquote(pw)
  374. return netloc, (user, pw)
  375. def redact_netloc(netloc: str) -> str:
  376. """
  377. Replace the sensitive data in a netloc with "****", if it exists.
  378. For example:
  379. - "user:pass@example.com" returns "user:****@example.com"
  380. - "accesstoken@example.com" returns "****@example.com"
  381. """
  382. netloc, (user, password) = split_auth_from_netloc(netloc)
  383. if user is None:
  384. return netloc
  385. if password is None:
  386. user = "****"
  387. password = ""
  388. else:
  389. user = urllib.parse.quote(user)
  390. password = ":****"
  391. return "{user}{password}@{netloc}".format(
  392. user=user, password=password, netloc=netloc
  393. )
  394. def _transform_url(
  395. url: str, transform_netloc: Callable[[str], Tuple[Any, ...]]
  396. ) -> Tuple[str, NetlocTuple]:
  397. """Transform and replace netloc in a url.
  398. transform_netloc is a function taking the netloc and returning a
  399. tuple. The first element of this tuple is the new netloc. The
  400. entire tuple is returned.
  401. Returns a tuple containing the transformed url as item 0 and the
  402. original tuple returned by transform_netloc as item 1.
  403. """
  404. purl = urllib.parse.urlsplit(url)
  405. netloc_tuple = transform_netloc(purl.netloc)
  406. # stripped url
  407. url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
  408. surl = urllib.parse.urlunsplit(url_pieces)
  409. return surl, cast("NetlocTuple", netloc_tuple)
  410. def _get_netloc(netloc: str) -> NetlocTuple:
  411. return split_auth_from_netloc(netloc)
  412. def _redact_netloc(netloc: str) -> Tuple[str]:
  413. return (redact_netloc(netloc),)
  414. def split_auth_netloc_from_url(url: str) -> Tuple[str, str, Tuple[str, str]]:
  415. """
  416. Parse a url into separate netloc, auth, and url with no auth.
  417. Returns: (url_without_auth, netloc, (username, password))
  418. """
  419. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  420. return url_without_auth, netloc, auth
  421. def remove_auth_from_url(url: str) -> str:
  422. """Return a copy of url with 'username:password@' removed."""
  423. # username/pass params are passed to subversion through flags
  424. # and are not recognized in the url.
  425. return _transform_url(url, _get_netloc)[0]
  426. def redact_auth_from_url(url: str) -> str:
  427. """Replace the password in a given url with ****."""
  428. return _transform_url(url, _redact_netloc)[0]
  429. class HiddenText:
  430. def __init__(self, secret: str, redacted: str) -> None:
  431. self.secret = secret
  432. self.redacted = redacted
  433. def __repr__(self) -> str:
  434. return "<HiddenText {!r}>".format(str(self))
  435. def __str__(self) -> str:
  436. return self.redacted
  437. # This is useful for testing.
  438. def __eq__(self, other: Any) -> bool:
  439. if type(self) != type(other):
  440. return False
  441. # The string being used for redaction doesn't also have to match,
  442. # just the raw, original string.
  443. return self.secret == other.secret
  444. def hide_value(value: str) -> HiddenText:
  445. return HiddenText(value, redacted="****")
  446. def hide_url(url: str) -> HiddenText:
  447. redacted = redact_auth_from_url(url)
  448. return HiddenText(url, redacted=redacted)
  449. def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
  450. """Protection of pip.exe from modification on Windows
  451. On Windows, any operation modifying pip should be run as:
  452. python -m pip ...
  453. """
  454. pip_names = [
  455. "pip.exe",
  456. "pip{}.exe".format(sys.version_info[0]),
  457. "pip{}.{}.exe".format(*sys.version_info[:2]),
  458. ]
  459. # See https://github.com/pypa/pip/issues/1299 for more discussion
  460. should_show_use_python_msg = (
  461. modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
  462. )
  463. if should_show_use_python_msg:
  464. new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
  465. raise CommandError(
  466. "To modify pip, please run the following command:\n{}".format(
  467. " ".join(new_command)
  468. )
  469. )
  470. def is_console_interactive() -> bool:
  471. """Is this console interactive?"""
  472. return sys.stdin is not None and sys.stdin.isatty()
  473. def hash_file(path: str, blocksize: int = 1 << 20) -> Tuple[Any, int]:
  474. """Return (hash, length) for path using hashlib.sha256()"""
  475. h = hashlib.sha256()
  476. length = 0
  477. with open(path, "rb") as f:
  478. for block in read_chunks(f, size=blocksize):
  479. length += len(block)
  480. h.update(block)
  481. return h, length
  482. def is_wheel_installed() -> bool:
  483. """
  484. Return whether the wheel package is installed.
  485. """
  486. try:
  487. import wheel # noqa: F401
  488. except ImportError:
  489. return False
  490. return True
  491. def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:
  492. """
  493. Return paired elements.
  494. For example:
  495. s -> (s0, s1), (s2, s3), (s4, s5), ...
  496. """
  497. iterable = iter(iterable)
  498. return zip_longest(iterable, iterable)
  499. def partition(
  500. pred: Callable[[T], bool],
  501. iterable: Iterable[T],
  502. ) -> Tuple[Iterable[T], Iterable[T]]:
  503. """
  504. Use a predicate to partition entries into false entries and true entries,
  505. like
  506. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  507. """
  508. t1, t2 = tee(iterable)
  509. return filterfalse(pred, t1), filter(pred, t2)