misc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. AnyStr,
  21. BinaryIO,
  22. Callable,
  23. Container,
  24. ContextManager,
  25. Iterable,
  26. Iterator,
  27. List,
  28. Optional,
  29. TextIO,
  30. Tuple,
  31. Type,
  32. TypeVar,
  33. cast,
  34. )
  35. from pip._vendor.pkg_resources import Distribution
  36. from pip._vendor.tenacity import retry, stop_after_delay, wait_fixed
  37. from pip import __version__
  38. from pip._internal.exceptions import CommandError
  39. from pip._internal.locations import get_major_minor_version, site_packages, user_site
  40. from pip._internal.utils.compat import WINDOWS, stdlib_pkgs
  41. from pip._internal.utils.virtualenv import (
  42. running_under_virtualenv,
  43. virtualenv_no_global,
  44. )
  45. __all__ = [
  46. "rmtree",
  47. "display_path",
  48. "backup_dir",
  49. "ask",
  50. "splitext",
  51. "format_size",
  52. "is_installable_dir",
  53. "normalize_path",
  54. "renames",
  55. "get_prog",
  56. "captured_stdout",
  57. "ensure_dir",
  58. "remove_auth_from_url",
  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. def get_pip_version():
  66. # type: () -> str
  67. pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
  68. pip_pkg_dir = os.path.abspath(pip_pkg_dir)
  69. return "pip {} from {} (python {})".format(
  70. __version__,
  71. pip_pkg_dir,
  72. get_major_minor_version(),
  73. )
  74. def normalize_version_info(py_version_info):
  75. # type: (Tuple[int, ...]) -> Tuple[int, int, int]
  76. """
  77. Convert a tuple of ints representing a Python version to one of length
  78. three.
  79. :param py_version_info: a tuple of ints representing a Python version,
  80. or None to specify no version. The tuple can have any length.
  81. :return: a tuple of length three if `py_version_info` is non-None.
  82. Otherwise, return `py_version_info` unchanged (i.e. None).
  83. """
  84. if len(py_version_info) < 3:
  85. py_version_info += (3 - len(py_version_info)) * (0,)
  86. elif len(py_version_info) > 3:
  87. py_version_info = py_version_info[:3]
  88. return cast("VersionInfo", py_version_info)
  89. def ensure_dir(path):
  90. # type: (AnyStr) -> None
  91. """os.path.makedirs without EEXIST."""
  92. try:
  93. os.makedirs(path)
  94. except OSError as e:
  95. # Windows can raise spurious ENOTEMPTY errors. See #6426.
  96. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
  97. raise
  98. def get_prog():
  99. # type: () -> str
  100. try:
  101. prog = os.path.basename(sys.argv[0])
  102. if prog in ("__main__.py", "-c"):
  103. return f"{sys.executable} -m pip"
  104. else:
  105. return prog
  106. except (AttributeError, TypeError, IndexError):
  107. pass
  108. return "pip"
  109. # Retry every half second for up to 3 seconds
  110. # Tenacity raises RetryError by default, explictly raise the original exception
  111. @retry(reraise=True, stop=stop_after_delay(3), wait=wait_fixed(0.5))
  112. def rmtree(dir, ignore_errors=False):
  113. # type: (AnyStr, bool) -> None
  114. shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler)
  115. def rmtree_errorhandler(func, path, exc_info):
  116. # type: (Callable[..., Any], str, ExcInfo) -> None
  117. """On Windows, the files in .svn are read-only, so when rmtree() tries to
  118. remove them, an exception is thrown. We catch that here, remove the
  119. read-only attribute, and hopefully continue without problems."""
  120. try:
  121. has_attr_readonly = not (os.stat(path).st_mode & stat.S_IWRITE)
  122. except OSError:
  123. # it's equivalent to os.path.exists
  124. return
  125. if has_attr_readonly:
  126. # convert to read/write
  127. os.chmod(path, stat.S_IWRITE)
  128. # use the original function to repeat the operation
  129. func(path)
  130. return
  131. else:
  132. raise
  133. def display_path(path):
  134. # type: (str) -> str
  135. """Gives the display value for a given path, making it relative to cwd
  136. if possible."""
  137. path = os.path.normcase(os.path.abspath(path))
  138. if path.startswith(os.getcwd() + os.path.sep):
  139. path = "." + path[len(os.getcwd()) :]
  140. return path
  141. def backup_dir(dir, ext=".bak"):
  142. # type: (str, str) -> str
  143. """Figure out the name of a directory to back up the given dir to
  144. (adding .bak, .bak2, etc)"""
  145. n = 1
  146. extension = ext
  147. while os.path.exists(dir + extension):
  148. n += 1
  149. extension = ext + str(n)
  150. return dir + extension
  151. def ask_path_exists(message, options):
  152. # type: (str, Iterable[str]) -> str
  153. for action in os.environ.get("PIP_EXISTS_ACTION", "").split():
  154. if action in options:
  155. return action
  156. return ask(message, options)
  157. def _check_no_input(message):
  158. # type: (str) -> None
  159. """Raise an error if no input is allowed."""
  160. if os.environ.get("PIP_NO_INPUT"):
  161. raise Exception(
  162. f"No input was expected ($PIP_NO_INPUT set); question: {message}"
  163. )
  164. def ask(message, options):
  165. # type: (str, Iterable[str]) -> str
  166. """Ask the message interactively, with the given possible responses"""
  167. while 1:
  168. _check_no_input(message)
  169. response = input(message)
  170. response = response.strip().lower()
  171. if response not in options:
  172. print(
  173. "Your response ({!r}) was not one of the expected responses: "
  174. "{}".format(response, ", ".join(options))
  175. )
  176. else:
  177. return response
  178. def ask_input(message):
  179. # type: (str) -> str
  180. """Ask for input interactively."""
  181. _check_no_input(message)
  182. return input(message)
  183. def ask_password(message):
  184. # type: (str) -> str
  185. """Ask for a password interactively."""
  186. _check_no_input(message)
  187. return getpass.getpass(message)
  188. def strtobool(val):
  189. # type: (str) -> int
  190. """Convert a string representation of truth to true (1) or false (0).
  191. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  192. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  193. 'val' is anything else.
  194. """
  195. val = val.lower()
  196. if val in ("y", "yes", "t", "true", "on", "1"):
  197. return 1
  198. elif val in ("n", "no", "f", "false", "off", "0"):
  199. return 0
  200. else:
  201. raise ValueError(f"invalid truth value {val!r}")
  202. def format_size(bytes):
  203. # type: (float) -> str
  204. if bytes > 1000 * 1000:
  205. return "{:.1f} MB".format(bytes / 1000.0 / 1000)
  206. elif bytes > 10 * 1000:
  207. return "{} kB".format(int(bytes / 1000))
  208. elif bytes > 1000:
  209. return "{:.1f} kB".format(bytes / 1000.0)
  210. else:
  211. return "{} bytes".format(int(bytes))
  212. def tabulate(rows):
  213. # type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]
  214. """Return a list of formatted rows and a list of column sizes.
  215. For example::
  216. >>> tabulate([['foobar', 2000], [0xdeadbeef]])
  217. (['foobar 2000', '3735928559'], [10, 4])
  218. """
  219. rows = [tuple(map(str, row)) for row in rows]
  220. sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue="")]
  221. table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
  222. return table, sizes
  223. def is_installable_dir(path):
  224. # type: (str) -> bool
  225. """Is path is a directory containing setup.py or pyproject.toml?"""
  226. if not os.path.isdir(path):
  227. return False
  228. setup_py = os.path.join(path, "setup.py")
  229. if os.path.isfile(setup_py):
  230. return True
  231. pyproject_toml = os.path.join(path, "pyproject.toml")
  232. if os.path.isfile(pyproject_toml):
  233. return True
  234. return False
  235. def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
  236. # type: (BinaryIO, int) -> Iterator[bytes]
  237. """Yield pieces of data from a file-like object until EOF."""
  238. while True:
  239. chunk = file.read(size)
  240. if not chunk:
  241. break
  242. yield chunk
  243. def normalize_path(path, resolve_symlinks=True):
  244. # type: (str, bool) -> str
  245. """
  246. Convert a path to its canonical, case-normalized, absolute version.
  247. """
  248. path = os.path.expanduser(path)
  249. if resolve_symlinks:
  250. path = os.path.realpath(path)
  251. else:
  252. path = os.path.abspath(path)
  253. return os.path.normcase(path)
  254. def splitext(path):
  255. # type: (str) -> Tuple[str, str]
  256. """Like os.path.splitext, but take off .tar too"""
  257. base, ext = posixpath.splitext(path)
  258. if base.lower().endswith(".tar"):
  259. ext = base[-4:] + ext
  260. base = base[:-4]
  261. return base, ext
  262. def renames(old, new):
  263. # type: (str, str) -> None
  264. """Like os.renames(), but handles renaming across devices."""
  265. # Implementation borrowed from os.renames().
  266. head, tail = os.path.split(new)
  267. if head and tail and not os.path.exists(head):
  268. os.makedirs(head)
  269. shutil.move(old, new)
  270. head, tail = os.path.split(old)
  271. if head and tail:
  272. try:
  273. os.removedirs(head)
  274. except OSError:
  275. pass
  276. def is_local(path):
  277. # type: (str) -> bool
  278. """
  279. Return True if path is within sys.prefix, if we're running in a virtualenv.
  280. If we're not in a virtualenv, all paths are considered "local."
  281. Caution: this function assumes the head of path has been normalized
  282. with normalize_path.
  283. """
  284. if not running_under_virtualenv():
  285. return True
  286. return path.startswith(normalize_path(sys.prefix))
  287. def dist_is_local(dist):
  288. # type: (Distribution) -> bool
  289. """
  290. Return True if given Distribution object is installed locally
  291. (i.e. within current virtualenv).
  292. Always True if we're not in a virtualenv.
  293. """
  294. return is_local(dist_location(dist))
  295. def dist_in_usersite(dist):
  296. # type: (Distribution) -> bool
  297. """
  298. Return True if given Distribution is installed in user site.
  299. """
  300. return dist_location(dist).startswith(normalize_path(user_site))
  301. def dist_in_site_packages(dist):
  302. # type: (Distribution) -> bool
  303. """
  304. Return True if given Distribution is installed in
  305. sysconfig.get_python_lib().
  306. """
  307. return dist_location(dist).startswith(normalize_path(site_packages))
  308. def dist_is_editable(dist):
  309. # type: (Distribution) -> bool
  310. """
  311. Return True if given Distribution is an editable install.
  312. """
  313. for path_item in sys.path:
  314. egg_link = os.path.join(path_item, dist.project_name + ".egg-link")
  315. if os.path.isfile(egg_link):
  316. return True
  317. return False
  318. def get_installed_distributions(
  319. local_only=True, # type: bool
  320. skip=stdlib_pkgs, # type: Container[str]
  321. include_editables=True, # type: bool
  322. editables_only=False, # type: bool
  323. user_only=False, # type: bool
  324. paths=None, # type: Optional[List[str]]
  325. ):
  326. # type: (...) -> List[Distribution]
  327. """Return a list of installed Distribution objects.
  328. Left for compatibility until direct pkg_resources uses are refactored out.
  329. """
  330. from pip._internal.metadata import get_default_environment, get_environment
  331. from pip._internal.metadata.pkg_resources import Distribution as _Dist
  332. if paths is None:
  333. env = get_default_environment()
  334. else:
  335. env = get_environment(paths)
  336. dists = env.iter_installed_distributions(
  337. local_only=local_only,
  338. skip=skip,
  339. include_editables=include_editables,
  340. editables_only=editables_only,
  341. user_only=user_only,
  342. )
  343. return [cast(_Dist, dist)._dist for dist in dists]
  344. def get_distribution(req_name):
  345. # type: (str) -> Optional[Distribution]
  346. """Given a requirement name, return the installed Distribution object.
  347. This searches from *all* distributions available in the environment, to
  348. match the behavior of ``pkg_resources.get_distribution()``.
  349. Left for compatibility until direct pkg_resources uses are refactored out.
  350. """
  351. from pip._internal.metadata import get_default_environment
  352. from pip._internal.metadata.pkg_resources import Distribution as _Dist
  353. dist = get_default_environment().get_distribution(req_name)
  354. if dist is None:
  355. return None
  356. return cast(_Dist, dist)._dist
  357. def egg_link_path(dist):
  358. # type: (Distribution) -> Optional[str]
  359. """
  360. Return the path for the .egg-link file if it exists, otherwise, None.
  361. There's 3 scenarios:
  362. 1) not in a virtualenv
  363. try to find in site.USER_SITE, then site_packages
  364. 2) in a no-global virtualenv
  365. try to find in site_packages
  366. 3) in a yes-global virtualenv
  367. try to find in site_packages, then site.USER_SITE
  368. (don't look in global location)
  369. For #1 and #3, there could be odd cases, where there's an egg-link in 2
  370. locations.
  371. This method will just return the first one found.
  372. """
  373. sites = []
  374. if running_under_virtualenv():
  375. sites.append(site_packages)
  376. if not virtualenv_no_global() and user_site:
  377. sites.append(user_site)
  378. else:
  379. if user_site:
  380. sites.append(user_site)
  381. sites.append(site_packages)
  382. for site in sites:
  383. egglink = os.path.join(site, dist.project_name) + ".egg-link"
  384. if os.path.isfile(egglink):
  385. return egglink
  386. return None
  387. def dist_location(dist):
  388. # type: (Distribution) -> str
  389. """
  390. Get the site-packages location of this distribution. Generally
  391. this is dist.location, except in the case of develop-installed
  392. packages, where dist.location is the source code location, and we
  393. want to know where the egg-link file is.
  394. The returned location is normalized (in particular, with symlinks removed).
  395. """
  396. egg_link = egg_link_path(dist)
  397. if egg_link:
  398. return normalize_path(egg_link)
  399. return normalize_path(dist.location)
  400. def write_output(msg, *args):
  401. # type: (Any, Any) -> None
  402. logger.info(msg, *args)
  403. class StreamWrapper(StringIO):
  404. orig_stream = None # type: TextIO
  405. @classmethod
  406. def from_stream(cls, orig_stream):
  407. # type: (TextIO) -> StreamWrapper
  408. cls.orig_stream = orig_stream
  409. return cls()
  410. # compileall.compile_dir() needs stdout.encoding to print to stdout
  411. # https://github.com/python/mypy/issues/4125
  412. @property
  413. def encoding(self): # type: ignore
  414. return self.orig_stream.encoding
  415. @contextlib.contextmanager
  416. def captured_output(stream_name):
  417. # type: (str) -> Iterator[StreamWrapper]
  418. """Return a context manager used by captured_stdout/stdin/stderr
  419. that temporarily replaces the sys stream *stream_name* with a StringIO.
  420. Taken from Lib/support/__init__.py in the CPython repo.
  421. """
  422. orig_stdout = getattr(sys, stream_name)
  423. setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
  424. try:
  425. yield getattr(sys, stream_name)
  426. finally:
  427. setattr(sys, stream_name, orig_stdout)
  428. def captured_stdout():
  429. # type: () -> ContextManager[StreamWrapper]
  430. """Capture the output of sys.stdout:
  431. with captured_stdout() as stdout:
  432. print('hello')
  433. self.assertEqual(stdout.getvalue(), 'hello\n')
  434. Taken from Lib/support/__init__.py in the CPython repo.
  435. """
  436. return captured_output("stdout")
  437. def captured_stderr():
  438. # type: () -> ContextManager[StreamWrapper]
  439. """
  440. See captured_stdout().
  441. """
  442. return captured_output("stderr")
  443. # Simulates an enum
  444. def enum(*sequential, **named):
  445. # type: (*Any, **Any) -> Type[Any]
  446. enums = dict(zip(sequential, range(len(sequential))), **named)
  447. reverse = {value: key for key, value in enums.items()}
  448. enums["reverse_mapping"] = reverse
  449. return type("Enum", (), enums)
  450. def build_netloc(host, port):
  451. # type: (str, Optional[int]) -> str
  452. """
  453. Build a netloc from a host-port pair
  454. """
  455. if port is None:
  456. return host
  457. if ":" in host:
  458. # Only wrap host with square brackets when it is IPv6
  459. host = f"[{host}]"
  460. return f"{host}:{port}"
  461. def build_url_from_netloc(netloc, scheme="https"):
  462. # type: (str, str) -> str
  463. """
  464. Build a full URL from a netloc.
  465. """
  466. if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
  467. # It must be a bare IPv6 address, so wrap it with brackets.
  468. netloc = f"[{netloc}]"
  469. return f"{scheme}://{netloc}"
  470. def parse_netloc(netloc):
  471. # type: (str) -> Tuple[str, Optional[int]]
  472. """
  473. Return the host-port pair from a netloc.
  474. """
  475. url = build_url_from_netloc(netloc)
  476. parsed = urllib.parse.urlparse(url)
  477. return parsed.hostname, parsed.port
  478. def split_auth_from_netloc(netloc):
  479. # type: (str) -> NetlocTuple
  480. """
  481. Parse out and remove the auth information from a netloc.
  482. Returns: (netloc, (username, password)).
  483. """
  484. if "@" not in netloc:
  485. return netloc, (None, None)
  486. # Split from the right because that's how urllib.parse.urlsplit()
  487. # behaves if more than one @ is present (which can be checked using
  488. # the password attribute of urlsplit()'s return value).
  489. auth, netloc = netloc.rsplit("@", 1)
  490. pw = None # type: Optional[str]
  491. if ":" in auth:
  492. # Split from the left because that's how urllib.parse.urlsplit()
  493. # behaves if more than one : is present (which again can be checked
  494. # using the password attribute of the return value)
  495. user, pw = auth.split(":", 1)
  496. else:
  497. user, pw = auth, None
  498. user = urllib.parse.unquote(user)
  499. if pw is not None:
  500. pw = urllib.parse.unquote(pw)
  501. return netloc, (user, pw)
  502. def redact_netloc(netloc):
  503. # type: (str) -> str
  504. """
  505. Replace the sensitive data in a netloc with "****", if it exists.
  506. For example:
  507. - "user:pass@example.com" returns "user:****@example.com"
  508. - "accesstoken@example.com" returns "****@example.com"
  509. """
  510. netloc, (user, password) = split_auth_from_netloc(netloc)
  511. if user is None:
  512. return netloc
  513. if password is None:
  514. user = "****"
  515. password = ""
  516. else:
  517. user = urllib.parse.quote(user)
  518. password = ":****"
  519. return "{user}{password}@{netloc}".format(
  520. user=user, password=password, netloc=netloc
  521. )
  522. def _transform_url(url, transform_netloc):
  523. # type: (str, Callable[[str], Tuple[Any, ...]]) -> Tuple[str, NetlocTuple]
  524. """Transform and replace netloc in a url.
  525. transform_netloc is a function taking the netloc and returning a
  526. tuple. The first element of this tuple is the new netloc. The
  527. entire tuple is returned.
  528. Returns a tuple containing the transformed url as item 0 and the
  529. original tuple returned by transform_netloc as item 1.
  530. """
  531. purl = urllib.parse.urlsplit(url)
  532. netloc_tuple = transform_netloc(purl.netloc)
  533. # stripped url
  534. url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
  535. surl = urllib.parse.urlunsplit(url_pieces)
  536. return surl, cast("NetlocTuple", netloc_tuple)
  537. def _get_netloc(netloc):
  538. # type: (str) -> NetlocTuple
  539. return split_auth_from_netloc(netloc)
  540. def _redact_netloc(netloc):
  541. # type: (str) -> Tuple[str,]
  542. return (redact_netloc(netloc),)
  543. def split_auth_netloc_from_url(url):
  544. # type: (str) -> Tuple[str, str, Tuple[str, str]]
  545. """
  546. Parse a url into separate netloc, auth, and url with no auth.
  547. Returns: (url_without_auth, netloc, (username, password))
  548. """
  549. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  550. return url_without_auth, netloc, auth
  551. def remove_auth_from_url(url):
  552. # type: (str) -> str
  553. """Return a copy of url with 'username:password@' removed."""
  554. # username/pass params are passed to subversion through flags
  555. # and are not recognized in the url.
  556. return _transform_url(url, _get_netloc)[0]
  557. def redact_auth_from_url(url):
  558. # type: (str) -> str
  559. """Replace the password in a given url with ****."""
  560. return _transform_url(url, _redact_netloc)[0]
  561. class HiddenText:
  562. def __init__(
  563. self,
  564. secret, # type: str
  565. redacted, # type: str
  566. ):
  567. # type: (...) -> None
  568. self.secret = secret
  569. self.redacted = redacted
  570. def __repr__(self):
  571. # type: (...) -> str
  572. return "<HiddenText {!r}>".format(str(self))
  573. def __str__(self):
  574. # type: (...) -> str
  575. return self.redacted
  576. # This is useful for testing.
  577. def __eq__(self, other):
  578. # type: (Any) -> bool
  579. if type(self) != type(other):
  580. return False
  581. # The string being used for redaction doesn't also have to match,
  582. # just the raw, original string.
  583. return self.secret == other.secret
  584. def hide_value(value):
  585. # type: (str) -> HiddenText
  586. return HiddenText(value, redacted="****")
  587. def hide_url(url):
  588. # type: (str) -> HiddenText
  589. redacted = redact_auth_from_url(url)
  590. return HiddenText(url, redacted=redacted)
  591. def protect_pip_from_modification_on_windows(modifying_pip):
  592. # type: (bool) -> None
  593. """Protection of pip.exe from modification on Windows
  594. On Windows, any operation modifying pip should be run as:
  595. python -m pip ...
  596. """
  597. pip_names = [
  598. "pip.exe",
  599. "pip{}.exe".format(sys.version_info[0]),
  600. "pip{}.{}.exe".format(*sys.version_info[:2]),
  601. ]
  602. # See https://github.com/pypa/pip/issues/1299 for more discussion
  603. should_show_use_python_msg = (
  604. modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
  605. )
  606. if should_show_use_python_msg:
  607. new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
  608. raise CommandError(
  609. "To modify pip, please run the following command:\n{}".format(
  610. " ".join(new_command)
  611. )
  612. )
  613. def is_console_interactive():
  614. # type: () -> bool
  615. """Is this console interactive?"""
  616. return sys.stdin is not None and sys.stdin.isatty()
  617. def hash_file(path, blocksize=1 << 20):
  618. # type: (str, int) -> Tuple[Any, int]
  619. """Return (hash, length) for path using hashlib.sha256()"""
  620. h = hashlib.sha256()
  621. length = 0
  622. with open(path, "rb") as f:
  623. for block in read_chunks(f, size=blocksize):
  624. length += len(block)
  625. h.update(block)
  626. return h, length
  627. def is_wheel_installed():
  628. # type: () -> bool
  629. """
  630. Return whether the wheel package is installed.
  631. """
  632. try:
  633. import wheel # noqa: F401
  634. except ImportError:
  635. return False
  636. return True
  637. def pairwise(iterable):
  638. # type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]
  639. """
  640. Return paired elements.
  641. For example:
  642. s -> (s0, s1), (s2, s3), (s4, s5), ...
  643. """
  644. iterable = iter(iterable)
  645. return zip_longest(iterable, iterable)
  646. def partition(
  647. pred, # type: Callable[[T], bool]
  648. iterable, # type: Iterable[T]
  649. ):
  650. # type: (...) -> Tuple[Iterable[T], Iterable[T]]
  651. """
  652. Use a predicate to partition entries into false entries and true entries,
  653. like
  654. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  655. """
  656. t1, t2 = tee(iterable)
  657. return filterfalse(pred, t1), filter(pred, t2)