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.

346 lines
12 KiB

4 years ago
  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 display_path, make_vcs_requirement_url
  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 https://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 get_branch(self, location):
  63. """
  64. Return the current branch, or None if HEAD isn't at a branch
  65. (e.g. detached HEAD).
  66. """
  67. args = ['rev-parse', '--abbrev-ref', 'HEAD']
  68. output = self.run_command(args, show_stdout=False, cwd=location)
  69. branch = output.strip()
  70. if branch == 'HEAD':
  71. return None
  72. return branch
  73. def export(self, location):
  74. """Export the Git repository at the url to the destination location"""
  75. if not location.endswith('/'):
  76. location = location + '/'
  77. with TempDirectory(kind="export") as temp_dir:
  78. self.unpack(temp_dir.path)
  79. self.run_command(
  80. ['checkout-index', '-a', '-f', '--prefix', location],
  81. show_stdout=False, cwd=temp_dir.path
  82. )
  83. def get_revision_sha(self, dest, rev):
  84. """
  85. Return (sha_or_none, is_branch), where sha_or_none is a commit hash
  86. if the revision names a remote branch or tag, otherwise None.
  87. Args:
  88. dest: the repository directory.
  89. rev: the revision name.
  90. """
  91. # Pass rev to pre-filter the list.
  92. output = self.run_command(['show-ref', rev], cwd=dest,
  93. show_stdout=False, on_returncode='ignore')
  94. refs = {}
  95. for line in output.strip().splitlines():
  96. try:
  97. sha, ref = line.split()
  98. except ValueError:
  99. # Include the offending line to simplify troubleshooting if
  100. # this error ever occurs.
  101. raise ValueError('unexpected show-ref line: {!r}'.format(line))
  102. refs[ref] = sha
  103. branch_ref = 'refs/remotes/origin/{}'.format(rev)
  104. tag_ref = 'refs/tags/{}'.format(rev)
  105. sha = refs.get(branch_ref)
  106. if sha is not None:
  107. return (sha, True)
  108. sha = refs.get(tag_ref)
  109. return (sha, False)
  110. def resolve_revision(self, dest, url, rev_options):
  111. """
  112. Resolve a revision to a new RevOptions object with the SHA1 of the
  113. branch, tag, or ref if found.
  114. Args:
  115. rev_options: a RevOptions object.
  116. """
  117. rev = rev_options.arg_rev
  118. sha, is_branch = self.get_revision_sha(dest, rev)
  119. if sha is not None:
  120. rev_options = rev_options.make_new(sha)
  121. rev_options.branch_name = rev if is_branch else None
  122. return rev_options
  123. # Do not show a warning for the common case of something that has
  124. # the form of a Git commit hash.
  125. if not looks_like_hash(rev):
  126. logger.warning(
  127. "Did not find branch or tag '%s', assuming revision or ref.",
  128. rev,
  129. )
  130. if not rev.startswith('refs/'):
  131. return rev_options
  132. # If it looks like a ref, we have to fetch it explicitly.
  133. self.run_command(
  134. ['fetch', '-q', url] + rev_options.to_args(),
  135. cwd=dest,
  136. )
  137. # Change the revision to the SHA of the ref we fetched
  138. sha = self.get_revision(dest, rev='FETCH_HEAD')
  139. rev_options = rev_options.make_new(sha)
  140. return rev_options
  141. def is_commit_id_equal(self, dest, name):
  142. """
  143. Return whether the current commit hash equals the given name.
  144. Args:
  145. dest: the repository directory.
  146. name: a string name.
  147. """
  148. if not name:
  149. # Then avoid an unnecessary subprocess call.
  150. return False
  151. return self.get_revision(dest) == name
  152. def fetch_new(self, dest, url, rev_options):
  153. rev_display = rev_options.to_display()
  154. logger.info(
  155. 'Cloning %s%s to %s', url, rev_display, display_path(dest),
  156. )
  157. self.run_command(['clone', '-q', url, dest])
  158. if rev_options.rev:
  159. # Then a specific revision was requested.
  160. rev_options = self.resolve_revision(dest, url, rev_options)
  161. branch_name = getattr(rev_options, 'branch_name', None)
  162. if branch_name is None:
  163. # Only do a checkout if the current commit id doesn't match
  164. # the requested revision.
  165. if not self.is_commit_id_equal(dest, rev_options.rev):
  166. cmd_args = ['checkout', '-q'] + rev_options.to_args()
  167. self.run_command(cmd_args, cwd=dest)
  168. elif self.get_branch(dest) != branch_name:
  169. # Then a specific branch was requested, and that branch
  170. # is not yet checked out.
  171. track_branch = 'origin/{}'.format(branch_name)
  172. cmd_args = [
  173. 'checkout', '-b', branch_name, '--track', track_branch,
  174. ]
  175. self.run_command(cmd_args, cwd=dest)
  176. #: repo may contain submodules
  177. self.update_submodules(dest)
  178. def switch(self, dest, url, rev_options):
  179. self.run_command(['config', 'remote.origin.url', url], cwd=dest)
  180. cmd_args = ['checkout', '-q'] + rev_options.to_args()
  181. self.run_command(cmd_args, cwd=dest)
  182. self.update_submodules(dest)
  183. def update(self, dest, url, rev_options):
  184. # First fetch changes from the default remote
  185. if self.get_git_version() >= parse_version('1.9.0'):
  186. # fetch tags in addition to everything else
  187. self.run_command(['fetch', '-q', '--tags'], cwd=dest)
  188. else:
  189. self.run_command(['fetch', '-q'], cwd=dest)
  190. # Then reset to wanted revision (maybe even origin/master)
  191. rev_options = self.resolve_revision(dest, url, rev_options)
  192. cmd_args = ['reset', '--hard', '-q'] + rev_options.to_args()
  193. self.run_command(cmd_args, cwd=dest)
  194. #: update submodules
  195. self.update_submodules(dest)
  196. def get_url(self, location):
  197. """Return URL of the first remote encountered."""
  198. remotes = self.run_command(
  199. ['config', '--get-regexp', r'remote\..*\.url'],
  200. show_stdout=False, cwd=location,
  201. )
  202. remotes = remotes.splitlines()
  203. found_remote = remotes[0]
  204. for remote in remotes:
  205. if remote.startswith('remote.origin.url '):
  206. found_remote = remote
  207. break
  208. url = found_remote.split(' ')[1]
  209. return url.strip()
  210. def get_revision(self, location, rev=None):
  211. if rev is None:
  212. rev = 'HEAD'
  213. current_rev = self.run_command(
  214. ['rev-parse', rev], show_stdout=False, cwd=location,
  215. )
  216. return current_rev.strip()
  217. def _get_subdirectory(self, location):
  218. """Return the relative path of setup.py to the git repo root."""
  219. # find the repo root
  220. git_dir = self.run_command(['rev-parse', '--git-dir'],
  221. show_stdout=False, cwd=location).strip()
  222. if not os.path.isabs(git_dir):
  223. git_dir = os.path.join(location, git_dir)
  224. root_dir = os.path.join(git_dir, '..')
  225. # find setup.py
  226. orig_location = location
  227. while not os.path.exists(os.path.join(location, 'setup.py')):
  228. last_location = location
  229. location = os.path.dirname(location)
  230. if location == last_location:
  231. # We've traversed up to the root of the filesystem without
  232. # finding setup.py
  233. logger.warning(
  234. "Could not find setup.py for directory %s (tried all "
  235. "parent directories)",
  236. orig_location,
  237. )
  238. return None
  239. # relative path of setup.py to repo root
  240. if samefile(root_dir, location):
  241. return None
  242. return os.path.relpath(location, root_dir)
  243. def get_src_requirement(self, dist, location):
  244. repo = self.get_url(location)
  245. if not repo.lower().startswith('git:'):
  246. repo = 'git+' + repo
  247. current_rev = self.get_revision(location)
  248. egg_project_name = dist.egg_name().split('-', 1)[0]
  249. subdir = self._get_subdirectory(location)
  250. req = make_vcs_requirement_url(repo, current_rev, egg_project_name,
  251. subdir=subdir)
  252. return req
  253. def get_url_rev_and_auth(self, url):
  254. """
  255. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  256. That's required because although they use SSH they sometimes don't
  257. work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
  258. parsing. Hence we remove it again afterwards and return it as a stub.
  259. """
  260. if '://' not in url:
  261. assert 'file:' not in url
  262. url = url.replace('git+', 'git+ssh://')
  263. url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
  264. url = url.replace('ssh://', '')
  265. else:
  266. url, rev, user_pass = super(Git, self).get_url_rev_and_auth(url)
  267. return url, rev, user_pass
  268. def update_submodules(self, location):
  269. if not os.path.exists(os.path.join(location, '.gitmodules')):
  270. return
  271. self.run_command(
  272. ['submodule', 'update', '--init', '--recursive', '-q'],
  273. cwd=location,
  274. )
  275. @classmethod
  276. def controls_location(cls, location):
  277. if super(Git, cls).controls_location(location):
  278. return True
  279. try:
  280. r = cls().run_command(['rev-parse'],
  281. cwd=location,
  282. show_stdout=False,
  283. on_returncode='ignore')
  284. return not r
  285. except BadCommand:
  286. logger.debug("could not determine if %s is under git control "
  287. "because git is not available", location)
  288. return False
  289. vcs.register(Git)