versioncontrol.py 23 KB

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