PageRenderTime 65ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/teca-env18/lib/python2.7/site-packages/pip/_internal/vcs/git.py

https://github.com/dpritsos/WEGA
Python | 309 lines | 266 code | 23 blank | 20 comment | 15 complexity | 149d9e4a4d452fcf59d3e4ad3333a89c MD5 | raw file
  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 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 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 fetch_new(self, dest, url, rev_options):
  126. rev_display = rev_options.to_display()
  127. logger.info(
  128. 'Cloning %s%s to %s', url, rev_display, display_path(dest),
  129. )
  130. self.run_command(['clone', '-q', url, dest])
  131. if rev_options.rev:
  132. # Then a specific revision was requested.
  133. rev_options = self.check_rev_options(dest, rev_options)
  134. # Only do a checkout if the current commit id doesn't match
  135. # the requested revision.
  136. if not self.is_commit_id_equal(dest, rev_options.rev):
  137. rev = rev_options.rev
  138. # Only fetch the revision if it's a ref
  139. if rev.startswith('refs/'):
  140. self.run_command(
  141. ['fetch', '-q', url] + rev_options.to_args(),
  142. cwd=dest,
  143. )
  144. # Change the revision to the SHA of the ref we fetched
  145. rev = 'FETCH_HEAD'
  146. self.run_command(['checkout', '-q', rev], cwd=dest)
  147. #: repo may contain submodules
  148. self.update_submodules(dest)
  149. def switch(self, dest, url, rev_options):
  150. self.run_command(['config', 'remote.origin.url', url], cwd=dest)
  151. cmd_args = ['checkout', '-q'] + rev_options.to_args()
  152. self.run_command(cmd_args, cwd=dest)
  153. self.update_submodules(dest)
  154. def update(self, dest, rev_options):
  155. # First fetch changes from the default remote
  156. if self.get_git_version() >= parse_version('1.9.0'):
  157. # fetch tags in addition to everything else
  158. self.run_command(['fetch', '-q', '--tags'], cwd=dest)
  159. else:
  160. self.run_command(['fetch', '-q'], cwd=dest)
  161. # Then reset to wanted revision (maybe even origin/master)
  162. rev_options = self.check_rev_options(dest, rev_options)
  163. cmd_args = ['reset', '--hard', '-q'] + rev_options.to_args()
  164. self.run_command(cmd_args, cwd=dest)
  165. #: update submodules
  166. self.update_submodules(dest)
  167. def get_url(self, location):
  168. """Return URL of the first remote encountered."""
  169. remotes = self.run_command(
  170. ['config', '--get-regexp', r'remote\..*\.url'],
  171. show_stdout=False, cwd=location,
  172. )
  173. remotes = remotes.splitlines()
  174. found_remote = remotes[0]
  175. for remote in remotes:
  176. if remote.startswith('remote.origin.url '):
  177. found_remote = remote
  178. break
  179. url = found_remote.split(' ')[1]
  180. return url.strip()
  181. def get_revision(self, location):
  182. current_rev = self.run_command(
  183. ['rev-parse', 'HEAD'], show_stdout=False, cwd=location,
  184. )
  185. return current_rev.strip()
  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, url):
  226. """
  227. Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
  228. That's required because although they use SSH they sometimes don'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 url:
  233. assert 'file:' not in url
  234. url = url.replace('git+', 'git+ssh://')
  235. url, rev = super(Git, self).get_url_rev(url)
  236. url = url.replace('ssh://', '')
  237. else:
  238. url, rev = super(Git, self).get_url_rev(url)
  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)