git.py 18 KB

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