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.
 
 
 
 

210 lines
7.4 KiB

  1. from __future__ import absolute_import
  2. import logging
  3. import tempfile
  4. import os.path
  5. from pip._vendor.six.moves.urllib import parse as urllib_parse
  6. from pip._vendor.six.moves.urllib import request as urllib_request
  7. from pip.utils import display_path, rmtree
  8. from pip.vcs import vcs, VersionControl
  9. urlsplit = urllib_parse.urlsplit
  10. urlunsplit = urllib_parse.urlunsplit
  11. logger = logging.getLogger(__name__)
  12. class Git(VersionControl):
  13. name = 'git'
  14. dirname = '.git'
  15. repo_name = 'clone'
  16. schemes = (
  17. 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
  18. )
  19. def __init__(self, url=None, *args, **kwargs):
  20. # Works around an apparent Git bug
  21. # (see http://article.gmane.org/gmane.comp.version-control.git/146500)
  22. if url:
  23. scheme, netloc, path, query, fragment = urlsplit(url)
  24. if scheme.endswith('file'):
  25. initial_slashes = path[:-len(path.lstrip('/'))]
  26. newpath = (
  27. initial_slashes +
  28. urllib_request.url2pathname(path)
  29. .replace('\\', '/').lstrip('/')
  30. )
  31. url = urlunsplit((scheme, netloc, newpath, query, fragment))
  32. after_plus = scheme.find('+') + 1
  33. url = scheme[:after_plus] + urlunsplit(
  34. (scheme[after_plus:], netloc, newpath, query, fragment),
  35. )
  36. super(Git, self).__init__(url, *args, **kwargs)
  37. def export(self, location):
  38. """Export the Git repository at the url to the destination location"""
  39. temp_dir = tempfile.mkdtemp('-export', 'pip-')
  40. self.unpack(temp_dir)
  41. try:
  42. if not location.endswith('/'):
  43. location = location + '/'
  44. self.run_command(
  45. ['checkout-index', '-a', '-f', '--prefix', location],
  46. show_stdout=False, cwd=temp_dir)
  47. finally:
  48. rmtree(temp_dir)
  49. def check_rev_options(self, rev, dest, rev_options):
  50. """Check the revision options before checkout to compensate that tags
  51. and branches may need origin/ as a prefix.
  52. Returns the SHA1 of the branch or tag if found.
  53. """
  54. revisions = self.get_refs(dest)
  55. origin_rev = 'origin/%s' % rev
  56. if origin_rev in revisions:
  57. # remote branch
  58. return [revisions[origin_rev]]
  59. elif rev in revisions:
  60. # a local tag or branch name
  61. return [revisions[rev]]
  62. else:
  63. logger.warning(
  64. "Could not find a tag or branch '%s', assuming commit.", rev,
  65. )
  66. return rev_options
  67. def switch(self, dest, url, rev_options):
  68. self.run_command(['config', 'remote.origin.url', url], cwd=dest)
  69. self.run_command(['checkout', '-q'] + rev_options, cwd=dest)
  70. self.update_submodules(dest)
  71. def update(self, dest, rev_options):
  72. # First fetch changes from the default remote
  73. self.run_command(['fetch', '-q'], cwd=dest)
  74. # Then reset to wanted revision (maby even origin/master)
  75. if rev_options:
  76. rev_options = self.check_rev_options(
  77. rev_options[0], dest, rev_options,
  78. )
  79. self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest)
  80. #: update submodules
  81. self.update_submodules(dest)
  82. def obtain(self, dest):
  83. url, rev = self.get_url_rev()
  84. if rev:
  85. rev_options = [rev]
  86. rev_display = ' (to %s)' % rev
  87. else:
  88. rev_options = ['origin/master']
  89. rev_display = ''
  90. if self.check_destination(dest, url, rev_options, rev_display):
  91. logger.info(
  92. 'Cloning %s%s to %s', url, rev_display, display_path(dest),
  93. )
  94. self.run_command(['clone', '-q', url, dest])
  95. if rev:
  96. rev_options = self.check_rev_options(rev, dest, rev_options)
  97. # Only do a checkout if rev_options differs from HEAD
  98. if not self.get_revision(dest).startswith(rev_options[0]):
  99. self.run_command(
  100. ['checkout', '-q'] + rev_options,
  101. cwd=dest,
  102. )
  103. #: repo may contain submodules
  104. self.update_submodules(dest)
  105. def get_url(self, location):
  106. url = self.run_command(
  107. ['config', 'remote.origin.url'],
  108. show_stdout=False, cwd=location)
  109. return url.strip()
  110. def get_revision(self, location):
  111. current_rev = self.run_command(
  112. ['rev-parse', 'HEAD'], show_stdout=False, cwd=location)
  113. return current_rev.strip()
  114. def get_refs(self, location):
  115. """Return map of named refs (branches or tags) to commit hashes."""
  116. output = self.run_command(['show-ref'],
  117. show_stdout=False, cwd=location)
  118. rv = {}
  119. for line in output.strip().splitlines():
  120. commit, ref = line.split(' ', 1)
  121. ref = ref.strip()
  122. ref_name = None
  123. if ref.startswith('refs/remotes/'):
  124. ref_name = ref[len('refs/remotes/'):]
  125. elif ref.startswith('refs/heads/'):
  126. ref_name = ref[len('refs/heads/'):]
  127. elif ref.startswith('refs/tags/'):
  128. ref_name = ref[len('refs/tags/'):]
  129. if ref_name is not None:
  130. rv[ref_name] = commit.strip()
  131. return rv
  132. def get_src_requirement(self, dist, location, find_tags):
  133. repo = self.get_url(location)
  134. if not repo.lower().startswith('git:'):
  135. repo = 'git+' + repo
  136. egg_project_name = dist.egg_name().split('-', 1)[0]
  137. if not repo:
  138. return None
  139. current_rev = self.get_revision(location)
  140. refs = self.get_refs(location)
  141. # refs maps names to commit hashes; we need the inverse
  142. # if multiple names map to a single commit, we pick the first one
  143. # alphabetically
  144. names_by_commit = {}
  145. for ref, commit in sorted(refs.items()):
  146. if commit not in names_by_commit:
  147. names_by_commit[commit] = ref
  148. if current_rev in names_by_commit:
  149. # It's a tag or branch.
  150. name = names_by_commit[current_rev]
  151. full_egg_name = (
  152. '%s-%s' % (egg_project_name, self.translate_egg_surname(name))
  153. )
  154. else:
  155. full_egg_name = '%s-dev' % egg_project_name
  156. return '%s@%s#egg=%s' % (repo, current_rev, full_egg_name)
  157. def get_url_rev(self):
  158. """
  159. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  160. That's required because although they use SSH they sometimes doesn't
  161. work with a ssh:// scheme (e.g. Github). But we need a scheme for
  162. parsing. Hence we remove it again afterwards and return it as a stub.
  163. """
  164. if '://' not in self.url:
  165. assert 'file:' not in self.url
  166. self.url = self.url.replace('git+', 'git+ssh://')
  167. url, rev = super(Git, self).get_url_rev()
  168. url = url.replace('ssh://', '')
  169. else:
  170. url, rev = super(Git, self).get_url_rev()
  171. return url, rev
  172. def update_submodules(self, location):
  173. if not os.path.exists(os.path.join(location, '.gitmodules')):
  174. return
  175. self.run_command(
  176. ['submodule', 'update', '--init', '--recursive', '-q'],
  177. cwd=location,
  178. )
  179. vcs.register(Git)