git.py 17 KB

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