git.py 18 KB

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