misc.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. # The following comment should be removed at some point in the future.
  2. # mypy: strict-optional=False
  3. # mypy: disallow-untyped-defs=False
  4. from __future__ import absolute_import
  5. import contextlib
  6. import errno
  7. import getpass
  8. import hashlib
  9. import io
  10. import logging
  11. import os
  12. import posixpath
  13. import shutil
  14. import stat
  15. import sys
  16. from collections import deque
  17. from itertools import tee
  18. from pip._vendor import pkg_resources
  19. from pip._vendor.packaging.utils import canonicalize_name
  20. # NOTE: retrying is not annotated in typeshed as on 2017-07-17, which is
  21. # why we ignore the type on this import.
  22. from pip._vendor.retrying import retry # type: ignore
  23. from pip._vendor.six import PY2, text_type
  24. from pip._vendor.six.moves import filter, filterfalse, input, map, zip_longest
  25. from pip._vendor.six.moves.urllib import parse as urllib_parse
  26. from pip._vendor.six.moves.urllib.parse import unquote as urllib_unquote
  27. from pip import __version__
  28. from pip._internal.exceptions import CommandError
  29. from pip._internal.locations import get_major_minor_version, site_packages, user_site
  30. from pip._internal.utils.compat import WINDOWS, expanduser, stdlib_pkgs, str_to_display
  31. from pip._internal.utils.typing import MYPY_CHECK_RUNNING, cast
  32. from pip._internal.utils.virtualenv import (
  33. running_under_virtualenv,
  34. virtualenv_no_global,
  35. )
  36. if PY2:
  37. from io import BytesIO as StringIO
  38. else:
  39. from io import StringIO
  40. if MYPY_CHECK_RUNNING:
  41. from typing import (
  42. Any,
  43. AnyStr,
  44. Callable,
  45. Container,
  46. Iterable,
  47. Iterator,
  48. List,
  49. Optional,
  50. Text,
  51. Tuple,
  52. TypeVar,
  53. Union,
  54. )
  55. from pip._vendor.pkg_resources import Distribution
  56. VersionInfo = Tuple[int, int, int]
  57. T = TypeVar("T")
  58. __all__ = ['rmtree', 'display_path', 'backup_dir',
  59. 'ask', 'splitext',
  60. 'format_size', 'is_installable_dir',
  61. 'normalize_path',
  62. 'renames', 'get_prog',
  63. 'captured_stdout', 'ensure_dir',
  64. 'get_installed_version', 'remove_auth_from_url']
  65. logger = logging.getLogger(__name__)
  66. def get_pip_version():
  67. # type: () -> str
  68. pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
  69. pip_pkg_dir = os.path.abspath(pip_pkg_dir)
  70. return (
  71. 'pip {} from {} (python {})'.format(
  72. __version__, pip_pkg_dir, get_major_minor_version(),
  73. )
  74. )
  75. def normalize_version_info(py_version_info):
  76. # type: (Tuple[int, ...]) -> Tuple[int, int, int]
  77. """
  78. Convert a tuple of ints representing a Python version to one of length
  79. three.
  80. :param py_version_info: a tuple of ints representing a Python version,
  81. or None to specify no version. The tuple can have any length.
  82. :return: a tuple of length three if `py_version_info` is non-None.
  83. Otherwise, return `py_version_info` unchanged (i.e. None).
  84. """
  85. if len(py_version_info) < 3:
  86. py_version_info += (3 - len(py_version_info)) * (0,)
  87. elif len(py_version_info) > 3:
  88. py_version_info = py_version_info[:3]
  89. return cast('VersionInfo', py_version_info)
  90. def ensure_dir(path):
  91. # type: (AnyStr) -> None
  92. """os.path.makedirs without EEXIST."""
  93. try:
  94. os.makedirs(path)
  95. except OSError as e:
  96. # Windows can raise spurious ENOTEMPTY errors. See #6426.
  97. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:
  98. raise
  99. def get_prog():
  100. # type: () -> str
  101. try:
  102. prog = os.path.basename(sys.argv[0])
  103. if prog in ('__main__.py', '-c'):
  104. return "{} -m pip".format(sys.executable)
  105. else:
  106. return prog
  107. except (AttributeError, TypeError, IndexError):
  108. pass
  109. return 'pip'
  110. # Retry every half second for up to 3 seconds
  111. @retry(stop_max_delay=3000, wait_fixed=500)
  112. def rmtree(dir, ignore_errors=False):
  113. # type: (AnyStr, bool) -> None
  114. shutil.rmtree(dir, ignore_errors=ignore_errors,
  115. onerror=rmtree_errorhandler)
  116. def rmtree_errorhandler(func, path, exc_info):
  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 (IOError, 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 path_to_display(path):
  134. # type: (Optional[Union[str, Text]]) -> Optional[Text]
  135. """
  136. Convert a bytes (or text) path to text (unicode in Python 2) for display
  137. and logging purposes.
  138. This function should never error out. Also, this function is mainly needed
  139. for Python 2 since in Python 3 str paths are already text.
  140. """
  141. if path is None:
  142. return None
  143. if isinstance(path, text_type):
  144. return path
  145. # Otherwise, path is a bytes object (str in Python 2).
  146. try:
  147. display_path = path.decode(sys.getfilesystemencoding(), 'strict')
  148. except UnicodeDecodeError:
  149. # Include the full bytes to make troubleshooting easier, even though
  150. # it may not be very human readable.
  151. if PY2:
  152. # Convert the bytes to a readable str representation using
  153. # repr(), and then convert the str to unicode.
  154. # Also, we add the prefix "b" to the repr() return value both
  155. # to make the Python 2 output look like the Python 3 output, and
  156. # to signal to the user that this is a bytes representation.
  157. display_path = str_to_display('b{!r}'.format(path))
  158. else:
  159. # Silence the "F821 undefined name 'ascii'" flake8 error since
  160. # in Python 3 ascii() is a built-in.
  161. display_path = ascii(path) # noqa: F821
  162. return display_path
  163. def display_path(path):
  164. # type: (Union[str, Text]) -> str
  165. """Gives the display value for a given path, making it relative to cwd
  166. if possible."""
  167. path = os.path.normcase(os.path.abspath(path))
  168. if sys.version_info[0] == 2:
  169. path = path.decode(sys.getfilesystemencoding(), 'replace')
  170. path = path.encode(sys.getdefaultencoding(), 'replace')
  171. if path.startswith(os.getcwd() + os.path.sep):
  172. path = '.' + path[len(os.getcwd()):]
  173. return path
  174. def backup_dir(dir, ext='.bak'):
  175. # type: (str, str) -> str
  176. """Figure out the name of a directory to back up the given dir to
  177. (adding .bak, .bak2, etc)"""
  178. n = 1
  179. extension = ext
  180. while os.path.exists(dir + extension):
  181. n += 1
  182. extension = ext + str(n)
  183. return dir + extension
  184. def ask_path_exists(message, options):
  185. # type: (str, Iterable[str]) -> str
  186. for action in os.environ.get('PIP_EXISTS_ACTION', '').split():
  187. if action in options:
  188. return action
  189. return ask(message, options)
  190. def _check_no_input(message):
  191. # type: (str) -> None
  192. """Raise an error if no input is allowed."""
  193. if os.environ.get('PIP_NO_INPUT'):
  194. raise Exception(
  195. 'No input was expected ($PIP_NO_INPUT set); question: {}'.format(
  196. message)
  197. )
  198. def ask(message, options):
  199. # type: (str, Iterable[str]) -> str
  200. """Ask the message interactively, with the given possible responses"""
  201. while 1:
  202. _check_no_input(message)
  203. response = input(message)
  204. response = response.strip().lower()
  205. if response not in options:
  206. print(
  207. 'Your response ({!r}) was not one of the expected responses: '
  208. '{}'.format(response, ', '.join(options))
  209. )
  210. else:
  211. return response
  212. def ask_input(message):
  213. # type: (str) -> str
  214. """Ask for input interactively."""
  215. _check_no_input(message)
  216. return input(message)
  217. def ask_password(message):
  218. # type: (str) -> str
  219. """Ask for a password interactively."""
  220. _check_no_input(message)
  221. return getpass.getpass(message)
  222. def format_size(bytes):
  223. # type: (float) -> str
  224. if bytes > 1000 * 1000:
  225. return '{:.1f} MB'.format(bytes / 1000.0 / 1000)
  226. elif bytes > 10 * 1000:
  227. return '{} kB'.format(int(bytes / 1000))
  228. elif bytes > 1000:
  229. return '{:.1f} kB'.format(bytes / 1000.0)
  230. else:
  231. return '{} bytes'.format(int(bytes))
  232. def tabulate(rows):
  233. # type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]
  234. """Return a list of formatted rows and a list of column sizes.
  235. For example::
  236. >>> tabulate([['foobar', 2000], [0xdeadbeef]])
  237. (['foobar 2000', '3735928559'], [10, 4])
  238. """
  239. rows = [tuple(map(str, row)) for row in rows]
  240. sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue='')]
  241. table = [" ".join(map(str.ljust, row, sizes)).rstrip() for row in rows]
  242. return table, sizes
  243. def is_installable_dir(path):
  244. # type: (str) -> bool
  245. """Is path is a directory containing setup.py or pyproject.toml?
  246. """
  247. if not os.path.isdir(path):
  248. return False
  249. setup_py = os.path.join(path, 'setup.py')
  250. if os.path.isfile(setup_py):
  251. return True
  252. pyproject_toml = os.path.join(path, 'pyproject.toml')
  253. if os.path.isfile(pyproject_toml):
  254. return True
  255. return False
  256. def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
  257. """Yield pieces of data from a file-like object until EOF."""
  258. while True:
  259. chunk = file.read(size)
  260. if not chunk:
  261. break
  262. yield chunk
  263. def normalize_path(path, resolve_symlinks=True):
  264. # type: (str, bool) -> str
  265. """
  266. Convert a path to its canonical, case-normalized, absolute version.
  267. """
  268. path = expanduser(path)
  269. if resolve_symlinks:
  270. path = os.path.realpath(path)
  271. else:
  272. path = os.path.abspath(path)
  273. return os.path.normcase(path)
  274. def splitext(path):
  275. # type: (str) -> Tuple[str, str]
  276. """Like os.path.splitext, but take off .tar too"""
  277. base, ext = posixpath.splitext(path)
  278. if base.lower().endswith('.tar'):
  279. ext = base[-4:] + ext
  280. base = base[:-4]
  281. return base, ext
  282. def renames(old, new):
  283. # type: (str, str) -> None
  284. """Like os.renames(), but handles renaming across devices."""
  285. # Implementation borrowed from os.renames().
  286. head, tail = os.path.split(new)
  287. if head and tail and not os.path.exists(head):
  288. os.makedirs(head)
  289. shutil.move(old, new)
  290. head, tail = os.path.split(old)
  291. if head and tail:
  292. try:
  293. os.removedirs(head)
  294. except OSError:
  295. pass
  296. def is_local(path):
  297. # type: (str) -> bool
  298. """
  299. Return True if path is within sys.prefix, if we're running in a virtualenv.
  300. If we're not in a virtualenv, all paths are considered "local."
  301. Caution: this function assumes the head of path has been normalized
  302. with normalize_path.
  303. """
  304. if not running_under_virtualenv():
  305. return True
  306. return path.startswith(normalize_path(sys.prefix))
  307. def dist_is_local(dist):
  308. # type: (Distribution) -> bool
  309. """
  310. Return True if given Distribution object is installed locally
  311. (i.e. within current virtualenv).
  312. Always True if we're not in a virtualenv.
  313. """
  314. return is_local(dist_location(dist))
  315. def dist_in_usersite(dist):
  316. # type: (Distribution) -> bool
  317. """
  318. Return True if given Distribution is installed in user site.
  319. """
  320. return dist_location(dist).startswith(normalize_path(user_site))
  321. def dist_in_site_packages(dist):
  322. # type: (Distribution) -> bool
  323. """
  324. Return True if given Distribution is installed in
  325. sysconfig.get_python_lib().
  326. """
  327. return dist_location(dist).startswith(normalize_path(site_packages))
  328. def dist_is_editable(dist):
  329. # type: (Distribution) -> bool
  330. """
  331. Return True if given Distribution is an editable install.
  332. """
  333. for path_item in sys.path:
  334. egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
  335. if os.path.isfile(egg_link):
  336. return True
  337. return False
  338. def get_installed_distributions(
  339. local_only=True, # type: bool
  340. skip=stdlib_pkgs, # type: Container[str]
  341. include_editables=True, # type: bool
  342. editables_only=False, # type: bool
  343. user_only=False, # type: bool
  344. paths=None # type: Optional[List[str]]
  345. ):
  346. # type: (...) -> List[Distribution]
  347. """
  348. Return a list of installed Distribution objects.
  349. If ``local_only`` is True (default), only return installations
  350. local to the current virtualenv, if in a virtualenv.
  351. ``skip`` argument is an iterable of lower-case project names to
  352. ignore; defaults to stdlib_pkgs
  353. If ``include_editables`` is False, don't report editables.
  354. If ``editables_only`` is True , only report editables.
  355. If ``user_only`` is True , only report installations in the user
  356. site directory.
  357. If ``paths`` is set, only report the distributions present at the
  358. specified list of locations.
  359. """
  360. if paths:
  361. working_set = pkg_resources.WorkingSet(paths)
  362. else:
  363. working_set = pkg_resources.working_set
  364. if local_only:
  365. local_test = dist_is_local
  366. else:
  367. def local_test(d):
  368. return True
  369. if include_editables:
  370. def editable_test(d):
  371. return True
  372. else:
  373. def editable_test(d):
  374. return not dist_is_editable(d)
  375. if editables_only:
  376. def editables_only_test(d):
  377. return dist_is_editable(d)
  378. else:
  379. def editables_only_test(d):
  380. return True
  381. if user_only:
  382. user_test = dist_in_usersite
  383. else:
  384. def user_test(d):
  385. return True
  386. return [d for d in working_set
  387. if local_test(d) and
  388. d.key not in skip and
  389. editable_test(d) and
  390. editables_only_test(d) and
  391. user_test(d)
  392. ]
  393. def _search_distribution(req_name):
  394. # type: (str) -> Optional[Distribution]
  395. """Find a distribution matching the ``req_name`` in the environment.
  396. This searches from *all* distributions available in the environment, to
  397. match the behavior of ``pkg_resources.get_distribution()``.
  398. """
  399. # Canonicalize the name before searching in the list of
  400. # installed distributions and also while creating the package
  401. # dictionary to get the Distribution object
  402. req_name = canonicalize_name(req_name)
  403. packages = get_installed_distributions(
  404. local_only=False,
  405. skip=(),
  406. include_editables=True,
  407. editables_only=False,
  408. user_only=False,
  409. paths=None,
  410. )
  411. pkg_dict = {canonicalize_name(p.key): p for p in packages}
  412. return pkg_dict.get(req_name)
  413. def get_distribution(req_name):
  414. # type: (str) -> Optional[Distribution]
  415. """Given a requirement name, return the installed Distribution object.
  416. This searches from *all* distributions available in the environment, to
  417. match the behavior of ``pkg_resources.get_distribution()``.
  418. """
  419. # Search the distribution by looking through the working set
  420. dist = _search_distribution(req_name)
  421. # If distribution could not be found, call working_set.require
  422. # to update the working set, and try to find the distribution
  423. # again.
  424. # This might happen for e.g. when you install a package
  425. # twice, once using setup.py develop and again using setup.py install.
  426. # Now when run pip uninstall twice, the package gets removed
  427. # from the working set in the first uninstall, so we have to populate
  428. # the working set again so that pip knows about it and the packages
  429. # gets picked up and is successfully uninstalled the second time too.
  430. if not dist:
  431. try:
  432. pkg_resources.working_set.require(req_name)
  433. except pkg_resources.DistributionNotFound:
  434. return None
  435. return _search_distribution(req_name)
  436. def egg_link_path(dist):
  437. # type: (Distribution) -> Optional[str]
  438. """
  439. Return the path for the .egg-link file if it exists, otherwise, None.
  440. There's 3 scenarios:
  441. 1) not in a virtualenv
  442. try to find in site.USER_SITE, then site_packages
  443. 2) in a no-global virtualenv
  444. try to find in site_packages
  445. 3) in a yes-global virtualenv
  446. try to find in site_packages, then site.USER_SITE
  447. (don't look in global location)
  448. For #1 and #3, there could be odd cases, where there's an egg-link in 2
  449. locations.
  450. This method will just return the first one found.
  451. """
  452. sites = []
  453. if running_under_virtualenv():
  454. sites.append(site_packages)
  455. if not virtualenv_no_global() and user_site:
  456. sites.append(user_site)
  457. else:
  458. if user_site:
  459. sites.append(user_site)
  460. sites.append(site_packages)
  461. for site in sites:
  462. egglink = os.path.join(site, dist.project_name) + '.egg-link'
  463. if os.path.isfile(egglink):
  464. return egglink
  465. return None
  466. def dist_location(dist):
  467. # type: (Distribution) -> str
  468. """
  469. Get the site-packages location of this distribution. Generally
  470. this is dist.location, except in the case of develop-installed
  471. packages, where dist.location is the source code location, and we
  472. want to know where the egg-link file is.
  473. The returned location is normalized (in particular, with symlinks removed).
  474. """
  475. egg_link = egg_link_path(dist)
  476. if egg_link:
  477. return normalize_path(egg_link)
  478. return normalize_path(dist.location)
  479. def write_output(msg, *args):
  480. # type: (Any, Any) -> None
  481. logger.info(msg, *args)
  482. class FakeFile(object):
  483. """Wrap a list of lines in an object with readline() to make
  484. ConfigParser happy."""
  485. def __init__(self, lines):
  486. self._gen = iter(lines)
  487. def readline(self):
  488. try:
  489. return next(self._gen)
  490. except StopIteration:
  491. return ''
  492. def __iter__(self):
  493. return self._gen
  494. class StreamWrapper(StringIO):
  495. @classmethod
  496. def from_stream(cls, orig_stream):
  497. cls.orig_stream = orig_stream
  498. return cls()
  499. # compileall.compile_dir() needs stdout.encoding to print to stdout
  500. @property
  501. def encoding(self):
  502. return self.orig_stream.encoding
  503. @contextlib.contextmanager
  504. def captured_output(stream_name):
  505. """Return a context manager used by captured_stdout/stdin/stderr
  506. that temporarily replaces the sys stream *stream_name* with a StringIO.
  507. Taken from Lib/support/__init__.py in the CPython repo.
  508. """
  509. orig_stdout = getattr(sys, stream_name)
  510. setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
  511. try:
  512. yield getattr(sys, stream_name)
  513. finally:
  514. setattr(sys, stream_name, orig_stdout)
  515. def captured_stdout():
  516. """Capture the output of sys.stdout:
  517. with captured_stdout() as stdout:
  518. print('hello')
  519. self.assertEqual(stdout.getvalue(), 'hello\n')
  520. Taken from Lib/support/__init__.py in the CPython repo.
  521. """
  522. return captured_output('stdout')
  523. def captured_stderr():
  524. """
  525. See captured_stdout().
  526. """
  527. return captured_output('stderr')
  528. def get_installed_version(dist_name, working_set=None):
  529. """Get the installed version of dist_name avoiding pkg_resources cache"""
  530. # Create a requirement that we'll look for inside of setuptools.
  531. req = pkg_resources.Requirement.parse(dist_name)
  532. if working_set is None:
  533. # We want to avoid having this cached, so we need to construct a new
  534. # working set each time.
  535. working_set = pkg_resources.WorkingSet()
  536. # Get the installed distribution from our working set
  537. dist = working_set.find(req)
  538. # Check to see if we got an installed distribution or not, if we did
  539. # we want to return it's version.
  540. return dist.version if dist else None
  541. def consume(iterator):
  542. """Consume an iterable at C speed."""
  543. deque(iterator, maxlen=0)
  544. # Simulates an enum
  545. def enum(*sequential, **named):
  546. enums = dict(zip(sequential, range(len(sequential))), **named)
  547. reverse = {value: key for key, value in enums.items()}
  548. enums['reverse_mapping'] = reverse
  549. return type('Enum', (), enums)
  550. def build_netloc(host, port):
  551. # type: (str, Optional[int]) -> str
  552. """
  553. Build a netloc from a host-port pair
  554. """
  555. if port is None:
  556. return host
  557. if ':' in host:
  558. # Only wrap host with square brackets when it is IPv6
  559. host = '[{}]'.format(host)
  560. return '{}:{}'.format(host, port)
  561. def build_url_from_netloc(netloc, scheme='https'):
  562. # type: (str, str) -> str
  563. """
  564. Build a full URL from a netloc.
  565. """
  566. if netloc.count(':') >= 2 and '@' not in netloc and '[' not in netloc:
  567. # It must be a bare IPv6 address, so wrap it with brackets.
  568. netloc = '[{}]'.format(netloc)
  569. return '{}://{}'.format(scheme, netloc)
  570. def parse_netloc(netloc):
  571. # type: (str) -> Tuple[str, Optional[int]]
  572. """
  573. Return the host-port pair from a netloc.
  574. """
  575. url = build_url_from_netloc(netloc)
  576. parsed = urllib_parse.urlparse(url)
  577. return parsed.hostname, parsed.port
  578. def split_auth_from_netloc(netloc):
  579. """
  580. Parse out and remove the auth information from a netloc.
  581. Returns: (netloc, (username, password)).
  582. """
  583. if '@' not in netloc:
  584. return netloc, (None, None)
  585. # Split from the right because that's how urllib.parse.urlsplit()
  586. # behaves if more than one @ is present (which can be checked using
  587. # the password attribute of urlsplit()'s return value).
  588. auth, netloc = netloc.rsplit('@', 1)
  589. if ':' in auth:
  590. # Split from the left because that's how urllib.parse.urlsplit()
  591. # behaves if more than one : is present (which again can be checked
  592. # using the password attribute of the return value)
  593. user_pass = auth.split(':', 1)
  594. else:
  595. user_pass = auth, None
  596. user_pass = tuple(
  597. None if x is None else urllib_unquote(x) for x in user_pass
  598. )
  599. return netloc, user_pass
  600. def redact_netloc(netloc):
  601. # type: (str) -> str
  602. """
  603. Replace the sensitive data in a netloc with "****", if it exists.
  604. For example:
  605. - "user:pass@example.com" returns "user:****@example.com"
  606. - "accesstoken@example.com" returns "****@example.com"
  607. """
  608. netloc, (user, password) = split_auth_from_netloc(netloc)
  609. if user is None:
  610. return netloc
  611. if password is None:
  612. user = '****'
  613. password = ''
  614. else:
  615. user = urllib_parse.quote(user)
  616. password = ':****'
  617. return '{user}{password}@{netloc}'.format(user=user,
  618. password=password,
  619. netloc=netloc)
  620. def _transform_url(url, transform_netloc):
  621. """Transform and replace netloc in a url.
  622. transform_netloc is a function taking the netloc and returning a
  623. tuple. The first element of this tuple is the new netloc. The
  624. entire tuple is returned.
  625. Returns a tuple containing the transformed url as item 0 and the
  626. original tuple returned by transform_netloc as item 1.
  627. """
  628. purl = urllib_parse.urlsplit(url)
  629. netloc_tuple = transform_netloc(purl.netloc)
  630. # stripped url
  631. url_pieces = (
  632. purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment
  633. )
  634. surl = urllib_parse.urlunsplit(url_pieces)
  635. return surl, netloc_tuple
  636. def _get_netloc(netloc):
  637. return split_auth_from_netloc(netloc)
  638. def _redact_netloc(netloc):
  639. return (redact_netloc(netloc),)
  640. def split_auth_netloc_from_url(url):
  641. # type: (str) -> Tuple[str, str, Tuple[str, str]]
  642. """
  643. Parse a url into separate netloc, auth, and url with no auth.
  644. Returns: (url_without_auth, netloc, (username, password))
  645. """
  646. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  647. return url_without_auth, netloc, auth
  648. def remove_auth_from_url(url):
  649. # type: (str) -> str
  650. """Return a copy of url with 'username:password@' removed."""
  651. # username/pass params are passed to subversion through flags
  652. # and are not recognized in the url.
  653. return _transform_url(url, _get_netloc)[0]
  654. def redact_auth_from_url(url):
  655. # type: (str) -> str
  656. """Replace the password in a given url with ****."""
  657. return _transform_url(url, _redact_netloc)[0]
  658. class HiddenText(object):
  659. def __init__(
  660. self,
  661. secret, # type: str
  662. redacted, # type: str
  663. ):
  664. # type: (...) -> None
  665. self.secret = secret
  666. self.redacted = redacted
  667. def __repr__(self):
  668. # type: (...) -> str
  669. return '<HiddenText {!r}>'.format(str(self))
  670. def __str__(self):
  671. # type: (...) -> str
  672. return self.redacted
  673. # This is useful for testing.
  674. def __eq__(self, other):
  675. # type: (Any) -> bool
  676. if type(self) != type(other):
  677. return False
  678. # The string being used for redaction doesn't also have to match,
  679. # just the raw, original string.
  680. return (self.secret == other.secret)
  681. # We need to provide an explicit __ne__ implementation for Python 2.
  682. # TODO: remove this when we drop PY2 support.
  683. def __ne__(self, other):
  684. # type: (Any) -> bool
  685. return not self == other
  686. def hide_value(value):
  687. # type: (str) -> HiddenText
  688. return HiddenText(value, redacted='****')
  689. def hide_url(url):
  690. # type: (str) -> HiddenText
  691. redacted = redact_auth_from_url(url)
  692. return HiddenText(url, redacted=redacted)
  693. def protect_pip_from_modification_on_windows(modifying_pip):
  694. # type: (bool) -> None
  695. """Protection of pip.exe from modification on Windows
  696. On Windows, any operation modifying pip should be run as:
  697. python -m pip ...
  698. """
  699. pip_names = [
  700. "pip.exe",
  701. "pip{}.exe".format(sys.version_info[0]),
  702. "pip{}.{}.exe".format(*sys.version_info[:2])
  703. ]
  704. # See https://github.com/pypa/pip/issues/1299 for more discussion
  705. should_show_use_python_msg = (
  706. modifying_pip and
  707. WINDOWS and
  708. os.path.basename(sys.argv[0]) in pip_names
  709. )
  710. if should_show_use_python_msg:
  711. new_command = [
  712. sys.executable, "-m", "pip"
  713. ] + sys.argv[1:]
  714. raise CommandError(
  715. 'To modify pip, please run the following command:\n{}'
  716. .format(" ".join(new_command))
  717. )
  718. def is_console_interactive():
  719. # type: () -> bool
  720. """Is this console interactive?
  721. """
  722. return sys.stdin is not None and sys.stdin.isatty()
  723. def hash_file(path, blocksize=1 << 20):
  724. # type: (Text, int) -> Tuple[Any, int]
  725. """Return (hash, length) for path using hashlib.sha256()
  726. """
  727. h = hashlib.sha256()
  728. length = 0
  729. with open(path, 'rb') as f:
  730. for block in read_chunks(f, size=blocksize):
  731. length += len(block)
  732. h.update(block)
  733. return h, length
  734. def is_wheel_installed():
  735. """
  736. Return whether the wheel package is installed.
  737. """
  738. try:
  739. import wheel # noqa: F401
  740. except ImportError:
  741. return False
  742. return True
  743. def pairwise(iterable):
  744. # type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]
  745. """
  746. Return paired elements.
  747. For example:
  748. s -> (s0, s1), (s2, s3), (s4, s5), ...
  749. """
  750. iterable = iter(iterable)
  751. return zip_longest(iterable, iterable)
  752. def partition(
  753. pred, # type: Callable[[T], bool]
  754. iterable, # type: Iterable[T]
  755. ):
  756. # type: (...) -> Tuple[Iterable[T], Iterable[T]]
  757. """
  758. Use a predicate to partition entries into false entries and true entries,
  759. like
  760. partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
  761. """
  762. t1, t2 = tee(iterable)
  763. return filterfalse(pred, t1), filter(pred, t2)