versioncontrol.py 23 KB

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