versioncontrol.py 22 KB

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