versioncontrol.py 22 KB

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