misc.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 path is within sys.prefix, if we're running in a virtualenv.
  255. If we're not in a virtualenv, all paths are considered "local."
  256. Caution: this function assumes the head of path has been normalized
  257. with normalize_path.
  258. """
  259. if not running_under_virtualenv():
  260. return True
  261. return path.startswith(normalize_path(sys.prefix))
  262. def write_output(msg: Any, *args: Any) -> None:
  263. logger.info(msg, *args)
  264. class StreamWrapper(StringIO):
  265. orig_stream: TextIO = None
  266. @classmethod
  267. def from_stream(cls, orig_stream: TextIO) -> "StreamWrapper":
  268. cls.orig_stream = orig_stream
  269. return cls()
  270. # compileall.compile_dir() needs stdout.encoding to print to stdout
  271. # https://github.com/python/mypy/issues/4125
  272. @property
  273. def encoding(self): # type: ignore
  274. return self.orig_stream.encoding
  275. @contextlib.contextmanager
  276. def captured_output(stream_name: str) -> Iterator[StreamWrapper]:
  277. """Return a context manager used by captured_stdout/stdin/stderr
  278. that temporarily replaces the sys stream *stream_name* with a StringIO.
  279. Taken from Lib/support/__init__.py in the CPython repo.
  280. """
  281. orig_stdout = getattr(sys, stream_name)
  282. setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
  283. try:
  284. yield getattr(sys, stream_name)
  285. finally:
  286. setattr(sys, stream_name, orig_stdout)
  287. def captured_stdout() -> ContextManager[StreamWrapper]:
  288. """Capture the output of sys.stdout:
  289. with captured_stdout() as stdout:
  290. print('hello')
  291. self.assertEqual(stdout.getvalue(), 'hello\n')
  292. Taken from Lib/support/__init__.py in the CPython repo.
  293. """
  294. return captured_output("stdout")
  295. def captured_stderr() -> ContextManager[StreamWrapper]:
  296. """
  297. See captured_stdout().
  298. """
  299. return captured_output("stderr")
  300. # Simulates an enum
  301. def enum(*sequential: Any, **named: Any) -> Type[Any]:
  302. enums = dict(zip(sequential, range(len(sequential))), **named)
  303. reverse = {value: key for key, value in enums.items()}
  304. enums["reverse_mapping"] = reverse
  305. return type("Enum", (), enums)
  306. def build_netloc(host: str, port: Optional[int]) -> str:
  307. """
  308. Build a netloc from a host-port pair
  309. """
  310. if port is None:
  311. return host
  312. if ":" in host:
  313. # Only wrap host with square brackets when it is IPv6
  314. host = f"[{host}]"
  315. return f"{host}:{port}"
  316. def build_url_from_netloc(netloc: str, scheme: str = "https") -> str:
  317. """
  318. Build a full URL from a netloc.
  319. """
  320. if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
  321. # It must be a bare IPv6 address, so wrap it with brackets.
  322. netloc = f"[{netloc}]"
  323. return f"{scheme}://{netloc}"
  324. def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]:
  325. """
  326. Return the host-port pair from a netloc.
  327. """
  328. url = build_url_from_netloc(netloc)
  329. parsed = urllib.parse.urlparse(url)
  330. return parsed.hostname, parsed.port
  331. def split_auth_from_netloc(netloc: str) -> NetlocTuple:
  332. """
  333. Parse out and remove the auth information from a netloc.
  334. Returns: (netloc, (username, password)).
  335. """
  336. if "@" not in netloc:
  337. return netloc, (None, None)
  338. # Split from the right because that's how urllib.parse.urlsplit()
  339. # behaves if more than one @ is present (which can be checked using
  340. # the password attribute of urlsplit()'s return value).
  341. auth, netloc = netloc.rsplit("@", 1)
  342. pw: Optional[str] = None
  343. if ":" in auth:
  344. # Split from the left because that's how urllib.parse.urlsplit()
  345. # behaves if more than one : is present (which again can be checked
  346. # using the password attribute of the return value)
  347. user, pw = auth.split(":", 1)
  348. else:
  349. user, pw = auth, None
  350. user = urllib.parse.unquote(user)
  351. if pw is not None:
  352. pw = urllib.parse.unquote(pw)
  353. return netloc, (user, pw)
  354. def redact_netloc(netloc: str) -> str:
  355. """
  356. Replace the sensitive data in a netloc with "****", if it exists.
  357. For example:
  358. - "user:pass@example.com" returns "user:****@example.com"
  359. - "accesstoken@example.com" returns "****@example.com"
  360. """
  361. netloc, (user, password) = split_auth_from_netloc(netloc)
  362. if user is None:
  363. return netloc
  364. if password is None:
  365. user = "****"
  366. password = ""
  367. else:
  368. user = urllib.parse.quote(user)
  369. password = ":****"
  370. return "{user}{password}@{netloc}".format(
  371. user=user, password=password, netloc=netloc
  372. )
  373. def _transform_url(
  374. url: str, transform_netloc: Callable[[str], Tuple[Any, ...]]
  375. ) -> Tuple[str, NetlocTuple]:
  376. """Transform and replace netloc in a url.
  377. transform_netloc is a function taking the netloc and returning a
  378. tuple. The first element of this tuple is the new netloc. The
  379. entire tuple is returned.
  380. Returns a tuple containing the transformed url as item 0 and the
  381. original tuple returned by transform_netloc as item 1.
  382. """
  383. purl = urllib.parse.urlsplit(url)
  384. netloc_tuple = transform_netloc(purl.netloc)
  385. # stripped url
  386. url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
  387. surl = urllib.parse.urlunsplit(url_pieces)
  388. return surl, cast("NetlocTuple", netloc_tuple)
  389. def _get_netloc(netloc: str) -> NetlocTuple:
  390. return split_auth_from_netloc(netloc)
  391. def _redact_netloc(netloc: str) -> Tuple[str]:
  392. return (redact_netloc(netloc),)
  393. def split_auth_netloc_from_url(url: str) -> Tuple[str, str, Tuple[str, str]]:
  394. """
  395. Parse a url into separate netloc, auth, and url with no auth.
  396. Returns: (url_without_auth, netloc, (username, password))
  397. """
  398. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  399. return url_without_auth, netloc, auth
  400. def remove_auth_from_url(url: str) -> str:
  401. """Return a copy of url with 'username:password@' removed."""
  402. # username/pass params are passed to subversion through flags
  403. # and are not recognized in the url.
  404. return _transform_url(url, _get_netloc)[0]
  405. def redact_auth_from_url(url: str) -> str:
  406. """Replace the password in a given url with ****."""
  407. return _transform_url(url, _redact_netloc)[0]
  408. class HiddenText:
  409. def __init__(self, secret: str, redacted: str) -> None:
  410. self.secret = secret
  411. self.redacted = redacted
  412. def __repr__(self) -> str:
  413. return "<HiddenText {!r}>".format(str(self))
  414. def __str__(self) -> str:
  415. return self.redacted
  416. # This is useful for testing.
  417. def __eq__(self, other: Any) -> bool:
  418. if type(self) != type(other):
  419. return False
  420. # The string being used for redaction doesn't also have to match,
  421. # just the raw, original string.
  422. return self.secret == other.secret
  423. def hide_value(value: str) -> HiddenText:
  424. return HiddenText(value, redacted="****")
  425. def hide_url(url: str) -> HiddenText:
  426. redacted = redact_auth_from_url(url)
  427. return HiddenText(url, redacted=redacted)
  428. def protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:
  429. """Protection of pip.exe from modification on Windows
  430. On Windows, any operation modifying pip should be run as:
  431. python -m pip ...
  432. """
  433. pip_names = [
  434. "pip.exe",
  435. "pip{}.exe".format(sys.version_info[0]),
  436. "pip{}.{}.exe".format(*sys.version_info[:2]),
  437. ]
  438. # See https://github.com/pypa/pip/issues/1299 for more discussion
  439. should_show_use_python_msg = (
  440. modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
  441. )
  442. if should_show_use_python_msg:
  443. new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
  444. raise CommandError(
  445. "To modify pip, please run the following command:\n{}".format(
  446. " ".join(new_command)
  447. )
  448. )
  449. def is_console_interactive() -> bool:
  450. """Is this console interactive?"""
  451. return sys.stdin is not None and sys.stdin.isatty()
  452. def hash_file(path: str, blocksize: int = 1 << 20) -> Tuple[Any, int]:
  453. """Return (hash, length) for path using hashlib.sha256()"""
  454. h = hashlib.sha256()
  455. length = 0
  456. with open(path, "rb") as f:
  457. for block in read_chunks(f, size=blocksize):
  458. length += len(block)
  459. h.update(block)
  460. return h, length
  461. def is_wheel_installed() -> bool:
  462. """
  463. Return whether the wheel package is installed.
  464. """
  465. try:
  466. import wheel # noqa: F401
  467. except ImportError:
  468. return False
  469. return True
  470. def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:
  471. """
  472. Return paired elements.
  473. For example:
  474. s -> (s0, s1), (s2, s3), (s4, s5), ...
  475. """
  476. iterable = iter(iterable)
  477. return zip_longest(iterable, iterable)
  478. def partition(
  479. pred: Callable[[T], bool],
  480. iterable: Iterable[T],
  481. ) -> Tuple[Iterable[T], Iterable[T]]:
  482. """
  483. Use a predicate to partition entries into false entries and true entries,
  484. like
  485. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  486. """
  487. t1, t2 = tee(iterable)
  488. return filterfalse(pred, t1), filter(pred, t2)