misc.py 26 KB

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