git.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. from __future__ import annotations
  2. import logging
  3. import os.path
  4. import pathlib
  5. import re
  6. import urllib.parse
  7. import urllib.request
  8. from dataclasses import replace
  9. from typing import Any
  10. from pip._internal.exceptions import BadCommand, InstallationError
  11. from pip._internal.utils.misc import HiddenText, display_path, hide_url
  12. from pip._internal.utils.subprocess import make_command
  13. from pip._internal.vcs.versioncontrol import (
  14. AuthInfo,
  15. RemoteNotFoundError,
  16. RemoteNotValidError,
  17. RevOptions,
  18. VersionControl,
  19. find_path_to_project_root_from_repo_root,
  20. vcs,
  21. )
  22. urlsplit = urllib.parse.urlsplit
  23. urlunsplit = urllib.parse.urlunsplit
  24. logger = logging.getLogger(__name__)
  25. GIT_VERSION_REGEX = re.compile(
  26. r"^git version " # Prefix.
  27. r"(\d+)" # Major.
  28. r"\.(\d+)" # Dot, minor.
  29. r"(?:\.(\d+))?" # Optional dot, patch.
  30. r".*$" # Suffix, including any pre- and post-release segments we don't care about.
  31. )
  32. HASH_REGEX = re.compile("^[a-fA-F0-9]{40}$")
  33. # SCP (Secure copy protocol) shorthand. e.g. 'git@example.com:foo/bar.git'
  34. SCP_REGEX = re.compile(
  35. r"""^
  36. # Optional user, e.g. 'git@'
  37. (\w+@)?
  38. # Server, e.g. 'github.com'.
  39. ([^/:]+):
  40. # The server-side path. e.g. 'user/project.git'. Must start with an
  41. # alphanumeric character so as not to be confusable with a Windows paths
  42. # like 'C:/foo/bar' or 'C:\foo\bar'.
  43. (\w[^:]*)
  44. $""",
  45. re.VERBOSE,
  46. )
  47. def looks_like_hash(sha: str) -> bool:
  48. return bool(HASH_REGEX.match(sha))
  49. class Git(VersionControl):
  50. name = "git"
  51. dirname = ".git"
  52. repo_name = "clone"
  53. schemes = (
  54. "git+http",
  55. "git+https",
  56. "git+ssh",
  57. "git+git",
  58. "git+file",
  59. )
  60. # Prevent the user's environment variables from interfering with pip:
  61. # https://github.com/pypa/pip/issues/1130
  62. unset_environ = ("GIT_DIR", "GIT_WORK_TREE")
  63. default_arg_rev = "HEAD"
  64. @staticmethod
  65. def get_base_rev_args(rev: str) -> list[str]:
  66. return [rev]
  67. @classmethod
  68. def run_command(cls, *args: Any, **kwargs: Any) -> str:
  69. if os.environ.get("PIP_NO_INPUT"):
  70. extra_environ = kwargs.get("extra_environ", {})
  71. extra_environ["GIT_TERMINAL_PROMPT"] = "0"
  72. extra_environ["GIT_SSH_COMMAND"] = "ssh -oBatchMode=yes"
  73. kwargs["extra_environ"] = extra_environ
  74. return super().run_command(*args, **kwargs)
  75. def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:
  76. _, rev_options = self.get_url_rev_options(hide_url(url))
  77. if not rev_options.rev:
  78. return False
  79. if not self.is_commit_id_equal(dest, rev_options.rev):
  80. # the current commit is different from rev,
  81. # which means rev was something else than a commit hash
  82. return False
  83. # return False in the rare case rev is both a commit hash
  84. # and a tag or a branch; we don't want to cache in that case
  85. # because that branch/tag could point to something else in the future
  86. is_tag_or_branch = bool(self.get_revision_sha(dest, rev_options.rev)[0])
  87. return not is_tag_or_branch
  88. def get_git_version(self) -> tuple[int, ...]:
  89. version = self.run_command(
  90. ["version"],
  91. command_desc="git version",
  92. show_stdout=False,
  93. stdout_only=True,
  94. )
  95. match = GIT_VERSION_REGEX.match(version)
  96. if not match:
  97. logger.warning("Can't parse git version: %s", version)
  98. return ()
  99. return (int(match.group(1)), int(match.group(2)))
  100. @classmethod
  101. def get_current_branch(cls, location: str) -> str | None:
  102. """
  103. Return the current branch, or None if HEAD isn't at a branch
  104. (e.g. detached HEAD).
  105. """
  106. # git-symbolic-ref exits with empty stdout if "HEAD" is a detached
  107. # HEAD rather than a symbolic ref. In addition, the -q causes the
  108. # command to exit with status code 1 instead of 128 in this case
  109. # and to suppress the message to stderr.
  110. args = ["symbolic-ref", "-q", "HEAD"]
  111. output = cls.run_command(
  112. args,
  113. extra_ok_returncodes=(1,),
  114. show_stdout=False,
  115. stdout_only=True,
  116. cwd=location,
  117. )
  118. ref = output.strip()
  119. if ref.startswith("refs/heads/"):
  120. return ref[len("refs/heads/") :]
  121. return None
  122. @classmethod
  123. def get_revision_sha(cls, dest: str, rev: str) -> tuple[str | None, bool]:
  124. """
  125. Return (sha_or_none, is_branch), where sha_or_none is a commit hash
  126. if the revision names a remote branch or tag, otherwise None.
  127. Args:
  128. dest: the repository directory.
  129. rev: the revision name.
  130. """
  131. # Pass rev to pre-filter the list.
  132. output = cls.run_command(
  133. ["show-ref", rev],
  134. cwd=dest,
  135. show_stdout=False,
  136. stdout_only=True,
  137. on_returncode="ignore",
  138. )
  139. refs = {}
  140. # NOTE: We do not use splitlines here since that would split on other
  141. # unicode separators, which can be maliciously used to install a
  142. # different revision.
  143. for line in output.strip().split("\n"):
  144. line = line.rstrip("\r")
  145. if not line:
  146. continue
  147. try:
  148. ref_sha, ref_name = line.split(" ", maxsplit=2)
  149. except ValueError:
  150. # Include the offending line to simplify troubleshooting if
  151. # this error ever occurs.
  152. raise ValueError(f"unexpected show-ref line: {line!r}")
  153. refs[ref_name] = ref_sha
  154. branch_ref = f"refs/remotes/origin/{rev}"
  155. tag_ref = f"refs/tags/{rev}"
  156. sha = refs.get(branch_ref)
  157. if sha is not None:
  158. return (sha, True)
  159. sha = refs.get(tag_ref)
  160. return (sha, False)
  161. @classmethod
  162. def _should_fetch(cls, dest: str, rev: str) -> bool:
  163. """
  164. Return true if rev is a ref or is a commit that we don't have locally.
  165. Branches and tags are not considered in this method because they are
  166. assumed to be always available locally (which is a normal outcome of
  167. ``git clone`` and ``git fetch --tags``).
  168. """
  169. if rev.startswith("refs/"):
  170. # Always fetch remote refs.
  171. return True
  172. if not looks_like_hash(rev):
  173. # Git fetch would fail with abbreviated commits.
  174. return False
  175. if cls.has_commit(dest, rev):
  176. # Don't fetch if we have the commit locally.
  177. return False
  178. return True
  179. @classmethod
  180. def resolve_revision(
  181. cls, dest: str, url: HiddenText, rev_options: RevOptions
  182. ) -> RevOptions:
  183. """
  184. Resolve a revision to a new RevOptions object with the SHA1 of the
  185. branch, tag, or ref if found.
  186. Args:
  187. rev_options: a RevOptions object.
  188. """
  189. rev = rev_options.arg_rev
  190. # The arg_rev property's implementation for Git ensures that the
  191. # rev return value is always non-None.
  192. assert rev is not None
  193. sha, is_branch = cls.get_revision_sha(dest, rev)
  194. if sha is not None:
  195. rev_options = rev_options.make_new(sha)
  196. rev_options = replace(rev_options, branch_name=(rev if is_branch else None))
  197. return rev_options
  198. # Do not show a warning for the common case of something that has
  199. # the form of a Git commit hash.
  200. if not looks_like_hash(rev):
  201. logger.info(
  202. "Did not find branch or tag '%s', assuming revision or ref.",
  203. rev,
  204. )
  205. if not cls._should_fetch(dest, rev):
  206. return rev_options
  207. # fetch the requested revision
  208. cls.run_command(
  209. make_command("fetch", "-q", url, rev_options.to_args()),
  210. cwd=dest,
  211. )
  212. # Change the revision to the SHA of the ref we fetched
  213. sha = cls.get_revision(dest, rev="FETCH_HEAD")
  214. rev_options = rev_options.make_new(sha)
  215. return rev_options
  216. @classmethod
  217. def is_commit_id_equal(cls, dest: str, name: str | None) -> bool:
  218. """
  219. Return whether the current commit hash equals the given name.
  220. Args:
  221. dest: the repository directory.
  222. name: a string name.
  223. """
  224. if not name:
  225. # Then avoid an unnecessary subprocess call.
  226. return False
  227. return cls.get_revision(dest) == name
  228. def fetch_new(
  229. self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int
  230. ) -> None:
  231. rev_display = rev_options.to_display()
  232. logger.info("Cloning %s%s to %s", url, rev_display, display_path(dest))
  233. if verbosity <= 0:
  234. flags: tuple[str, ...] = ("--quiet",)
  235. elif verbosity == 1:
  236. flags = ()
  237. else:
  238. flags = ("--verbose", "--progress")
  239. if self.get_git_version() >= (2, 17):
  240. # Git added support for partial clone in 2.17
  241. # https://git-scm.com/docs/partial-clone
  242. # Speeds up cloning by functioning without a complete copy of repository
  243. self.run_command(
  244. make_command(
  245. "clone",
  246. "--filter=blob:none",
  247. *flags,
  248. url,
  249. dest,
  250. )
  251. )
  252. else:
  253. self.run_command(make_command("clone", *flags, url, dest))
  254. if rev_options.rev:
  255. # Then a specific revision was requested.
  256. rev_options = self.resolve_revision(dest, url, rev_options)
  257. branch_name = getattr(rev_options, "branch_name", None)
  258. logger.debug("Rev options %s, branch_name %s", rev_options, branch_name)
  259. if branch_name is None:
  260. # Only do a checkout if the current commit id doesn't match
  261. # the requested revision.
  262. if not self.is_commit_id_equal(dest, rev_options.rev):
  263. cmd_args = make_command(
  264. "checkout",
  265. "-q",
  266. rev_options.to_args(),
  267. )
  268. self.run_command(cmd_args, cwd=dest)
  269. elif self.get_current_branch(dest) != branch_name:
  270. # Then a specific branch was requested, and that branch
  271. # is not yet checked out.
  272. track_branch = f"origin/{branch_name}"
  273. cmd_args = [
  274. "checkout",
  275. "-b",
  276. branch_name,
  277. "--track",
  278. track_branch,
  279. ]
  280. self.run_command(cmd_args, cwd=dest)
  281. else:
  282. sha = self.get_revision(dest)
  283. rev_options = rev_options.make_new(sha)
  284. logger.info("Resolved %s to commit %s", url, rev_options.rev)
  285. #: repo may contain submodules
  286. self.update_submodules(dest, verbosity=verbosity)
  287. def switch(
  288. self,
  289. dest: str,
  290. url: HiddenText,
  291. rev_options: RevOptions,
  292. verbosity: int = 0,
  293. ) -> None:
  294. self.run_command(
  295. make_command("config", "remote.origin.url", url),
  296. cwd=dest,
  297. )
  298. extra_flags = []
  299. if verbosity <= 0:
  300. extra_flags.append("-q")
  301. cmd_args = make_command("checkout", *extra_flags, rev_options.to_args())
  302. self.run_command(cmd_args, cwd=dest)
  303. self.update_submodules(dest, verbosity=verbosity)
  304. def update(
  305. self,
  306. dest: str,
  307. url: HiddenText,
  308. rev_options: RevOptions,
  309. verbosity: int = 0,
  310. ) -> None:
  311. extra_flags = []
  312. if verbosity <= 0:
  313. extra_flags.append("-q")
  314. # First fetch changes from the default remote
  315. if self.get_git_version() >= (1, 9):
  316. # fetch tags in addition to everything else
  317. self.run_command(["fetch", "--tags", *extra_flags], cwd=dest)
  318. else:
  319. self.run_command(["fetch", *extra_flags], cwd=dest)
  320. # Then reset to wanted revision (maybe even origin/master)
  321. rev_options = self.resolve_revision(dest, url, rev_options)
  322. cmd_args = make_command(
  323. "reset",
  324. "--hard",
  325. *extra_flags,
  326. rev_options.to_args(),
  327. )
  328. self.run_command(cmd_args, cwd=dest)
  329. #: update submodules
  330. self.update_submodules(dest, verbosity=verbosity)
  331. @classmethod
  332. def get_remote_url(cls, location: str) -> str:
  333. """
  334. Return URL of the first remote encountered.
  335. Raises RemoteNotFoundError if the repository does not have a remote
  336. url configured.
  337. """
  338. # We need to pass 1 for extra_ok_returncodes since the command
  339. # exits with return code 1 if there are no matching lines.
  340. stdout = cls.run_command(
  341. ["config", "--get-regexp", r"remote\..*\.url"],
  342. extra_ok_returncodes=(1,),
  343. show_stdout=False,
  344. stdout_only=True,
  345. cwd=location,
  346. )
  347. remotes = stdout.splitlines()
  348. try:
  349. found_remote = remotes[0]
  350. except IndexError:
  351. raise RemoteNotFoundError
  352. for remote in remotes:
  353. if remote.startswith("remote.origin.url "):
  354. found_remote = remote
  355. break
  356. url = found_remote.split(" ")[1]
  357. return cls._git_remote_to_pip_url(url.strip())
  358. @staticmethod
  359. def _git_remote_to_pip_url(url: str) -> str:
  360. """
  361. Convert a remote url from what git uses to what pip accepts.
  362. There are 3 legal forms **url** may take:
  363. 1. A fully qualified url: ssh://git@example.com/foo/bar.git
  364. 2. A local project.git folder: /path/to/bare/repository.git
  365. 3. SCP shorthand for form 1: git@example.com:foo/bar.git
  366. Form 1 is output as-is. Form 2 must be converted to URI and form 3 must
  367. be converted to form 1.
  368. See the corresponding test test_git_remote_url_to_pip() for examples of
  369. sample inputs/outputs.
  370. """
  371. if re.match(r"\w+://", url):
  372. # This is already valid. Pass it though as-is.
  373. return url
  374. if os.path.exists(url):
  375. # A local bare remote (git clone --mirror).
  376. # Needs a file:// prefix.
  377. return pathlib.PurePath(url).as_uri()
  378. scp_match = SCP_REGEX.match(url)
  379. if scp_match:
  380. # Add an ssh:// prefix and replace the ':' with a '/'.
  381. return scp_match.expand(r"ssh://\1\2/\3")
  382. # Otherwise, bail out.
  383. raise RemoteNotValidError(url)
  384. @classmethod
  385. def has_commit(cls, location: str, rev: str) -> bool:
  386. """
  387. Check if rev is a commit that is available in the local repository.
  388. """
  389. try:
  390. cls.run_command(
  391. ["rev-parse", "-q", "--verify", "sha^" + rev],
  392. cwd=location,
  393. log_failed_cmd=False,
  394. )
  395. except InstallationError:
  396. return False
  397. else:
  398. return True
  399. @classmethod
  400. def get_revision(cls, location: str, rev: str | None = None) -> str:
  401. if rev is None:
  402. rev = "HEAD"
  403. current_rev = cls.run_command(
  404. ["rev-parse", rev],
  405. show_stdout=False,
  406. stdout_only=True,
  407. cwd=location,
  408. )
  409. return current_rev.strip()
  410. @classmethod
  411. def get_subdirectory(cls, location: str) -> str | None:
  412. """
  413. Return the path to Python project root, relative to the repo root.
  414. Return None if the project root is in the repo root.
  415. """
  416. # find the repo root
  417. git_dir = cls.run_command(
  418. ["rev-parse", "--git-dir"],
  419. show_stdout=False,
  420. stdout_only=True,
  421. cwd=location,
  422. ).strip()
  423. if not os.path.isabs(git_dir):
  424. git_dir = os.path.join(location, git_dir)
  425. repo_root = os.path.abspath(os.path.join(git_dir, ".."))
  426. return find_path_to_project_root_from_repo_root(location, repo_root)
  427. @classmethod
  428. def get_url_rev_and_auth(cls, url: str) -> tuple[str, str | None, AuthInfo]:
  429. """
  430. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  431. That's required because although they use SSH they sometimes don't
  432. work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
  433. parsing. Hence we remove it again afterwards and return it as a stub.
  434. """
  435. # Works around an apparent Git bug
  436. # (see https://article.gmane.org/gmane.comp.version-control.git/146500)
  437. scheme, netloc, path, query, fragment = urlsplit(url)
  438. if scheme.endswith("file"):
  439. initial_slashes = path[: -len(path.lstrip("/"))]
  440. newpath = initial_slashes + urllib.request.url2pathname(path).replace(
  441. "\\", "/"
  442. ).lstrip("/")
  443. after_plus = scheme.find("+") + 1
  444. url = scheme[:after_plus] + urlunsplit(
  445. (scheme[after_plus:], netloc, newpath, query, fragment),
  446. )
  447. if "://" not in url:
  448. assert "file:" not in url
  449. url = url.replace("git+", "git+ssh://")
  450. url, rev, user_pass = super().get_url_rev_and_auth(url)
  451. url = url.replace("ssh://", "")
  452. else:
  453. url, rev, user_pass = super().get_url_rev_and_auth(url)
  454. return url, rev, user_pass
  455. @classmethod
  456. def update_submodules(cls, location: str, verbosity: int = 0) -> None:
  457. argv = ["submodule", "update", "--init", "--recursive"]
  458. if verbosity <= 0:
  459. argv.append("-q")
  460. if not os.path.exists(os.path.join(location, ".gitmodules")):
  461. return
  462. cls.run_command(
  463. argv,
  464. cwd=location,
  465. )
  466. @classmethod
  467. def get_repository_root(cls, location: str) -> str | None:
  468. loc = super().get_repository_root(location)
  469. if loc:
  470. return loc
  471. try:
  472. r = cls.run_command(
  473. ["rev-parse", "--show-toplevel"],
  474. cwd=location,
  475. show_stdout=False,
  476. stdout_only=True,
  477. on_returncode="raise",
  478. log_failed_cmd=False,
  479. )
  480. except BadCommand:
  481. logger.debug(
  482. "could not determine if %s is under git control "
  483. "because git is not available",
  484. location,
  485. )
  486. return None
  487. except InstallationError:
  488. return None
  489. return os.path.normpath(r.rstrip("\r\n"))
  490. @staticmethod
  491. def should_add_vcs_url_prefix(repo_url: str) -> bool:
  492. """In either https or ssh form, requirements must be prefixed with git+."""
  493. return True
  494. vcs.register(Git)