git.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. # The following comment should be removed at some point in the future.
  2. # mypy: disallow-untyped-defs=False
  3. from __future__ import absolute_import
  4. import logging
  5. import os.path
  6. import re
  7. from pip._vendor.packaging.version import parse as parse_version
  8. from pip._vendor.six.moves.urllib import parse as urllib_parse
  9. from pip._vendor.six.moves.urllib import request as urllib_request
  10. from pip._internal.exceptions import BadCommand, InstallationError
  11. from pip._internal.utils.misc import display_path, hide_url
  12. from pip._internal.utils.subprocess import make_command
  13. from pip._internal.utils.temp_dir import TempDirectory
  14. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  15. from pip._internal.vcs.versioncontrol import (
  16. RemoteNotFoundError,
  17. VersionControl,
  18. find_path_to_setup_from_repo_root,
  19. vcs,
  20. )
  21. if MYPY_CHECK_RUNNING:
  22. from typing import Optional, Tuple
  23. from pip._internal.utils.misc import HiddenText
  24. from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions
  25. urlsplit = urllib_parse.urlsplit
  26. urlunsplit = urllib_parse.urlunsplit
  27. logger = logging.getLogger(__name__)
  28. HASH_REGEX = re.compile('^[a-fA-F0-9]{40}$')
  29. def looks_like_hash(sha):
  30. return bool(HASH_REGEX.match(sha))
  31. class Git(VersionControl):
  32. name = 'git'
  33. dirname = '.git'
  34. repo_name = 'clone'
  35. schemes = (
  36. 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
  37. )
  38. # Prevent the user's environment variables from interfering with pip:
  39. # https://github.com/pypa/pip/issues/1130
  40. unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')
  41. default_arg_rev = 'HEAD'
  42. @staticmethod
  43. def get_base_rev_args(rev):
  44. return [rev]
  45. def is_immutable_rev_checkout(self, url, dest):
  46. # type: (str, str) -> bool
  47. _, rev_options = self.get_url_rev_options(hide_url(url))
  48. if not rev_options.rev:
  49. return False
  50. if not self.is_commit_id_equal(dest, rev_options.rev):
  51. # the current commit is different from rev,
  52. # which means rev was something else than a commit hash
  53. return False
  54. # return False in the rare case rev is both a commit hash
  55. # and a tag or a branch; we don't want to cache in that case
  56. # because that branch/tag could point to something else in the future
  57. is_tag_or_branch = bool(
  58. self.get_revision_sha(dest, rev_options.rev)[0]
  59. )
  60. return not is_tag_or_branch
  61. def get_git_version(self):
  62. VERSION_PFX = 'git version '
  63. version = self.run_command(
  64. ['version'], show_stdout=False, stdout_only=True
  65. )
  66. if version.startswith(VERSION_PFX):
  67. version = version[len(VERSION_PFX):].split()[0]
  68. else:
  69. version = ''
  70. # get first 3 positions of the git version because
  71. # on windows it is x.y.z.windows.t, and this parses as
  72. # LegacyVersion which always smaller than a Version.
  73. version = '.'.join(version.split('.')[:3])
  74. return parse_version(version)
  75. @classmethod
  76. def get_current_branch(cls, location):
  77. """
  78. Return the current branch, or None if HEAD isn't at a branch
  79. (e.g. detached HEAD).
  80. """
  81. # git-symbolic-ref exits with empty stdout if "HEAD" is a detached
  82. # HEAD rather than a symbolic ref. In addition, the -q causes the
  83. # command to exit with status code 1 instead of 128 in this case
  84. # and to suppress the message to stderr.
  85. args = ['symbolic-ref', '-q', 'HEAD']
  86. output = cls.run_command(
  87. args,
  88. extra_ok_returncodes=(1, ),
  89. show_stdout=False,
  90. stdout_only=True,
  91. cwd=location,
  92. )
  93. ref = output.strip()
  94. if ref.startswith('refs/heads/'):
  95. return ref[len('refs/heads/'):]
  96. return None
  97. def export(self, location, url):
  98. # type: (str, HiddenText) -> None
  99. """Export the Git repository at the url to the destination location"""
  100. if not location.endswith('/'):
  101. location = location + '/'
  102. with TempDirectory(kind="export") as temp_dir:
  103. self.unpack(temp_dir.path, url=url)
  104. self.run_command(
  105. ['checkout-index', '-a', '-f', '--prefix', location],
  106. show_stdout=False, cwd=temp_dir.path
  107. )
  108. @classmethod
  109. def get_revision_sha(cls, dest, rev):
  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. for line in output.strip().splitlines():
  127. try:
  128. sha, ref = line.split()
  129. except ValueError:
  130. # Include the offending line to simplify troubleshooting if
  131. # this error ever occurs.
  132. raise ValueError('unexpected show-ref line: {!r}'.format(line))
  133. refs[ref] = sha
  134. branch_ref = 'refs/remotes/origin/{}'.format(rev)
  135. tag_ref = 'refs/tags/{}'.format(rev)
  136. sha = refs.get(branch_ref)
  137. if sha is not None:
  138. return (sha, True)
  139. sha = refs.get(tag_ref)
  140. return (sha, False)
  141. @classmethod
  142. def _should_fetch(cls, dest, rev):
  143. """
  144. Return true if rev is a ref or is a commit that we don't have locally.
  145. Branches and tags are not considered in this method because they are
  146. assumed to be always available locally (which is a normal outcome of
  147. ``git clone`` and ``git fetch --tags``).
  148. """
  149. if rev.startswith("refs/"):
  150. # Always fetch remote refs.
  151. return True
  152. if not looks_like_hash(rev):
  153. # Git fetch would fail with abbreviated commits.
  154. return False
  155. if cls.has_commit(dest, rev):
  156. # Don't fetch if we have the commit locally.
  157. return False
  158. return True
  159. @classmethod
  160. def resolve_revision(cls, dest, url, rev_options):
  161. # type: (str, HiddenText, RevOptions) -> RevOptions
  162. """
  163. Resolve a revision to a new RevOptions object with the SHA1 of the
  164. branch, tag, or ref if found.
  165. Args:
  166. rev_options: a RevOptions object.
  167. """
  168. rev = rev_options.arg_rev
  169. # The arg_rev property's implementation for Git ensures that the
  170. # rev return value is always non-None.
  171. assert rev is not None
  172. sha, is_branch = cls.get_revision_sha(dest, rev)
  173. if sha is not None:
  174. rev_options = rev_options.make_new(sha)
  175. rev_options.branch_name = rev if is_branch else None
  176. return rev_options
  177. # Do not show a warning for the common case of something that has
  178. # the form of a Git commit hash.
  179. if not looks_like_hash(rev):
  180. logger.warning(
  181. "Did not find branch or tag '%s', assuming revision or ref.",
  182. rev,
  183. )
  184. if not cls._should_fetch(dest, rev):
  185. return rev_options
  186. # fetch the requested revision
  187. cls.run_command(
  188. make_command('fetch', '-q', url, rev_options.to_args()),
  189. cwd=dest,
  190. )
  191. # Change the revision to the SHA of the ref we fetched
  192. sha = cls.get_revision(dest, rev='FETCH_HEAD')
  193. rev_options = rev_options.make_new(sha)
  194. return rev_options
  195. @classmethod
  196. def is_commit_id_equal(cls, dest, name):
  197. """
  198. Return whether the current commit hash equals the given name.
  199. Args:
  200. dest: the repository directory.
  201. name: a string name.
  202. """
  203. if not name:
  204. # Then avoid an unnecessary subprocess call.
  205. return False
  206. return cls.get_revision(dest) == name
  207. def fetch_new(self, dest, url, rev_options):
  208. # type: (str, HiddenText, RevOptions) -> None
  209. rev_display = rev_options.to_display()
  210. logger.info('Cloning %s%s to %s', url, rev_display, display_path(dest))
  211. self.run_command(make_command('clone', '-q', url, dest))
  212. if rev_options.rev:
  213. # Then a specific revision was requested.
  214. rev_options = self.resolve_revision(dest, url, rev_options)
  215. branch_name = getattr(rev_options, 'branch_name', None)
  216. if branch_name is None:
  217. # Only do a checkout if the current commit id doesn't match
  218. # the requested revision.
  219. if not self.is_commit_id_equal(dest, rev_options.rev):
  220. cmd_args = make_command(
  221. 'checkout', '-q', rev_options.to_args(),
  222. )
  223. self.run_command(cmd_args, cwd=dest)
  224. elif self.get_current_branch(dest) != branch_name:
  225. # Then a specific branch was requested, and that branch
  226. # is not yet checked out.
  227. track_branch = 'origin/{}'.format(branch_name)
  228. cmd_args = [
  229. 'checkout', '-b', branch_name, '--track', track_branch,
  230. ]
  231. self.run_command(cmd_args, cwd=dest)
  232. #: repo may contain submodules
  233. self.update_submodules(dest)
  234. def switch(self, dest, url, rev_options):
  235. # type: (str, HiddenText, RevOptions) -> None
  236. self.run_command(
  237. make_command('config', 'remote.origin.url', url),
  238. cwd=dest,
  239. )
  240. cmd_args = make_command('checkout', '-q', rev_options.to_args())
  241. self.run_command(cmd_args, cwd=dest)
  242. self.update_submodules(dest)
  243. def update(self, dest, url, rev_options):
  244. # type: (str, HiddenText, RevOptions) -> None
  245. # First fetch changes from the default remote
  246. if self.get_git_version() >= parse_version('1.9.0'):
  247. # fetch tags in addition to everything else
  248. self.run_command(['fetch', '-q', '--tags'], cwd=dest)
  249. else:
  250. self.run_command(['fetch', '-q'], cwd=dest)
  251. # Then reset to wanted revision (maybe even origin/master)
  252. rev_options = self.resolve_revision(dest, url, rev_options)
  253. cmd_args = make_command('reset', '--hard', '-q', rev_options.to_args())
  254. self.run_command(cmd_args, cwd=dest)
  255. #: update submodules
  256. self.update_submodules(dest)
  257. @classmethod
  258. def get_remote_url(cls, location):
  259. """
  260. Return URL of the first remote encountered.
  261. Raises RemoteNotFoundError if the repository does not have a remote
  262. url configured.
  263. """
  264. # We need to pass 1 for extra_ok_returncodes since the command
  265. # exits with return code 1 if there are no matching lines.
  266. stdout = cls.run_command(
  267. ['config', '--get-regexp', r'remote\..*\.url'],
  268. extra_ok_returncodes=(1, ),
  269. show_stdout=False,
  270. stdout_only=True,
  271. cwd=location,
  272. )
  273. remotes = stdout.splitlines()
  274. try:
  275. found_remote = remotes[0]
  276. except IndexError:
  277. raise RemoteNotFoundError
  278. for remote in remotes:
  279. if remote.startswith('remote.origin.url '):
  280. found_remote = remote
  281. break
  282. url = found_remote.split(' ')[1]
  283. return url.strip()
  284. @classmethod
  285. def has_commit(cls, location, rev):
  286. """
  287. Check if rev is a commit that is available in the local repository.
  288. """
  289. try:
  290. cls.run_command(
  291. ['rev-parse', '-q', '--verify', "sha^" + rev],
  292. cwd=location,
  293. log_failed_cmd=False,
  294. )
  295. except InstallationError:
  296. return False
  297. else:
  298. return True
  299. @classmethod
  300. def get_revision(cls, location, rev=None):
  301. if rev is None:
  302. rev = 'HEAD'
  303. current_rev = cls.run_command(
  304. ['rev-parse', rev],
  305. show_stdout=False,
  306. stdout_only=True,
  307. cwd=location,
  308. )
  309. return current_rev.strip()
  310. @classmethod
  311. def get_subdirectory(cls, location):
  312. """
  313. Return the path to setup.py, relative to the repo root.
  314. Return None if setup.py is in the repo root.
  315. """
  316. # find the repo root
  317. git_dir = cls.run_command(
  318. ['rev-parse', '--git-dir'],
  319. show_stdout=False,
  320. stdout_only=True,
  321. cwd=location,
  322. ).strip()
  323. if not os.path.isabs(git_dir):
  324. git_dir = os.path.join(location, git_dir)
  325. repo_root = os.path.abspath(os.path.join(git_dir, '..'))
  326. return find_path_to_setup_from_repo_root(location, repo_root)
  327. @classmethod
  328. def get_url_rev_and_auth(cls, url):
  329. # type: (str) -> Tuple[str, Optional[str], AuthInfo]
  330. """
  331. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  332. That's required because although they use SSH they sometimes don't
  333. work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
  334. parsing. Hence we remove it again afterwards and return it as a stub.
  335. """
  336. # Works around an apparent Git bug
  337. # (see https://article.gmane.org/gmane.comp.version-control.git/146500)
  338. scheme, netloc, path, query, fragment = urlsplit(url)
  339. if scheme.endswith('file'):
  340. initial_slashes = path[:-len(path.lstrip('/'))]
  341. newpath = (
  342. initial_slashes +
  343. urllib_request.url2pathname(path)
  344. .replace('\\', '/').lstrip('/')
  345. )
  346. after_plus = scheme.find('+') + 1
  347. url = scheme[:after_plus] + urlunsplit(
  348. (scheme[after_plus:], netloc, newpath, query, fragment),
  349. )
  350. if '://' not in url:
  351. assert 'file:' not in url
  352. url = url.replace('git+', 'git+ssh://')
  353. url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
  354. url = url.replace('ssh://', '')
  355. else:
  356. url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
  357. return url, rev, user_pass
  358. @classmethod
  359. def update_submodules(cls, location):
  360. if not os.path.exists(os.path.join(location, '.gitmodules')):
  361. return
  362. cls.run_command(
  363. ['submodule', 'update', '--init', '--recursive', '-q'],
  364. cwd=location,
  365. )
  366. @classmethod
  367. def get_repository_root(cls, location):
  368. loc = super(Git, cls).get_repository_root(location)
  369. if loc:
  370. return loc
  371. try:
  372. r = cls.run_command(
  373. ['rev-parse', '--show-toplevel'],
  374. cwd=location,
  375. show_stdout=False,
  376. stdout_only=True,
  377. on_returncode='raise',
  378. log_failed_cmd=False,
  379. )
  380. except BadCommand:
  381. logger.debug("could not determine if %s is under git control "
  382. "because git is not available", location)
  383. return None
  384. except InstallationError:
  385. return None
  386. return os.path.normpath(r.rstrip('\r\n'))
  387. vcs.register(Git)