You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

git.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. from __future__ import absolute_import
  2. import logging
  3. import os.path
  4. import re
  5. from pip._vendor.packaging.version import parse as parse_version
  6. from pip._vendor.six.moves.urllib import parse as urllib_parse
  7. from pip._vendor.six.moves.urllib import request as urllib_request
  8. from pip._internal.exceptions import BadCommand
  9. from pip._internal.utils.compat import samefile
  10. from pip._internal.utils.misc import (
  11. display_path, make_vcs_requirement_url, redact_password_from_url,
  12. )
  13. from pip._internal.utils.temp_dir import TempDirectory
  14. from pip._internal.vcs import RemoteNotFoundError, VersionControl, vcs
  15. urlsplit = urllib_parse.urlsplit
  16. urlunsplit = urllib_parse.urlunsplit
  17. logger = logging.getLogger(__name__)
  18. HASH_REGEX = re.compile('[a-fA-F0-9]{40}')
  19. def looks_like_hash(sha):
  20. return bool(HASH_REGEX.match(sha))
  21. class Git(VersionControl):
  22. name = 'git'
  23. dirname = '.git'
  24. repo_name = 'clone'
  25. schemes = (
  26. 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
  27. )
  28. # Prevent the user's environment variables from interfering with pip:
  29. # https://github.com/pypa/pip/issues/1130
  30. unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')
  31. default_arg_rev = 'HEAD'
  32. def __init__(self, url=None, *args, **kwargs):
  33. # Works around an apparent Git bug
  34. # (see https://article.gmane.org/gmane.comp.version-control.git/146500)
  35. if url:
  36. scheme, netloc, path, query, fragment = urlsplit(url)
  37. if scheme.endswith('file'):
  38. initial_slashes = path[:-len(path.lstrip('/'))]
  39. newpath = (
  40. initial_slashes +
  41. urllib_request.url2pathname(path)
  42. .replace('\\', '/').lstrip('/')
  43. )
  44. url = urlunsplit((scheme, netloc, newpath, query, fragment))
  45. after_plus = scheme.find('+') + 1
  46. url = scheme[:after_plus] + urlunsplit(
  47. (scheme[after_plus:], netloc, newpath, query, fragment),
  48. )
  49. super(Git, self).__init__(url, *args, **kwargs)
  50. def get_base_rev_args(self, rev):
  51. return [rev]
  52. def get_git_version(self):
  53. VERSION_PFX = 'git version '
  54. version = self.run_command(['version'], show_stdout=False)
  55. if version.startswith(VERSION_PFX):
  56. version = version[len(VERSION_PFX):].split()[0]
  57. else:
  58. version = ''
  59. # get first 3 positions of the git version becasue
  60. # on windows it is x.y.z.windows.t, and this parses as
  61. # LegacyVersion which always smaller than a Version.
  62. version = '.'.join(version.split('.')[:3])
  63. return parse_version(version)
  64. def get_current_branch(self, location):
  65. """
  66. Return the current branch, or None if HEAD isn't at a branch
  67. (e.g. detached HEAD).
  68. """
  69. # git-symbolic-ref exits with empty stdout if "HEAD" is a detached
  70. # HEAD rather than a symbolic ref. In addition, the -q causes the
  71. # command to exit with status code 1 instead of 128 in this case
  72. # and to suppress the message to stderr.
  73. args = ['symbolic-ref', '-q', 'HEAD']
  74. output = self.run_command(
  75. args, extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
  76. )
  77. ref = output.strip()
  78. if ref.startswith('refs/heads/'):
  79. return ref[len('refs/heads/'):]
  80. return None
  81. def export(self, location):
  82. """Export the Git repository at the url to the destination location"""
  83. if not location.endswith('/'):
  84. location = location + '/'
  85. with TempDirectory(kind="export") as temp_dir:
  86. self.unpack(temp_dir.path)
  87. self.run_command(
  88. ['checkout-index', '-a', '-f', '--prefix', location],
  89. show_stdout=False, cwd=temp_dir.path
  90. )
  91. def get_revision_sha(self, dest, rev):
  92. """
  93. Return (sha_or_none, is_branch), where sha_or_none is a commit hash
  94. if the revision names a remote branch or tag, otherwise None.
  95. Args:
  96. dest: the repository directory.
  97. rev: the revision name.
  98. """
  99. # Pass rev to pre-filter the list.
  100. output = self.run_command(['show-ref', rev], cwd=dest,
  101. show_stdout=False, on_returncode='ignore')
  102. refs = {}
  103. for line in output.strip().splitlines():
  104. try:
  105. sha, ref = line.split()
  106. except ValueError:
  107. # Include the offending line to simplify troubleshooting if
  108. # this error ever occurs.
  109. raise ValueError('unexpected show-ref line: {!r}'.format(line))
  110. refs[ref] = sha
  111. branch_ref = 'refs/remotes/origin/{}'.format(rev)
  112. tag_ref = 'refs/tags/{}'.format(rev)
  113. sha = refs.get(branch_ref)
  114. if sha is not None:
  115. return (sha, True)
  116. sha = refs.get(tag_ref)
  117. return (sha, False)
  118. def resolve_revision(self, dest, url, rev_options):
  119. """
  120. Resolve a revision to a new RevOptions object with the SHA1 of the
  121. branch, tag, or ref if found.
  122. Args:
  123. rev_options: a RevOptions object.
  124. """
  125. rev = rev_options.arg_rev
  126. sha, is_branch = self.get_revision_sha(dest, rev)
  127. if sha is not None:
  128. rev_options = rev_options.make_new(sha)
  129. rev_options.branch_name = rev if is_branch else None
  130. return rev_options
  131. # Do not show a warning for the common case of something that has
  132. # the form of a Git commit hash.
  133. if not looks_like_hash(rev):
  134. logger.warning(
  135. "Did not find branch or tag '%s', assuming revision or ref.",
  136. rev,
  137. )
  138. if not rev.startswith('refs/'):
  139. return rev_options
  140. # If it looks like a ref, we have to fetch it explicitly.
  141. self.run_command(
  142. ['fetch', '-q', url] + rev_options.to_args(),
  143. cwd=dest,
  144. )
  145. # Change the revision to the SHA of the ref we fetched
  146. sha = self.get_revision(dest, rev='FETCH_HEAD')
  147. rev_options = rev_options.make_new(sha)
  148. return rev_options
  149. def is_commit_id_equal(self, dest, name):
  150. """
  151. Return whether the current commit hash equals the given name.
  152. Args:
  153. dest: the repository directory.
  154. name: a string name.
  155. """
  156. if not name:
  157. # Then avoid an unnecessary subprocess call.
  158. return False
  159. return self.get_revision(dest) == name
  160. def fetch_new(self, dest, url, rev_options):
  161. rev_display = rev_options.to_display()
  162. logger.info(
  163. 'Cloning %s%s to %s', redact_password_from_url(url),
  164. rev_display, display_path(dest),
  165. )
  166. self.run_command(['clone', '-q', url, dest])
  167. if rev_options.rev:
  168. # Then a specific revision was requested.
  169. rev_options = self.resolve_revision(dest, url, rev_options)
  170. branch_name = getattr(rev_options, 'branch_name', None)
  171. if branch_name is None:
  172. # Only do a checkout if the current commit id doesn't match
  173. # the requested revision.
  174. if not self.is_commit_id_equal(dest, rev_options.rev):
  175. cmd_args = ['checkout', '-q'] + rev_options.to_args()
  176. self.run_command(cmd_args, cwd=dest)
  177. elif self.get_current_branch(dest) != branch_name:
  178. # Then a specific branch was requested, and that branch
  179. # is not yet checked out.
  180. track_branch = 'origin/{}'.format(branch_name)
  181. cmd_args = [
  182. 'checkout', '-b', branch_name, '--track', track_branch,
  183. ]
  184. self.run_command(cmd_args, cwd=dest)
  185. #: repo may contain submodules
  186. self.update_submodules(dest)
  187. def switch(self, dest, url, rev_options):
  188. self.run_command(['config', 'remote.origin.url', url], cwd=dest)
  189. cmd_args = ['checkout', '-q'] + rev_options.to_args()
  190. self.run_command(cmd_args, cwd=dest)
  191. self.update_submodules(dest)
  192. def update(self, dest, url, rev_options):
  193. # First fetch changes from the default remote
  194. if self.get_git_version() >= parse_version('1.9.0'):
  195. # fetch tags in addition to everything else
  196. self.run_command(['fetch', '-q', '--tags'], cwd=dest)
  197. else:
  198. self.run_command(['fetch', '-q'], cwd=dest)
  199. # Then reset to wanted revision (maybe even origin/master)
  200. rev_options = self.resolve_revision(dest, url, rev_options)
  201. cmd_args = ['reset', '--hard', '-q'] + rev_options.to_args()
  202. self.run_command(cmd_args, cwd=dest)
  203. #: update submodules
  204. self.update_submodules(dest)
  205. @classmethod
  206. def get_remote_url(cls, location):
  207. """
  208. Return URL of the first remote encountered.
  209. Raises RemoteNotFoundError if the repository does not have a remote
  210. url configured.
  211. """
  212. # We need to pass 1 for extra_ok_returncodes since the command
  213. # exits with return code 1 if there are no matching lines.
  214. stdout = cls.run_command(
  215. ['config', '--get-regexp', r'remote\..*\.url'],
  216. extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
  217. )
  218. remotes = stdout.splitlines()
  219. try:
  220. found_remote = remotes[0]
  221. except IndexError:
  222. raise RemoteNotFoundError
  223. for remote in remotes:
  224. if remote.startswith('remote.origin.url '):
  225. found_remote = remote
  226. break
  227. url = found_remote.split(' ')[1]
  228. return url.strip()
  229. @classmethod
  230. def get_revision(cls, location, rev=None):
  231. if rev is None:
  232. rev = 'HEAD'
  233. current_rev = cls.run_command(
  234. ['rev-parse', rev], show_stdout=False, cwd=location,
  235. )
  236. return current_rev.strip()
  237. @classmethod
  238. def _get_subdirectory(cls, location):
  239. """Return the relative path of setup.py to the git repo root."""
  240. # find the repo root
  241. git_dir = cls.run_command(['rev-parse', '--git-dir'],
  242. show_stdout=False, cwd=location).strip()
  243. if not os.path.isabs(git_dir):
  244. git_dir = os.path.join(location, git_dir)
  245. root_dir = os.path.join(git_dir, '..')
  246. # find setup.py
  247. orig_location = location
  248. while not os.path.exists(os.path.join(location, 'setup.py')):
  249. last_location = location
  250. location = os.path.dirname(location)
  251. if location == last_location:
  252. # We've traversed up to the root of the filesystem without
  253. # finding setup.py
  254. logger.warning(
  255. "Could not find setup.py for directory %s (tried all "
  256. "parent directories)",
  257. orig_location,
  258. )
  259. return None
  260. # relative path of setup.py to repo root
  261. if samefile(root_dir, location):
  262. return None
  263. return os.path.relpath(location, root_dir)
  264. @classmethod
  265. def get_src_requirement(cls, location, project_name):
  266. repo = cls.get_remote_url(location)
  267. if not repo.lower().startswith('git:'):
  268. repo = 'git+' + repo
  269. current_rev = cls.get_revision(location)
  270. subdir = cls._get_subdirectory(location)
  271. req = make_vcs_requirement_url(repo, current_rev, project_name,
  272. subdir=subdir)
  273. return req
  274. def get_url_rev_and_auth(self, url):
  275. """
  276. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  277. That's required because although they use SSH they sometimes don't
  278. work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
  279. parsing. Hence we remove it again afterwards and return it as a stub.
  280. """
  281. if '://' not in url:
  282. assert 'file:' not in url
  283. url = url.replace('git+', 'git+ssh://')
  284. url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
  285. url = url.replace('ssh://', '')
  286. else:
  287. url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
  288. return url, rev, user_pass
  289. def update_submodules(self, location):
  290. if not os.path.exists(os.path.join(location, '.gitmodules')):
  291. return
  292. self.run_command(
  293. ['submodule', 'update', '--init', '--recursive', '-q'],
  294. cwd=location,
  295. )
  296. @classmethod
  297. def controls_location(cls, location):
  298. if super(Git, cls).controls_location(location):
  299. return True
  300. try:
  301. r = cls.run_command(['rev-parse'],
  302. cwd=location,
  303. show_stdout=False,
  304. on_returncode='ignore')
  305. return not r
  306. except BadCommand:
  307. logger.debug("could not determine if %s is under git control "
  308. "because git is not available", location)
  309. return False
  310. vcs.register(Git)