misc.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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 io
  9. import logging
  10. import os
  11. import posixpath
  12. import shutil
  13. import stat
  14. import sys
  15. from collections import deque
  16. from pip._vendor import pkg_resources
  17. # NOTE: retrying is not annotated in typeshed as on 2017-07-17, which is
  18. # why we ignore the type on this import.
  19. from pip._vendor.retrying import retry # type: ignore
  20. from pip._vendor.six import PY2, text_type
  21. from pip._vendor.six.moves import input
  22. from pip._vendor.six.moves.urllib import parse as urllib_parse
  23. from pip._vendor.six.moves.urllib.parse import unquote as urllib_unquote
  24. from pip import __version__
  25. from pip._internal.exceptions import CommandError
  26. from pip._internal.locations import (
  27. get_major_minor_version,
  28. site_packages,
  29. user_site,
  30. )
  31. from pip._internal.utils.compat import (
  32. WINDOWS,
  33. expanduser,
  34. stdlib_pkgs,
  35. str_to_display,
  36. )
  37. from pip._internal.utils.marker_files import write_delete_marker_file
  38. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  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, List, Optional, Text,
  50. Tuple, Union, cast,
  51. )
  52. from pip._vendor.pkg_resources import Distribution
  53. VersionInfo = Tuple[int, int, int]
  54. else:
  55. # typing's cast() is needed at runtime, but we don't want to import typing.
  56. # Thus, we use a dummy no-op version, which we tell mypy to ignore.
  57. def cast(type_, value): # type: ignore
  58. return value
  59. __all__ = ['rmtree', 'display_path', 'backup_dir',
  60. 'ask', 'splitext',
  61. 'format_size', 'is_installable_dir',
  62. 'normalize_path',
  63. 'renames', 'get_prog',
  64. 'captured_stdout', 'ensure_dir',
  65. 'get_installed_version', 'remove_auth_from_url']
  66. logger = logging.getLogger(__name__)
  67. def get_pip_version():
  68. # type: () -> str
  69. pip_pkg_dir = os.path.join(os.path.dirname(__file__), "..", "..")
  70. pip_pkg_dir = os.path.abspath(pip_pkg_dir)
  71. return (
  72. 'pip {} from {} (python {})'.format(
  73. __version__, pip_pkg_dir, get_major_minor_version(),
  74. )
  75. )
  76. def normalize_version_info(py_version_info):
  77. # type: (Tuple[int, ...]) -> Tuple[int, int, int]
  78. """
  79. Convert a tuple of ints representing a Python version to one of length
  80. three.
  81. :param py_version_info: a tuple of ints representing a Python version,
  82. or None to specify no version. The tuple can have any length.
  83. :return: a tuple of length three if `py_version_info` is non-None.
  84. Otherwise, return `py_version_info` unchanged (i.e. None).
  85. """
  86. if len(py_version_info) < 3:
  87. py_version_info += (3 - len(py_version_info)) * (0,)
  88. elif len(py_version_info) > 3:
  89. py_version_info = py_version_info[:3]
  90. return cast('VersionInfo', py_version_info)
  91. def ensure_dir(path):
  92. # type: (AnyStr) -> None
  93. """os.path.makedirs without EEXIST."""
  94. try:
  95. os.makedirs(path)
  96. except OSError as e:
  97. if e.errno != errno.EEXIST:
  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 "%s -m pip" % 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: (str, 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: %s' %
  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. '%s' % (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 '%.1fMB' % (bytes / 1000.0 / 1000)
  226. elif bytes > 10 * 1000:
  227. return '%ikB' % (bytes / 1000)
  228. elif bytes > 1000:
  229. return '%.1fkB' % (bytes / 1000.0)
  230. else:
  231. return '%ibytes' % bytes
  232. def is_installable_dir(path):
  233. # type: (str) -> bool
  234. """Is path is a directory containing setup.py or pyproject.toml?
  235. """
  236. if not os.path.isdir(path):
  237. return False
  238. setup_py = os.path.join(path, 'setup.py')
  239. if os.path.isfile(setup_py):
  240. return True
  241. pyproject_toml = os.path.join(path, 'pyproject.toml')
  242. if os.path.isfile(pyproject_toml):
  243. return True
  244. return False
  245. def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
  246. """Yield pieces of data from a file-like object until EOF."""
  247. while True:
  248. chunk = file.read(size)
  249. if not chunk:
  250. break
  251. yield chunk
  252. def normalize_path(path, resolve_symlinks=True):
  253. # type: (str, bool) -> str
  254. """
  255. Convert a path to its canonical, case-normalized, absolute version.
  256. """
  257. path = expanduser(path)
  258. if resolve_symlinks:
  259. path = os.path.realpath(path)
  260. else:
  261. path = os.path.abspath(path)
  262. return os.path.normcase(path)
  263. def splitext(path):
  264. # type: (str) -> Tuple[str, str]
  265. """Like os.path.splitext, but take off .tar too"""
  266. base, ext = posixpath.splitext(path)
  267. if base.lower().endswith('.tar'):
  268. ext = base[-4:] + ext
  269. base = base[:-4]
  270. return base, ext
  271. def renames(old, new):
  272. # type: (str, str) -> None
  273. """Like os.renames(), but handles renaming across devices."""
  274. # Implementation borrowed from os.renames().
  275. head, tail = os.path.split(new)
  276. if head and tail and not os.path.exists(head):
  277. os.makedirs(head)
  278. shutil.move(old, new)
  279. head, tail = os.path.split(old)
  280. if head and tail:
  281. try:
  282. os.removedirs(head)
  283. except OSError:
  284. pass
  285. def is_local(path):
  286. # type: (str) -> bool
  287. """
  288. Return True if path is within sys.prefix, if we're running in a virtualenv.
  289. If we're not in a virtualenv, all paths are considered "local."
  290. Caution: this function assumes the head of path has been normalized
  291. with normalize_path.
  292. """
  293. if not running_under_virtualenv():
  294. return True
  295. return path.startswith(normalize_path(sys.prefix))
  296. def dist_is_local(dist):
  297. # type: (Distribution) -> bool
  298. """
  299. Return True if given Distribution object is installed locally
  300. (i.e. within current virtualenv).
  301. Always True if we're not in a virtualenv.
  302. """
  303. return is_local(dist_location(dist))
  304. def dist_in_usersite(dist):
  305. # type: (Distribution) -> bool
  306. """
  307. Return True if given Distribution is installed in user site.
  308. """
  309. return dist_location(dist).startswith(normalize_path(user_site))
  310. def dist_in_site_packages(dist):
  311. # type: (Distribution) -> bool
  312. """
  313. Return True if given Distribution is installed in
  314. sysconfig.get_python_lib().
  315. """
  316. return dist_location(dist).startswith(normalize_path(site_packages))
  317. def dist_is_editable(dist):
  318. # type: (Distribution) -> bool
  319. """
  320. Return True if given Distribution is an editable install.
  321. """
  322. for path_item in sys.path:
  323. egg_link = os.path.join(path_item, dist.project_name + '.egg-link')
  324. if os.path.isfile(egg_link):
  325. return True
  326. return False
  327. def get_installed_distributions(
  328. local_only=True, # type: bool
  329. skip=stdlib_pkgs, # type: Container[str]
  330. include_editables=True, # type: bool
  331. editables_only=False, # type: bool
  332. user_only=False, # type: bool
  333. paths=None # type: Optional[List[str]]
  334. ):
  335. # type: (...) -> List[Distribution]
  336. """
  337. Return a list of installed Distribution objects.
  338. If ``local_only`` is True (default), only return installations
  339. local to the current virtualenv, if in a virtualenv.
  340. ``skip`` argument is an iterable of lower-case project names to
  341. ignore; defaults to stdlib_pkgs
  342. If ``include_editables`` is False, don't report editables.
  343. If ``editables_only`` is True , only report editables.
  344. If ``user_only`` is True , only report installations in the user
  345. site directory.
  346. If ``paths`` is set, only report the distributions present at the
  347. specified list of locations.
  348. """
  349. if paths:
  350. working_set = pkg_resources.WorkingSet(paths)
  351. else:
  352. working_set = pkg_resources.working_set
  353. if local_only:
  354. local_test = dist_is_local
  355. else:
  356. def local_test(d):
  357. return True
  358. if include_editables:
  359. def editable_test(d):
  360. return True
  361. else:
  362. def editable_test(d):
  363. return not dist_is_editable(d)
  364. if editables_only:
  365. def editables_only_test(d):
  366. return dist_is_editable(d)
  367. else:
  368. def editables_only_test(d):
  369. return True
  370. if user_only:
  371. user_test = dist_in_usersite
  372. else:
  373. def user_test(d):
  374. return True
  375. # because of pkg_resources vendoring, mypy cannot find stub in typeshed
  376. return [d for d in working_set # type: ignore
  377. if local_test(d) and
  378. d.key not in skip and
  379. editable_test(d) and
  380. editables_only_test(d) and
  381. user_test(d)
  382. ]
  383. def egg_link_path(dist):
  384. # type: (Distribution) -> Optional[str]
  385. """
  386. Return the path for the .egg-link file if it exists, otherwise, None.
  387. There's 3 scenarios:
  388. 1) not in a virtualenv
  389. try to find in site.USER_SITE, then site_packages
  390. 2) in a no-global virtualenv
  391. try to find in site_packages
  392. 3) in a yes-global virtualenv
  393. try to find in site_packages, then site.USER_SITE
  394. (don't look in global location)
  395. For #1 and #3, there could be odd cases, where there's an egg-link in 2
  396. locations.
  397. This method will just return the first one found.
  398. """
  399. sites = []
  400. if running_under_virtualenv():
  401. sites.append(site_packages)
  402. if not virtualenv_no_global() and user_site:
  403. sites.append(user_site)
  404. else:
  405. if user_site:
  406. sites.append(user_site)
  407. sites.append(site_packages)
  408. for site in sites:
  409. egglink = os.path.join(site, dist.project_name) + '.egg-link'
  410. if os.path.isfile(egglink):
  411. return egglink
  412. return None
  413. def dist_location(dist):
  414. # type: (Distribution) -> str
  415. """
  416. Get the site-packages location of this distribution. Generally
  417. this is dist.location, except in the case of develop-installed
  418. packages, where dist.location is the source code location, and we
  419. want to know where the egg-link file is.
  420. The returned location is normalized (in particular, with symlinks removed).
  421. """
  422. egg_link = egg_link_path(dist)
  423. if egg_link:
  424. return normalize_path(egg_link)
  425. return normalize_path(dist.location)
  426. def write_output(msg, *args):
  427. # type: (str, str) -> None
  428. logger.info(msg, *args)
  429. def _make_build_dir(build_dir):
  430. os.makedirs(build_dir)
  431. write_delete_marker_file(build_dir)
  432. class FakeFile(object):
  433. """Wrap a list of lines in an object with readline() to make
  434. ConfigParser happy."""
  435. def __init__(self, lines):
  436. self._gen = (l for l in lines)
  437. def readline(self):
  438. try:
  439. try:
  440. return next(self._gen)
  441. except NameError:
  442. return self._gen.next()
  443. except StopIteration:
  444. return ''
  445. def __iter__(self):
  446. return self._gen
  447. class StreamWrapper(StringIO):
  448. @classmethod
  449. def from_stream(cls, orig_stream):
  450. cls.orig_stream = orig_stream
  451. return cls()
  452. # compileall.compile_dir() needs stdout.encoding to print to stdout
  453. @property
  454. def encoding(self):
  455. return self.orig_stream.encoding
  456. @contextlib.contextmanager
  457. def captured_output(stream_name):
  458. """Return a context manager used by captured_stdout/stdin/stderr
  459. that temporarily replaces the sys stream *stream_name* with a StringIO.
  460. Taken from Lib/support/__init__.py in the CPython repo.
  461. """
  462. orig_stdout = getattr(sys, stream_name)
  463. setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
  464. try:
  465. yield getattr(sys, stream_name)
  466. finally:
  467. setattr(sys, stream_name, orig_stdout)
  468. def captured_stdout():
  469. """Capture the output of sys.stdout:
  470. with captured_stdout() as stdout:
  471. print('hello')
  472. self.assertEqual(stdout.getvalue(), 'hello\n')
  473. Taken from Lib/support/__init__.py in the CPython repo.
  474. """
  475. return captured_output('stdout')
  476. def captured_stderr():
  477. """
  478. See captured_stdout().
  479. """
  480. return captured_output('stderr')
  481. class cached_property(object):
  482. """A property that is only computed once per instance and then replaces
  483. itself with an ordinary attribute. Deleting the attribute resets the
  484. property.
  485. Source: https://github.com/bottlepy/bottle/blob/0.11.5/bottle.py#L175
  486. """
  487. def __init__(self, func):
  488. self.__doc__ = getattr(func, '__doc__')
  489. self.func = func
  490. def __get__(self, obj, cls):
  491. if obj is None:
  492. # We're being accessed from the class itself, not from an object
  493. return self
  494. value = obj.__dict__[self.func.__name__] = self.func(obj)
  495. return value
  496. def get_installed_version(dist_name, working_set=None):
  497. """Get the installed version of dist_name avoiding pkg_resources cache"""
  498. # Create a requirement that we'll look for inside of setuptools.
  499. req = pkg_resources.Requirement.parse(dist_name)
  500. if working_set is None:
  501. # We want to avoid having this cached, so we need to construct a new
  502. # working set each time.
  503. working_set = pkg_resources.WorkingSet()
  504. # Get the installed distribution from our working set
  505. dist = working_set.find(req)
  506. # Check to see if we got an installed distribution or not, if we did
  507. # we want to return it's version.
  508. return dist.version if dist else None
  509. def consume(iterator):
  510. """Consume an iterable at C speed."""
  511. deque(iterator, maxlen=0)
  512. # Simulates an enum
  513. def enum(*sequential, **named):
  514. enums = dict(zip(sequential, range(len(sequential))), **named)
  515. reverse = {value: key for key, value in enums.items()}
  516. enums['reverse_mapping'] = reverse
  517. return type('Enum', (), enums)
  518. def build_netloc(host, port):
  519. # type: (str, Optional[int]) -> str
  520. """
  521. Build a netloc from a host-port pair
  522. """
  523. if port is None:
  524. return host
  525. if ':' in host:
  526. # Only wrap host with square brackets when it is IPv6
  527. host = '[{}]'.format(host)
  528. return '{}:{}'.format(host, port)
  529. def build_url_from_netloc(netloc, scheme='https'):
  530. # type: (str, str) -> str
  531. """
  532. Build a full URL from a netloc.
  533. """
  534. if netloc.count(':') >= 2 and '@' not in netloc and '[' not in netloc:
  535. # It must be a bare IPv6 address, so wrap it with brackets.
  536. netloc = '[{}]'.format(netloc)
  537. return '{}://{}'.format(scheme, netloc)
  538. def parse_netloc(netloc):
  539. # type: (str) -> Tuple[str, Optional[int]]
  540. """
  541. Return the host-port pair from a netloc.
  542. """
  543. url = build_url_from_netloc(netloc)
  544. parsed = urllib_parse.urlparse(url)
  545. return parsed.hostname, parsed.port
  546. def split_auth_from_netloc(netloc):
  547. """
  548. Parse out and remove the auth information from a netloc.
  549. Returns: (netloc, (username, password)).
  550. """
  551. if '@' not in netloc:
  552. return netloc, (None, None)
  553. # Split from the right because that's how urllib.parse.urlsplit()
  554. # behaves if more than one @ is present (which can be checked using
  555. # the password attribute of urlsplit()'s return value).
  556. auth, netloc = netloc.rsplit('@', 1)
  557. if ':' in auth:
  558. # Split from the left because that's how urllib.parse.urlsplit()
  559. # behaves if more than one : is present (which again can be checked
  560. # using the password attribute of the return value)
  561. user_pass = auth.split(':', 1)
  562. else:
  563. user_pass = auth, None
  564. user_pass = tuple(
  565. None if x is None else urllib_unquote(x) for x in user_pass
  566. )
  567. return netloc, user_pass
  568. def redact_netloc(netloc):
  569. # type: (str) -> str
  570. """
  571. Replace the sensitive data in a netloc with "****", if it exists.
  572. For example:
  573. - "user:pass@example.com" returns "user:****@example.com"
  574. - "accesstoken@example.com" returns "****@example.com"
  575. """
  576. netloc, (user, password) = split_auth_from_netloc(netloc)
  577. if user is None:
  578. return netloc
  579. if password is None:
  580. user = '****'
  581. password = ''
  582. else:
  583. user = urllib_parse.quote(user)
  584. password = ':****'
  585. return '{user}{password}@{netloc}'.format(user=user,
  586. password=password,
  587. netloc=netloc)
  588. def _transform_url(url, transform_netloc):
  589. """Transform and replace netloc in a url.
  590. transform_netloc is a function taking the netloc and returning a
  591. tuple. The first element of this tuple is the new netloc. The
  592. entire tuple is returned.
  593. Returns a tuple containing the transformed url as item 0 and the
  594. original tuple returned by transform_netloc as item 1.
  595. """
  596. purl = urllib_parse.urlsplit(url)
  597. netloc_tuple = transform_netloc(purl.netloc)
  598. # stripped url
  599. url_pieces = (
  600. purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment
  601. )
  602. surl = urllib_parse.urlunsplit(url_pieces)
  603. return surl, netloc_tuple
  604. def _get_netloc(netloc):
  605. return split_auth_from_netloc(netloc)
  606. def _redact_netloc(netloc):
  607. return (redact_netloc(netloc),)
  608. def split_auth_netloc_from_url(url):
  609. # type: (str) -> Tuple[str, str, Tuple[str, str]]
  610. """
  611. Parse a url into separate netloc, auth, and url with no auth.
  612. Returns: (url_without_auth, netloc, (username, password))
  613. """
  614. url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
  615. return url_without_auth, netloc, auth
  616. def remove_auth_from_url(url):
  617. # type: (str) -> str
  618. """Return a copy of url with 'username:password@' removed."""
  619. # username/pass params are passed to subversion through flags
  620. # and are not recognized in the url.
  621. return _transform_url(url, _get_netloc)[0]
  622. def redact_auth_from_url(url):
  623. # type: (str) -> str
  624. """Replace the password in a given url with ****."""
  625. return _transform_url(url, _redact_netloc)[0]
  626. class HiddenText(object):
  627. def __init__(
  628. self,
  629. secret, # type: str
  630. redacted, # type: str
  631. ):
  632. # type: (...) -> None
  633. self.secret = secret
  634. self.redacted = redacted
  635. def __repr__(self):
  636. # type: (...) -> str
  637. return '<HiddenText {!r}>'.format(str(self))
  638. def __str__(self):
  639. # type: (...) -> str
  640. return self.redacted
  641. # This is useful for testing.
  642. def __eq__(self, other):
  643. # type: (Any) -> bool
  644. if type(self) != type(other):
  645. return False
  646. # The string being used for redaction doesn't also have to match,
  647. # just the raw, original string.
  648. return (self.secret == other.secret)
  649. # We need to provide an explicit __ne__ implementation for Python 2.
  650. # TODO: remove this when we drop PY2 support.
  651. def __ne__(self, other):
  652. # type: (Any) -> bool
  653. return not self == other
  654. def hide_value(value):
  655. # type: (str) -> HiddenText
  656. return HiddenText(value, redacted='****')
  657. def hide_url(url):
  658. # type: (str) -> HiddenText
  659. redacted = redact_auth_from_url(url)
  660. return HiddenText(url, redacted=redacted)
  661. def protect_pip_from_modification_on_windows(modifying_pip):
  662. # type: (bool) -> None
  663. """Protection of pip.exe from modification on Windows
  664. On Windows, any operation modifying pip should be run as:
  665. python -m pip ...
  666. """
  667. pip_names = set()
  668. for ext in ('', '.exe'):
  669. pip_names.add('pip{ext}'.format(ext=ext))
  670. pip_names.add('pip{}{ext}'.format(sys.version_info[0], ext=ext))
  671. pip_names.add('pip{}.{}{ext}'.format(*sys.version_info[:2], ext=ext))
  672. # See https://github.com/pypa/pip/issues/1299 for more discussion
  673. should_show_use_python_msg = (
  674. modifying_pip and
  675. WINDOWS and
  676. os.path.basename(sys.argv[0]) in pip_names
  677. )
  678. if should_show_use_python_msg:
  679. new_command = [
  680. sys.executable, "-m", "pip"
  681. ] + sys.argv[1:]
  682. raise CommandError(
  683. 'To modify pip, please run the following command:\n{}'
  684. .format(" ".join(new_command))
  685. )
  686. def is_console_interactive():
  687. # type: () -> bool
  688. """Is this console interactive?
  689. """
  690. return sys.stdin is not None and sys.stdin.isatty()