versioncontrol.py 22 KB

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