misc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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, explicitly 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: str) -> bool:
  224. """Is path is a directory containing pyproject.toml or setup.py?
  225. If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for
  226. a legacy setuptools layout by identifying setup.py. We don't check for the
  227. setup.cfg because using it without setup.py is only available for PEP 517
  228. projects, which are already covered by the pyproject.toml check.
  229. """
  230. if not os.path.isdir(path):
  231. return False
  232. if os.path.isfile(os.path.join(path, "pyproject.toml")):
  233. return True
  234. if os.path.isfile(os.path.join(path, "setup.py")):
  235. return True
  236. return False
  237. def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
  238. # type: (BinaryIO, int) -> Iterator[bytes]
  239. """Yield pieces of data from a file-like object until EOF."""
  240. while True:
  241. chunk = file.read(size)
  242. if not chunk:
  243. break
  244. yield chunk
  245. def normalize_path(path, resolve_symlinks=True):
  246. # type: (str, bool) -> str
  247. """
  248. Convert a path to its canonical, case-normalized, absolute version.
  249. """
  250. path = os.path.expanduser(path)
  251. if resolve_symlinks:
  252. path = os.path.realpath(path)
  253. else:
  254. path = os.path.abspath(path)
  255. return os.path.normcase(path)
  256. def splitext(path):
  257. # type: (str) -> Tuple[str, str]
  258. """Like os.path.splitext, but take off .tar too"""
  259. base, ext = posixpath.splitext(path)
  260. if base.lower().endswith(".tar"):
  261. ext = base[-4:] + ext
  262. base = base[:-4]
  263. return base, ext
  264. def renames(old, new):
  265. # type: (str, str) -> None
  266. """Like os.renames(), but handles renaming across devices."""
  267. # Implementation borrowed from os.renames().
  268. head, tail = os.path.split(new)
  269. if head and tail and not os.path.exists(head):
  270. os.makedirs(head)
  271. shutil.move(old, new)
  272. head, tail = os.path.split(old)
  273. if head and tail:
  274. try:
  275. os.removedirs(head)
  276. except OSError:
  277. pass
  278. def is_local(path):
  279. # type: (str) -> bool
  280. """
  281. Return True if path is within sys.prefix, if we're running in a virtualenv.
  282. If we're not in a virtualenv, all paths are considered "local."
  283. Caution: this function assumes the head of path has been normalized
  284. with normalize_path.
  285. """
  286. if not running_under_virtualenv():
  287. return True
  288. return path.startswith(normalize_path(sys.prefix))
  289. def dist_is_local(dist):
  290. # type: (Distribution) -> bool
  291. """
  292. Return True if given Distribution object is installed locally
  293. (i.e. within current virtualenv).
  294. Always True if we're not in a virtualenv.
  295. """
  296. return is_local(dist_location(dist))
  297. def dist_in_usersite(dist):
  298. # type: (Distribution) -> bool
  299. """
  300. Return True if given Distribution is installed in user site.
  301. """
  302. return dist_location(dist).startswith(normalize_path(user_site))
  303. def dist_in_site_packages(dist):
  304. # type: (Distribution) -> bool
  305. """
  306. Return True if given Distribution is installed in
  307. sysconfig.get_python_lib().
  308. """
  309. return dist_location(dist).startswith(normalize_path(site_packages))
  310. def dist_is_editable(dist):
  311. # type: (Distribution) -> bool
  312. """
  313. Return True if given Distribution is an editable install.
  314. """
  315. for path_item in sys.path:
  316. egg_link = os.path.join(path_item, dist.project_name + ".egg-link")
  317. if os.path.isfile(egg_link):
  318. return True
  319. return False
  320. def get_installed_distributions(
  321. local_only=True, # type: bool
  322. skip=stdlib_pkgs, # type: Container[str]
  323. include_editables=True, # type: bool
  324. editables_only=False, # type: bool
  325. user_only=False, # type: bool
  326. paths=None, # type: Optional[List[str]]
  327. ):
  328. # type: (...) -> List[Distribution]
  329. """Return a list of installed Distribution objects.
  330. Left for compatibility until direct pkg_resources uses are refactored out.
  331. """
  332. from pip._internal.metadata import get_default_environment, get_environment
  333. from pip._internal.metadata.pkg_resources import Distribution as _Dist
  334. if paths is None:
  335. env = get_default_environment()
  336. else:
  337. env = get_environment(paths)
  338. dists = env.iter_installed_distributions(
  339. local_only=local_only,
  340. skip=skip,
  341. include_editables=include_editables,
  342. editables_only=editables_only,
  343. user_only=user_only,
  344. )
  345. return [cast(_Dist, dist)._dist for dist in dists]
  346. def get_distribution(req_name):
  347. # type: (str) -> Optional[Distribution]
  348. """Given a requirement name, return the installed Distribution object.
  349. This searches from *all* distributions available in the environment, to
  350. match the behavior of ``pkg_resources.get_distribution()``.
  351. Left for compatibility until direct pkg_resources uses are refactored out.
  352. """
  353. from pip._internal.metadata import get_default_environment
  354. from pip._internal.metadata.pkg_resources import Distribution as _Dist
  355. dist = get_default_environment().get_distribution(req_name)
  356. if dist is None:
  357. return None
  358. return cast(_Dist, dist)._dist
  359. def egg_link_path(dist):
  360. # type: (Distribution) -> Optional[str]
  361. """
  362. Return the path for the .egg-link file if it exists, otherwise, None.
  363. There's 3 scenarios:
  364. 1) not in a virtualenv
  365. try to find in site.USER_SITE, then site_packages
  366. 2) in a no-global virtualenv
  367. try to find in site_packages
  368. 3) in a yes-global virtualenv
  369. try to find in site_packages, then site.USER_SITE
  370. (don't look in global location)
  371. For #1 and #3, there could be odd cases, where there's an egg-link in 2
  372. locations.
  373. This method will just return the first one found.
  374. """
  375. sites = []
  376. if running_under_virtualenv():
  377. sites.append(site_packages)
  378. if not virtualenv_no_global() and user_site:
  379. sites.append(user_site)
  380. else:
  381. if user_site:
  382. sites.append(user_site)
  383. sites.append(site_packages)
  384. for site in sites:
  385. egglink = os.path.join(site, dist.project_name) + ".egg-link"
  386. if os.path.isfile(egglink):
  387. return egglink
  388. return None
  389. def dist_location(dist):
  390. # type: (Distribution) -> str
  391. """
  392. Get the site-packages location of this distribution. Generally
  393. this is dist.location, except in the case of develop-installed
  394. packages, where dist.location is the source code location, and we
  395. want to know where the egg-link file is.
  396. The returned location is normalized (in particular, with symlinks removed).
  397. """
  398. egg_link = egg_link_path(dist)
  399. if egg_link:
  400. return normalize_path(egg_link)
  401. return normalize_path(dist.location)
  402. def write_output(msg, *args):
  403. # type: (Any, Any) -> None
  404. logger.info(msg, *args)
  405. class StreamWrapper(StringIO):
  406. orig_stream = None # type: TextIO
  407. @classmethod
  408. def from_stream(cls, orig_stream):
  409. # type: (TextIO) -> StreamWrapper
  410. cls.orig_stream = orig_stream
  411. return cls()
  412. # compileall.compile_dir() needs stdout.encoding to print to stdout
  413. # https://github.com/python/mypy/issues/4125
  414. @property
  415. def encoding(self): # type: ignore
  416. return self.orig_stream.encoding
  417. @contextlib.contextmanager
  418. def captured_output(stream_name):
  419. # type: (str) -> Iterator[StreamWrapper]
  420. """Return a context manager used by captured_stdout/stdin/stderr
  421. that temporarily replaces the sys stream *stream_name* with a StringIO.
  422. Taken from Lib/support/__init__.py in the CPython repo.
  423. """
  424. orig_stdout = getattr(sys, stream_name)
  425. setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
  426. try:
  427. yield getattr(sys, stream_name)
  428. finally:
  429. setattr(sys, stream_name, orig_stdout)
  430. def captured_stdout():
  431. # type: () -> ContextManager[StreamWrapper]
  432. """Capture the output of sys.stdout:
  433. with captured_stdout() as stdout:
  434. print('hello')
  435. self.assertEqual(stdout.getvalue(), 'hello\n')
  436. Taken from Lib/support/__init__.py in the CPython repo.
  437. """
  438. return captured_output("stdout")
  439. def captured_stderr():
  440. # type: () -> ContextManager[StreamWrapper]
  441. """
  442. See captured_stdout().
  443. """
  444. return captured_output("stderr")
  445. # Simulates an enum
  446. def enum(*sequential, **named):
  447. # type: (*Any, **Any) -> Type[Any]
  448. enums = dict(zip(sequential, range(len(sequential))), **named)
  449. reverse = {value: key for key, value in enums.items()}
  450. enums["reverse_mapping"] = reverse
  451. return type("Enum", (), enums)
  452. def build_netloc(host, port):
  453. # type: (str, Optional[int]) -> str
  454. """
  455. Build a netloc from a host-port pair
  456. """
  457. if port is None:
  458. return host
  459. if ":" in host:
  460. # Only wrap host with square brackets when it is IPv6
  461. host = f"[{host}]"
  462. return f"{host}:{port}"
  463. def build_url_from_netloc(netloc, scheme="https"):
  464. # type: (str, str) -> str
  465. """
  466. Build a full URL from a netloc.
  467. """
  468. if netloc.count(":") >= 2 and "@" not in netloc and "[" not in netloc:
  469. # It must be a bare IPv6 address, so wrap it with brackets.
  470. netloc = f"[{netloc}]"
  471. return f"{scheme}://{netloc}"
  472. def parse_netloc(netloc):
  473. # type: (str) -> Tuple[str, Optional[int]]
  474. """
  475. Return the host-port pair from a netloc.
  476. """
  477. url = build_url_from_netloc(netloc)
  478. parsed = urllib.parse.urlparse(url)
  479. return parsed.hostname, parsed.port
  480. def split_auth_from_netloc(netloc):
  481. # type: (str) -> NetlocTuple
  482. """
  483. Parse out and remove the auth information from a netloc.
  484. Returns: (netloc, (username, password)).
  485. """
  486. if "@" not in netloc:
  487. return netloc, (None, None)
  488. # Split from the right because that's how urllib.parse.urlsplit()
  489. # behaves if more than one @ is present (which can be checked using
  490. # the password attribute of urlsplit()'s return value).
  491. auth, netloc = netloc.rsplit("@", 1)
  492. pw = None # type: Optional[str]
  493. if ":" in auth:
  494. # Split from the left because that's how urllib.parse.urlsplit()
  495. # behaves if more than one : is present (which again can be checked
  496. # using the password attribute of the return value)
  497. user, pw = auth.split(":", 1)
  498. else:
  499. user, pw = auth, None
  500. user = urllib.parse.unquote(user)
  501. if pw is not None:
  502. pw = urllib.parse.unquote(pw)
  503. return netloc, (user, pw)
  504. def redact_netloc(netloc):
  505. # type: (str) -> str
  506. """
  507. Replace the sensitive data in a netloc with "****", if it exists.
  508. For example:
  509. - "user:pass@example.com" returns "user:****@example.com"
  510. - "accesstoken@example.com" returns "****@example.com"
  511. """
  512. netloc, (user, password) = split_auth_from_netloc(netloc)
  513. if user is None:
  514. return netloc
  515. if password is None:
  516. user = "****"
  517. password = ""
  518. else:
  519. user = urllib.parse.quote(user)
  520. password = ":****"
  521. return "{user}{password}@{netloc}".format(
  522. user=user, password=password, netloc=netloc
  523. )
  524. def _transform_url(url, transform_netloc):
  525. # type: (str, Callable[[str], Tuple[Any, ...]]) -> Tuple[str, NetlocTuple]
  526. """Transform and replace netloc in a url.
  527. transform_netloc is a function taking the netloc and returning a
  528. tuple. The first element of this tuple is the new netloc. The
  529. entire tuple is returned.
  530. Returns a tuple containing the transformed url as item 0 and the
  531. original tuple returned by transform_netloc as item 1.
  532. """
  533. purl = urllib.parse.urlsplit(url)
  534. netloc_tuple = transform_netloc(purl.netloc)
  535. # stripped url
  536. url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)
  537. surl = urllib.parse.urlunsplit(url_pieces)
  538. return surl, cast("NetlocTuple", netloc_tuple)
  539. def _get_netloc(netloc):
  540. # type: (str) -> NetlocTuple
  541. return split_auth_from_netloc(netloc)
  542. def _redact_netloc(netloc):
  543. # type: (str) -> Tuple[str,]
  544. return (redact_netloc(netloc),)
  545. def split_auth_netloc_from_url(url):
  546. # type: (str) -> Tuple[str, str, Tuple[str, str]]
  547. """
  548. Parse a url into separate netloc, auth, and url with no auth.
  549. Returns: (url_without_auth, netloc, (username, password))
  550. """
  551. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  552. return url_without_auth, netloc, auth
  553. def remove_auth_from_url(url):
  554. # type: (str) -> str
  555. """Return a copy of url with 'username:password@' removed."""
  556. # username/pass params are passed to subversion through flags
  557. # and are not recognized in the url.
  558. return _transform_url(url, _get_netloc)[0]
  559. def redact_auth_from_url(url):
  560. # type: (str) -> str
  561. """Replace the password in a given url with ****."""
  562. return _transform_url(url, _redact_netloc)[0]
  563. class HiddenText:
  564. def __init__(
  565. self,
  566. secret, # type: str
  567. redacted, # type: str
  568. ):
  569. # type: (...) -> None
  570. self.secret = secret
  571. self.redacted = redacted
  572. def __repr__(self):
  573. # type: (...) -> str
  574. return "<HiddenText {!r}>".format(str(self))
  575. def __str__(self):
  576. # type: (...) -> str
  577. return self.redacted
  578. # This is useful for testing.
  579. def __eq__(self, other):
  580. # type: (Any) -> bool
  581. if type(self) != type(other):
  582. return False
  583. # The string being used for redaction doesn't also have to match,
  584. # just the raw, original string.
  585. return self.secret == other.secret
  586. def hide_value(value):
  587. # type: (str) -> HiddenText
  588. return HiddenText(value, redacted="****")
  589. def hide_url(url):
  590. # type: (str) -> HiddenText
  591. redacted = redact_auth_from_url(url)
  592. return HiddenText(url, redacted=redacted)
  593. def protect_pip_from_modification_on_windows(modifying_pip):
  594. # type: (bool) -> None
  595. """Protection of pip.exe from modification on Windows
  596. On Windows, any operation modifying pip should be run as:
  597. python -m pip ...
  598. """
  599. pip_names = [
  600. "pip.exe",
  601. "pip{}.exe".format(sys.version_info[0]),
  602. "pip{}.{}.exe".format(*sys.version_info[:2]),
  603. ]
  604. # See https://github.com/pypa/pip/issues/1299 for more discussion
  605. should_show_use_python_msg = (
  606. modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names
  607. )
  608. if should_show_use_python_msg:
  609. new_command = [sys.executable, "-m", "pip"] + sys.argv[1:]
  610. raise CommandError(
  611. "To modify pip, please run the following command:\n{}".format(
  612. " ".join(new_command)
  613. )
  614. )
  615. def is_console_interactive():
  616. # type: () -> bool
  617. """Is this console interactive?"""
  618. return sys.stdin is not None and sys.stdin.isatty()
  619. def hash_file(path, blocksize=1 << 20):
  620. # type: (str, int) -> Tuple[Any, int]
  621. """Return (hash, length) for path using hashlib.sha256()"""
  622. h = hashlib.sha256()
  623. length = 0
  624. with open(path, "rb") as f:
  625. for block in read_chunks(f, size=blocksize):
  626. length += len(block)
  627. h.update(block)
  628. return h, length
  629. def is_wheel_installed():
  630. # type: () -> bool
  631. """
  632. Return whether the wheel package is installed.
  633. """
  634. try:
  635. import wheel # noqa: F401
  636. except ImportError:
  637. return False
  638. return True
  639. def pairwise(iterable):
  640. # type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]
  641. """
  642. Return paired elements.
  643. For example:
  644. s -> (s0, s1), (s2, s3), (s4, s5), ...
  645. """
  646. iterable = iter(iterable)
  647. return zip_longest(iterable, iterable)
  648. def partition(
  649. pred, # type: Callable[[T], bool]
  650. iterable, # type: Iterable[T]
  651. ):
  652. # type: (...) -> Tuple[Iterable[T], Iterable[T]]
  653. """
  654. Use a predicate to partition entries into false entries and true entries,
  655. like
  656. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  657. """
  658. t1, t2 = tee(iterable)
  659. return filterfalse(pred, t1), filter(pred, t2)