git.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. from __future__ import absolute_import
  2. import logging
  3. import tempfile
  4. import os.path
  5. from pip.compat import samefile
  6. from pip.exceptions import BadCommand
  7. from pip._vendor.six.moves.urllib import parse as urllib_parse
  8. from pip._vendor.six.moves.urllib import request as urllib_request
  9. from pip._vendor.packaging.version import parse as parse_version
  10. from pip.utils import display_path, rmtree
  11. from pip.vcs import vcs, VersionControl
  12. urlsplit = urllib_parse.urlsplit
  13. urlunsplit = urllib_parse.urlunsplit
  14. logger = logging.getLogger(__name__)
  15. class Git(VersionControl):
  16. name = 'git'
  17. dirname = '.git'
  18. repo_name = 'clone'
  19. schemes = (
  20. 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
  21. )
  22. def __init__(self, url=None, *args, **kwargs):
  23. # Works around an apparent Git bug
  24. # (see http://article.gmane.org/gmane.comp.version-control.git/146500)
  25. if url:
  26. scheme, netloc, path, query, fragment = urlsplit(url)
  27. if scheme.endswith('file'):
  28. initial_slashes = path[:-len(path.lstrip('/'))]
  29. newpath = (
  30. initial_slashes +
  31. urllib_request.url2pathname(path)
  32. .replace('\\', '/').lstrip('/')
  33. )
  34. url = urlunsplit((scheme, netloc, newpath, query, fragment))
  35. after_plus = scheme.find('+') + 1
  36. url = scheme[:after_plus] + urlunsplit(
  37. (scheme[after_plus:], netloc, newpath, query, fragment),
  38. )
  39. super(Git, self).__init__(url, *args, **kwargs)
  40. def get_git_version(self):
  41. VERSION_PFX = 'git version '
  42. version = self.run_command(['version'], show_stdout=False)
  43. if version.startswith(VERSION_PFX):
  44. version = version[len(VERSION_PFX):]
  45. else:
  46. version = ''
  47. # get first 3 positions of the git version becasue
  48. # on windows it is x.y.z.windows.t, and this parses as
  49. # LegacyVersion which always smaller than a Version.
  50. version = '.'.join(version.split('.')[:3])
  51. return parse_version(version)
  52. def export(self, location):
  53. """Export the Git repository at the url to the destination location"""
  54. temp_dir = tempfile.mkdtemp('-export', 'pip-')
  55. self.unpack(temp_dir)
  56. try:
  57. if not location.endswith('/'):
  58. location = location + '/'
  59. self.run_command(
  60. ['checkout-index', '-a', '-f', '--prefix', location],
  61. show_stdout=False, cwd=temp_dir)
  62. finally:
  63. rmtree(temp_dir)
  64. def check_rev_options(self, rev, dest, rev_options):
  65. """Check the revision options before checkout to compensate that tags
  66. and branches may need origin/ as a prefix.
  67. Returns the SHA1 of the branch or tag if found.
  68. """
  69. revisions = self.get_short_refs(dest)
  70. origin_rev = 'origin/%s' % rev
  71. if origin_rev in revisions:
  72. # remote branch
  73. return [revisions[origin_rev]]
  74. elif rev in revisions:
  75. # a local tag or branch name
  76. return [revisions[rev]]
  77. else:
  78. logger.warning(
  79. "Could not find a tag or branch '%s', assuming commit.", rev,
  80. )
  81. return rev_options
  82. def check_version(self, dest, rev_options):
  83. """
  84. Compare the current sha to the ref. ref may be a branch or tag name,
  85. but current rev will always point to a sha. This means that a branch
  86. or tag will never compare as True. So this ultimately only matches
  87. against exact shas.
  88. """
  89. return self.get_revision(dest).startswith(rev_options[0])
  90. def switch(self, dest, url, rev_options):
  91. self.run_command(['config', 'remote.origin.url', url], cwd=dest)
  92. self.run_command(['checkout', '-q'] + rev_options, cwd=dest)
  93. self.update_submodules(dest)
  94. def update(self, dest, rev_options):
  95. # First fetch changes from the default remote
  96. if self.get_git_version() >= parse_version('1.9.0'):
  97. # fetch tags in addition to everything else
  98. self.run_command(['fetch', '-q', '--tags'], cwd=dest)
  99. else:
  100. self.run_command(['fetch', '-q'], cwd=dest)
  101. # Then reset to wanted revision (maybe even origin/master)
  102. if rev_options:
  103. rev_options = self.check_rev_options(
  104. rev_options[0], dest, rev_options,
  105. )
  106. self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest)
  107. #: update submodules
  108. self.update_submodules(dest)
  109. def obtain(self, dest):
  110. url, rev = self.get_url_rev()
  111. if rev:
  112. rev_options = [rev]
  113. rev_display = ' (to %s)' % rev
  114. else:
  115. rev_options = ['origin/master']
  116. rev_display = ''
  117. if self.check_destination(dest, url, rev_options, rev_display):
  118. logger.info(
  119. 'Cloning %s%s to %s', url, rev_display, display_path(dest),
  120. )
  121. self.run_command(['clone', '-q', url, dest])
  122. if rev:
  123. rev_options = self.check_rev_options(rev, dest, rev_options)
  124. # Only do a checkout if rev_options differs from HEAD
  125. if not self.check_version(dest, rev_options):
  126. self.run_command(
  127. ['checkout', '-q'] + rev_options,
  128. cwd=dest,
  129. )
  130. #: repo may contain submodules
  131. self.update_submodules(dest)
  132. def get_url(self, location):
  133. """Return URL of the first remote encountered."""
  134. remotes = self.run_command(
  135. ['config', '--get-regexp', 'remote\..*\.url'],
  136. show_stdout=False, cwd=location)
  137. remotes = remotes.splitlines()
  138. found_remote = remotes[0]
  139. for remote in remotes:
  140. if remote.startswith('remote.origin.url '):
  141. found_remote = remote
  142. break
  143. url = found_remote.split(' ')[1]
  144. return url.strip()
  145. def get_revision(self, location):
  146. current_rev = self.run_command(
  147. ['rev-parse', 'HEAD'], show_stdout=False, cwd=location)
  148. return current_rev.strip()
  149. def get_full_refs(self, location):
  150. """Yields tuples of (commit, ref) for branches and tags"""
  151. output = self.run_command(['show-ref'],
  152. show_stdout=False, cwd=location)
  153. for line in output.strip().splitlines():
  154. commit, ref = line.split(' ', 1)
  155. yield commit.strip(), ref.strip()
  156. def is_ref_remote(self, ref):
  157. return ref.startswith('refs/remotes/')
  158. def is_ref_branch(self, ref):
  159. return ref.startswith('refs/heads/')
  160. def is_ref_tag(self, ref):
  161. return ref.startswith('refs/tags/')
  162. def is_ref_commit(self, ref):
  163. """A ref is a commit sha if it is not anything else"""
  164. return not any((
  165. self.is_ref_remote(ref),
  166. self.is_ref_branch(ref),
  167. self.is_ref_tag(ref),
  168. ))
  169. # Should deprecate `get_refs` since it's ambiguous
  170. def get_refs(self, location):
  171. return self.get_short_refs(location)
  172. def get_short_refs(self, location):
  173. """Return map of named refs (branches or tags) to commit hashes."""
  174. rv = {}
  175. for commit, ref in self.get_full_refs(location):
  176. ref_name = None
  177. if self.is_ref_remote(ref):
  178. ref_name = ref[len('refs/remotes/'):]
  179. elif self.is_ref_branch(ref):
  180. ref_name = ref[len('refs/heads/'):]
  181. elif self.is_ref_tag(ref):
  182. ref_name = ref[len('refs/tags/'):]
  183. if ref_name is not None:
  184. rv[ref_name] = commit
  185. return rv
  186. def _get_subdirectory(self, location):
  187. """Return the relative path of setup.py to the git repo root."""
  188. # find the repo root
  189. git_dir = self.run_command(['rev-parse', '--git-dir'],
  190. show_stdout=False, cwd=location).strip()
  191. if not os.path.isabs(git_dir):
  192. git_dir = os.path.join(location, git_dir)
  193. root_dir = os.path.join(git_dir, '..')
  194. # find setup.py
  195. orig_location = location
  196. while not os.path.exists(os.path.join(location, 'setup.py')):
  197. last_location = location
  198. location = os.path.dirname(location)
  199. if location == last_location:
  200. # We've traversed up to the root of the filesystem without
  201. # finding setup.py
  202. logger.warning(
  203. "Could not find setup.py for directory %s (tried all "
  204. "parent directories)",
  205. orig_location,
  206. )
  207. return None
  208. # relative path of setup.py to repo root
  209. if samefile(root_dir, location):
  210. return None
  211. return os.path.relpath(location, root_dir)
  212. def get_src_requirement(self, dist, location):
  213. repo = self.get_url(location)
  214. if not repo.lower().startswith('git:'):
  215. repo = 'git+' + repo
  216. egg_project_name = dist.egg_name().split('-', 1)[0]
  217. if not repo:
  218. return None
  219. current_rev = self.get_revision(location)
  220. req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name)
  221. subdirectory = self._get_subdirectory(location)
  222. if subdirectory:
  223. req += '&subdirectory=' + subdirectory
  224. return req
  225. def get_url_rev(self):
  226. """
  227. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  228. That's required because although they use SSH they sometimes doesn't
  229. work with a ssh:// scheme (e.g. Github). But we need a scheme for
  230. parsing. Hence we remove it again afterwards and return it as a stub.
  231. """
  232. if '://' not in self.url:
  233. assert 'file:' not in self.url
  234. self.url = self.url.replace('git+', 'git+ssh://')
  235. url, rev = super(Git, self).get_url_rev()
  236. url = url.replace('ssh://', '')
  237. else:
  238. url, rev = super(Git, self).get_url_rev()
  239. return url, rev
  240. def update_submodules(self, location):
  241. if not os.path.exists(os.path.join(location, '.gitmodules')):
  242. return
  243. self.run_command(
  244. ['submodule', 'update', '--init', '--recursive', '-q'],
  245. cwd=location,
  246. )
  247. @classmethod
  248. def controls_location(cls, location):
  249. if super(Git, cls).controls_location(location):
  250. return True
  251. try:
  252. r = cls().run_command(['rev-parse'],
  253. cwd=location,
  254. show_stdout=False,
  255. on_returncode='ignore')
  256. return not r
  257. except BadCommand:
  258. logger.debug("could not determine if %s is under git control "
  259. "because git is not available", location)
  260. return False
  261. vcs.register(Git)