git.py 11 KB

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