versioncontrol.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. """Handles all VCS (version control) support"""
  2. from __future__ import absolute_import
  3. import errno
  4. import logging
  5. import os
  6. import shutil
  7. import sys
  8. from pip._vendor import pkg_resources
  9. from pip._vendor.six.moves.urllib import parse as urllib_parse
  10. from pip._internal.exceptions import BadCommand, InstallationError
  11. from pip._internal.utils.compat import samefile
  12. from pip._internal.utils.misc import (
  13. ask_path_exists,
  14. backup_dir,
  15. display_path,
  16. hide_url,
  17. hide_value,
  18. rmtree,
  19. )
  20. from pip._internal.utils.subprocess import call_subprocess, make_command
  21. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  22. from pip._internal.utils.urls import get_url_scheme
  23. if MYPY_CHECK_RUNNING:
  24. from typing import (
  25. Any, Dict, Iterable, Iterator, List, Mapping, Optional, Text, Tuple,
  26. Type, Union
  27. )
  28. from pip._internal.cli.spinners import SpinnerInterface
  29. from pip._internal.utils.misc import HiddenText
  30. from pip._internal.utils.subprocess import CommandArgs
  31. AuthInfo = Tuple[Optional[str], Optional[str]]
  32. __all__ = ['vcs']
  33. logger = logging.getLogger(__name__)
  34. def is_url(name):
  35. # type: (Union[str, Text]) -> bool
  36. """
  37. Return true if the name looks like a URL.
  38. """
  39. scheme = get_url_scheme(name)
  40. if scheme is None:
  41. return False
  42. return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes
  43. def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
  44. # type: (str, str, str, Optional[str]) -> str
  45. """
  46. Return the URL for a VCS requirement.
  47. Args:
  48. repo_url: the remote VCS url, with any needed VCS prefix (e.g. "git+").
  49. project_name: the (unescaped) project name.
  50. """
  51. egg_project_name = pkg_resources.to_filename(project_name)
  52. req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)
  53. if subdir:
  54. req += '&subdirectory={}'.format(subdir)
  55. return req
  56. def find_path_to_setup_from_repo_root(location, repo_root):
  57. # type: (str, str) -> Optional[str]
  58. """
  59. Find the path to `setup.py` by searching up the filesystem from `location`.
  60. Return the path to `setup.py` relative to `repo_root`.
  61. Return None if `setup.py` is in `repo_root` or cannot be found.
  62. """
  63. # find setup.py
  64. orig_location = location
  65. while not os.path.exists(os.path.join(location, 'setup.py')):
  66. last_location = location
  67. location = os.path.dirname(location)
  68. if location == last_location:
  69. # We've traversed up to the root of the filesystem without
  70. # finding setup.py
  71. logger.warning(
  72. "Could not find setup.py for directory %s (tried all "
  73. "parent directories)",
  74. orig_location,
  75. )
  76. return None
  77. if samefile(repo_root, location):
  78. return None
  79. return os.path.relpath(location, repo_root)
  80. class RemoteNotFoundError(Exception):
  81. pass
  82. class RevOptions(object):
  83. """
  84. Encapsulates a VCS-specific revision to install, along with any VCS
  85. install options.
  86. Instances of this class should be treated as if immutable.
  87. """
  88. def __init__(
  89. self,
  90. vc_class, # type: Type[VersionControl]
  91. rev=None, # type: Optional[str]
  92. extra_args=None, # type: Optional[CommandArgs]
  93. ):
  94. # type: (...) -> None
  95. """
  96. Args:
  97. vc_class: a VersionControl subclass.
  98. rev: the name of the revision to install.
  99. extra_args: a list of extra options.
  100. """
  101. if extra_args is None:
  102. extra_args = []
  103. self.extra_args = extra_args
  104. self.rev = rev
  105. self.vc_class = vc_class
  106. self.branch_name = None # type: Optional[str]
  107. def __repr__(self):
  108. # type: () -> str
  109. return '<RevOptions {}: rev={!r}>'.format(self.vc_class.name, self.rev)
  110. @property
  111. def arg_rev(self):
  112. # type: () -> Optional[str]
  113. if self.rev is None:
  114. return self.vc_class.default_arg_rev
  115. return self.rev
  116. def to_args(self):
  117. # type: () -> CommandArgs
  118. """
  119. Return the VCS-specific command arguments.
  120. """
  121. args = [] # type: CommandArgs
  122. rev = self.arg_rev
  123. if rev is not None:
  124. args += self.vc_class.get_base_rev_args(rev)
  125. args += self.extra_args
  126. return args
  127. def to_display(self):
  128. # type: () -> str
  129. if not self.rev:
  130. return ''
  131. return ' (to revision {})'.format(self.rev)
  132. def make_new(self, rev):
  133. # type: (str) -> RevOptions
  134. """
  135. Make a copy of the current instance, but with a new rev.
  136. Args:
  137. rev: the name of the revision for the new object.
  138. """
  139. return self.vc_class.make_rev_options(rev, extra_args=self.extra_args)
  140. class VcsSupport(object):
  141. _registry = {} # type: Dict[str, VersionControl]
  142. schemes = ['ssh', 'git', 'hg', 'bzr', 'sftp', 'svn']
  143. def __init__(self):
  144. # type: () -> None
  145. # Register more schemes with urlparse for various version control
  146. # systems
  147. urllib_parse.uses_netloc.extend(self.schemes)
  148. # Python >= 2.7.4, 3.3 doesn't have uses_fragment
  149. if getattr(urllib_parse, 'uses_fragment', None):
  150. urllib_parse.uses_fragment.extend(self.schemes)
  151. super(VcsSupport, self).__init__()
  152. def __iter__(self):
  153. # type: () -> Iterator[str]
  154. return self._registry.__iter__()
  155. @property
  156. def backends(self):
  157. # type: () -> List[VersionControl]
  158. return list(self._registry.values())
  159. @property
  160. def dirnames(self):
  161. # type: () -> List[str]
  162. return [backend.dirname for backend in self.backends]
  163. @property
  164. def all_schemes(self):
  165. # type: () -> List[str]
  166. schemes = [] # type: List[str]
  167. for backend in self.backends:
  168. schemes.extend(backend.schemes)
  169. return schemes
  170. def register(self, cls):
  171. # type: (Type[VersionControl]) -> None
  172. if not hasattr(cls, 'name'):
  173. logger.warning('Cannot register VCS %s', cls.__name__)
  174. return
  175. if cls.name not in self._registry:
  176. self._registry[cls.name] = cls()
  177. logger.debug('Registered VCS backend: %s', cls.name)
  178. def unregister(self, name):
  179. # type: (str) -> None
  180. if name in self._registry:
  181. del self._registry[name]
  182. def get_backend_for_dir(self, location):
  183. # type: (str) -> Optional[VersionControl]
  184. """
  185. Return a VersionControl object if a repository of that type is found
  186. at the given directory.
  187. """
  188. vcs_backends = {}
  189. for vcs_backend in self._registry.values():
  190. repo_path = vcs_backend.get_repository_root(location)
  191. if not repo_path:
  192. continue
  193. logger.debug('Determine that %s uses VCS: %s',
  194. location, vcs_backend.name)
  195. vcs_backends[repo_path] = vcs_backend
  196. if not vcs_backends:
  197. return None
  198. # Choose the VCS in the inner-most directory. Since all repository
  199. # roots found here would be either `location` or one of its
  200. # parents, the longest path should have the most path components,
  201. # i.e. the backend representing the inner-most repository.
  202. inner_most_repo_path = max(vcs_backends, key=len)
  203. return vcs_backends[inner_most_repo_path]
  204. def get_backend_for_scheme(self, scheme):
  205. # type: (str) -> Optional[VersionControl]
  206. """
  207. Return a VersionControl object or None.
  208. """
  209. for vcs_backend in self._registry.values():
  210. if scheme in vcs_backend.schemes:
  211. return vcs_backend
  212. return None
  213. def get_backend(self, name):
  214. # type: (str) -> Optional[VersionControl]
  215. """
  216. Return a VersionControl object or None.
  217. """
  218. name = name.lower()
  219. return self._registry.get(name)
  220. vcs = VcsSupport()
  221. class VersionControl(object):
  222. name = ''
  223. dirname = ''
  224. repo_name = ''
  225. # List of supported schemes for this Version Control
  226. schemes = () # type: Tuple[str, ...]
  227. # Iterable of environment variable names to pass to call_subprocess().
  228. unset_environ = () # type: Tuple[str, ...]
  229. default_arg_rev = None # type: Optional[str]
  230. @classmethod
  231. def should_add_vcs_url_prefix(cls, remote_url):
  232. # type: (str) -> bool
  233. """
  234. Return whether the vcs prefix (e.g. "git+") should be added to a
  235. repository's remote url when used in a requirement.
  236. """
  237. return not remote_url.lower().startswith('{}:'.format(cls.name))
  238. @classmethod
  239. def get_subdirectory(cls, location):
  240. # type: (str) -> Optional[str]
  241. """
  242. Return the path to setup.py, relative to the repo root.
  243. Return None if setup.py is in the repo root.
  244. """
  245. return None
  246. @classmethod
  247. def get_requirement_revision(cls, repo_dir):
  248. # type: (str) -> str
  249. """
  250. Return the revision string that should be used in a requirement.
  251. """
  252. return cls.get_revision(repo_dir)
  253. @classmethod
  254. def get_src_requirement(cls, repo_dir, project_name):
  255. # type: (str, str) -> Optional[str]
  256. """
  257. Return the requirement string to use to redownload the files
  258. currently at the given repository directory.
  259. Args:
  260. project_name: the (unescaped) project name.
  261. The return value has a form similar to the following:
  262. {repository_url}@{revision}#egg={project_name}
  263. """
  264. repo_url = cls.get_remote_url(repo_dir)
  265. if repo_url is None:
  266. return None
  267. if cls.should_add_vcs_url_prefix(repo_url):
  268. repo_url = '{}+{}'.format(cls.name, repo_url)
  269. revision = cls.get_requirement_revision(repo_dir)
  270. subdir = cls.get_subdirectory(repo_dir)
  271. req = make_vcs_requirement_url(repo_url, revision, project_name,
  272. subdir=subdir)
  273. return req
  274. @staticmethod
  275. def get_base_rev_args(rev):
  276. # type: (str) -> List[str]
  277. """
  278. Return the base revision arguments for a vcs command.
  279. Args:
  280. rev: the name of a revision to install. Cannot be None.
  281. """
  282. raise NotImplementedError
  283. def is_immutable_rev_checkout(self, url, dest):
  284. # type: (str, str) -> bool
  285. """
  286. Return true if the commit hash checked out at dest matches
  287. the revision in url.
  288. Always return False, if the VCS does not support immutable commit
  289. hashes.
  290. This method does not check if there are local uncommitted changes
  291. in dest after checkout, as pip currently has no use case for that.
  292. """
  293. return False
  294. @classmethod
  295. def make_rev_options(cls, rev=None, extra_args=None):
  296. # type: (Optional[str], Optional[CommandArgs]) -> RevOptions
  297. """
  298. Return a RevOptions object.
  299. Args:
  300. rev: the name of a revision to install.
  301. extra_args: a list of extra options.
  302. """
  303. return RevOptions(cls, rev, extra_args=extra_args)
  304. @classmethod
  305. def _is_local_repository(cls, repo):
  306. # type: (str) -> bool
  307. """
  308. posix absolute paths start with os.path.sep,
  309. win32 ones start with drive (like c:\\folder)
  310. """
  311. drive, tail = os.path.splitdrive(repo)
  312. return repo.startswith(os.path.sep) or bool(drive)
  313. def export(self, location, url):
  314. # type: (str, HiddenText) -> None
  315. """
  316. Export the repository at the url to the destination location
  317. i.e. only download the files, without vcs informations
  318. :param url: the repository URL starting with a vcs prefix.
  319. """
  320. raise NotImplementedError
  321. @classmethod
  322. def get_netloc_and_auth(cls, netloc, scheme):
  323. # type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]]
  324. """
  325. Parse the repository URL's netloc, and return the new netloc to use
  326. along with auth information.
  327. Args:
  328. netloc: the original repository URL netloc.
  329. scheme: the repository URL's scheme without the vcs prefix.
  330. This is mainly for the Subversion class to override, so that auth
  331. information can be provided via the --username and --password options
  332. instead of through the URL. For other subclasses like Git without
  333. such an option, auth information must stay in the URL.
  334. Returns: (netloc, (username, password)).
  335. """
  336. return netloc, (None, None)
  337. @classmethod
  338. def get_url_rev_and_auth(cls, url):
  339. # type: (str) -> Tuple[str, Optional[str], AuthInfo]
  340. """
  341. Parse the repository URL to use, and return the URL, revision,
  342. and auth info to use.
  343. Returns: (url, rev, (username, password)).
  344. """
  345. scheme, netloc, path, query, frag = urllib_parse.urlsplit(url)
  346. if '+' not in scheme:
  347. raise ValueError(
  348. "Sorry, {!r} is a malformed VCS url. "
  349. "The format is <vcs>+<protocol>://<url>, "
  350. "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp".format(url)
  351. )
  352. # Remove the vcs prefix.
  353. scheme = scheme.split('+', 1)[1]
  354. netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme)
  355. rev = None
  356. if '@' in path:
  357. path, rev = path.rsplit('@', 1)
  358. if not rev:
  359. raise InstallationError(
  360. "The URL {!r} has an empty revision (after @) "
  361. "which is not supported. Include a revision after @ "
  362. "or remove @ from the URL.".format(url)
  363. )
  364. url = urllib_parse.urlunsplit((scheme, netloc, path, query, ''))
  365. return url, rev, user_pass
  366. @staticmethod
  367. def make_rev_args(username, password):
  368. # type: (Optional[str], Optional[HiddenText]) -> CommandArgs
  369. """
  370. Return the RevOptions "extra arguments" to use in obtain().
  371. """
  372. return []
  373. def get_url_rev_options(self, url):
  374. # type: (HiddenText) -> Tuple[HiddenText, RevOptions]
  375. """
  376. Return the URL and RevOptions object to use in obtain() and in
  377. some cases export(), as a tuple (url, rev_options).
  378. """
  379. secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret)
  380. username, secret_password = user_pass
  381. password = None # type: Optional[HiddenText]
  382. if secret_password is not None:
  383. password = hide_value(secret_password)
  384. extra_args = self.make_rev_args(username, password)
  385. rev_options = self.make_rev_options(rev, extra_args=extra_args)
  386. return hide_url(secret_url), rev_options
  387. @staticmethod
  388. def normalize_url(url):
  389. # type: (str) -> str
  390. """
  391. Normalize a URL for comparison by unquoting it and removing any
  392. trailing slash.
  393. """
  394. return urllib_parse.unquote(url).rstrip('/')
  395. @classmethod
  396. def compare_urls(cls, url1, url2):
  397. # type: (str, str) -> bool
  398. """
  399. Compare two repo URLs for identity, ignoring incidental differences.
  400. """
  401. return (cls.normalize_url(url1) == cls.normalize_url(url2))
  402. def fetch_new(self, dest, url, rev_options):
  403. # type: (str, HiddenText, RevOptions) -> None
  404. """
  405. Fetch a revision from a repository, in the case that this is the
  406. first fetch from the repository.
  407. Args:
  408. dest: the directory to fetch the repository to.
  409. rev_options: a RevOptions object.
  410. """
  411. raise NotImplementedError
  412. def switch(self, dest, url, rev_options):
  413. # type: (str, HiddenText, RevOptions) -> None
  414. """
  415. Switch the repo at ``dest`` to point to ``URL``.
  416. Args:
  417. rev_options: a RevOptions object.
  418. """
  419. raise NotImplementedError
  420. def update(self, dest, url, rev_options):
  421. # type: (str, HiddenText, RevOptions) -> None
  422. """
  423. Update an already-existing repo to the given ``rev_options``.
  424. Args:
  425. rev_options: a RevOptions object.
  426. """
  427. raise NotImplementedError
  428. @classmethod
  429. def is_commit_id_equal(cls, dest, name):
  430. # type: (str, Optional[str]) -> bool
  431. """
  432. Return whether the id of the current commit equals the given name.
  433. Args:
  434. dest: the repository directory.
  435. name: a string name.
  436. """
  437. raise NotImplementedError
  438. def obtain(self, dest, url):
  439. # type: (str, HiddenText) -> None
  440. """
  441. Install or update in editable mode the package represented by this
  442. VersionControl object.
  443. :param dest: the repository directory in which to install or update.
  444. :param url: the repository URL starting with a vcs prefix.
  445. """
  446. url, rev_options = self.get_url_rev_options(url)
  447. if not os.path.exists(dest):
  448. self.fetch_new(dest, url, rev_options)
  449. return
  450. rev_display = rev_options.to_display()
  451. if self.is_repository_directory(dest):
  452. existing_url = self.get_remote_url(dest)
  453. if self.compare_urls(existing_url, url.secret):
  454. logger.debug(
  455. '%s in %s exists, and has correct URL (%s)',
  456. self.repo_name.title(),
  457. display_path(dest),
  458. url,
  459. )
  460. if not self.is_commit_id_equal(dest, rev_options.rev):
  461. logger.info(
  462. 'Updating %s %s%s',
  463. display_path(dest),
  464. self.repo_name,
  465. rev_display,
  466. )
  467. self.update(dest, url, rev_options)
  468. else:
  469. logger.info('Skipping because already up-to-date.')
  470. return
  471. logger.warning(
  472. '%s %s in %s exists with URL %s',
  473. self.name,
  474. self.repo_name,
  475. display_path(dest),
  476. existing_url,
  477. )
  478. prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ',
  479. ('s', 'i', 'w', 'b'))
  480. else:
  481. logger.warning(
  482. 'Directory %s already exists, and is not a %s %s.',
  483. dest,
  484. self.name,
  485. self.repo_name,
  486. )
  487. # https://github.com/python/mypy/issues/1174
  488. prompt = ('(i)gnore, (w)ipe, (b)ackup ', # type: ignore
  489. ('i', 'w', 'b'))
  490. logger.warning(
  491. 'The plan is to install the %s repository %s',
  492. self.name,
  493. url,
  494. )
  495. response = ask_path_exists('What to do? {}'.format(
  496. prompt[0]), prompt[1])
  497. if response == 'a':
  498. sys.exit(-1)
  499. if response == 'w':
  500. logger.warning('Deleting %s', display_path(dest))
  501. rmtree(dest)
  502. self.fetch_new(dest, url, rev_options)
  503. return
  504. if response == 'b':
  505. dest_dir = backup_dir(dest)
  506. logger.warning(
  507. 'Backing up %s to %s', display_path(dest), dest_dir,
  508. )
  509. shutil.move(dest, dest_dir)
  510. self.fetch_new(dest, url, rev_options)
  511. return
  512. # Do nothing if the response is "i".
  513. if response == 's':
  514. logger.info(
  515. 'Switching %s %s to %s%s',
  516. self.repo_name,
  517. display_path(dest),
  518. url,
  519. rev_display,
  520. )
  521. self.switch(dest, url, rev_options)
  522. def unpack(self, location, url):
  523. # type: (str, HiddenText) -> None
  524. """
  525. Clean up current location and download the url repository
  526. (and vcs infos) into location
  527. :param url: the repository URL starting with a vcs prefix.
  528. """
  529. if os.path.exists(location):
  530. rmtree(location)
  531. self.obtain(location, url=url)
  532. @classmethod
  533. def get_remote_url(cls, location):
  534. # type: (str) -> str
  535. """
  536. Return the url used at location
  537. Raises RemoteNotFoundError if the repository does not have a remote
  538. url configured.
  539. """
  540. raise NotImplementedError
  541. @classmethod
  542. def get_revision(cls, location):
  543. # type: (str) -> str
  544. """
  545. Return the current commit id of the files at the given location.
  546. """
  547. raise NotImplementedError
  548. @classmethod
  549. def run_command(
  550. cls,
  551. cmd, # type: Union[List[str], CommandArgs]
  552. show_stdout=True, # type: bool
  553. cwd=None, # type: Optional[str]
  554. on_returncode='raise', # type: str
  555. extra_ok_returncodes=None, # type: Optional[Iterable[int]]
  556. command_desc=None, # type: Optional[str]
  557. extra_environ=None, # type: Optional[Mapping[str, Any]]
  558. spinner=None, # type: Optional[SpinnerInterface]
  559. log_failed_cmd=True # type: bool
  560. ):
  561. # type: (...) -> Text
  562. """
  563. Run a VCS subcommand
  564. This is simply a wrapper around call_subprocess that adds the VCS
  565. command name, and checks that the VCS is available
  566. """
  567. cmd = make_command(cls.name, *cmd)
  568. try:
  569. return call_subprocess(cmd, show_stdout, cwd,
  570. on_returncode=on_returncode,
  571. extra_ok_returncodes=extra_ok_returncodes,
  572. command_desc=command_desc,
  573. extra_environ=extra_environ,
  574. unset_environ=cls.unset_environ,
  575. spinner=spinner,
  576. log_failed_cmd=log_failed_cmd)
  577. except OSError as e:
  578. # errno.ENOENT = no such file or directory
  579. # In other words, the VCS executable isn't available
  580. if e.errno == errno.ENOENT:
  581. raise BadCommand(
  582. 'Cannot find command {cls.name!r} - do you have '
  583. '{cls.name!r} installed and in your '
  584. 'PATH?'.format(**locals()))
  585. else:
  586. raise # re-raise exception if a different error occurred
  587. @classmethod
  588. def is_repository_directory(cls, path):
  589. # type: (str) -> bool
  590. """
  591. Return whether a directory path is a repository directory.
  592. """
  593. logger.debug('Checking in %s for %s (%s)...',
  594. path, cls.dirname, cls.name)
  595. return os.path.exists(os.path.join(path, cls.dirname))
  596. @classmethod
  597. def get_repository_root(cls, location):
  598. # type: (str) -> Optional[str]
  599. """
  600. Return the "root" (top-level) directory controlled by the vcs,
  601. or `None` if the directory is not in any.
  602. It is meant to be overridden to implement smarter detection
  603. mechanisms for specific vcs.
  604. This can do more than is_repository_directory() alone. For
  605. example, the Git override checks that Git is actually available.
  606. """
  607. if cls.is_repository_directory(location):
  608. return location
  609. return None