subversion.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. # The following comment should be removed at some point in the future.
  2. # mypy: disallow-untyped-defs=False
  3. from __future__ import absolute_import
  4. import logging
  5. import os
  6. import re
  7. from pip._internal.utils.logging import indent_log
  8. from pip._internal.utils.misc import (
  9. display_path,
  10. is_console_interactive,
  11. rmtree,
  12. split_auth_from_netloc,
  13. )
  14. from pip._internal.utils.subprocess import make_command
  15. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  16. from pip._internal.vcs.versioncontrol import VersionControl, vcs
  17. _svn_xml_url_re = re.compile('url="([^"]+)"')
  18. _svn_rev_re = re.compile(r'committed-rev="(\d+)"')
  19. _svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"')
  20. _svn_info_xml_url_re = re.compile(r'<url>(.*)</url>')
  21. if MYPY_CHECK_RUNNING:
  22. from typing import Optional, Tuple
  23. from pip._internal.utils.subprocess import CommandArgs
  24. from pip._internal.utils.misc import HiddenText
  25. from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions
  26. logger = logging.getLogger(__name__)
  27. class Subversion(VersionControl):
  28. name = 'svn'
  29. dirname = '.svn'
  30. repo_name = 'checkout'
  31. schemes = ('svn', 'svn+ssh', 'svn+http', 'svn+https', 'svn+svn')
  32. @classmethod
  33. def should_add_vcs_url_prefix(cls, remote_url):
  34. return True
  35. @staticmethod
  36. def get_base_rev_args(rev):
  37. return ['-r', rev]
  38. @classmethod
  39. def get_revision(cls, location):
  40. """
  41. Return the maximum revision for all files under a given location
  42. """
  43. # Note: taken from setuptools.command.egg_info
  44. revision = 0
  45. for base, dirs, files in os.walk(location):
  46. if cls.dirname not in dirs:
  47. dirs[:] = []
  48. continue # no sense walking uncontrolled subdirs
  49. dirs.remove(cls.dirname)
  50. entries_fn = os.path.join(base, cls.dirname, 'entries')
  51. if not os.path.exists(entries_fn):
  52. # FIXME: should we warn?
  53. continue
  54. dirurl, localrev = cls._get_svn_url_rev(base)
  55. if base == location:
  56. base = dirurl + '/' # save the root url
  57. elif not dirurl or not dirurl.startswith(base):
  58. dirs[:] = []
  59. continue # not part of the same svn tree, skip it
  60. revision = max(revision, localrev)
  61. return revision
  62. @classmethod
  63. def get_netloc_and_auth(cls, netloc, scheme):
  64. """
  65. This override allows the auth information to be passed to svn via the
  66. --username and --password options instead of via the URL.
  67. """
  68. if scheme == 'ssh':
  69. # The --username and --password options can't be used for
  70. # svn+ssh URLs, so keep the auth information in the URL.
  71. return super(Subversion, cls).get_netloc_and_auth(netloc, scheme)
  72. return split_auth_from_netloc(netloc)
  73. @classmethod
  74. def get_url_rev_and_auth(cls, url):
  75. # type: (str) -> Tuple[str, Optional[str], AuthInfo]
  76. # hotfix the URL scheme after removing svn+ from svn+ssh:// readd it
  77. url, rev, user_pass = super(Subversion, cls).get_url_rev_and_auth(url)
  78. if url.startswith('ssh://'):
  79. url = 'svn+' + url
  80. return url, rev, user_pass
  81. @staticmethod
  82. def make_rev_args(username, password):
  83. # type: (Optional[str], Optional[HiddenText]) -> CommandArgs
  84. extra_args = [] # type: CommandArgs
  85. if username:
  86. extra_args += ['--username', username]
  87. if password:
  88. extra_args += ['--password', password]
  89. return extra_args
  90. @classmethod
  91. def get_remote_url(cls, location):
  92. # In cases where the source is in a subdirectory, not alongside
  93. # setup.py we have to look up in the location until we find a real
  94. # setup.py
  95. orig_location = location
  96. while not os.path.exists(os.path.join(location, 'setup.py')):
  97. last_location = location
  98. location = os.path.dirname(location)
  99. if location == last_location:
  100. # We've traversed up to the root of the filesystem without
  101. # finding setup.py
  102. logger.warning(
  103. "Could not find setup.py for directory %s (tried all "
  104. "parent directories)",
  105. orig_location,
  106. )
  107. return None
  108. return cls._get_svn_url_rev(location)[0]
  109. @classmethod
  110. def _get_svn_url_rev(cls, location):
  111. from pip._internal.exceptions import InstallationError
  112. entries_path = os.path.join(location, cls.dirname, 'entries')
  113. if os.path.exists(entries_path):
  114. with open(entries_path) as f:
  115. data = f.read()
  116. else: # subversion >= 1.7 does not have the 'entries' file
  117. data = ''
  118. if (data.startswith('8') or
  119. data.startswith('9') or
  120. data.startswith('10')):
  121. data = list(map(str.splitlines, data.split('\n\x0c\n')))
  122. del data[0][0] # get rid of the '8'
  123. url = data[0][3]
  124. revs = [int(d[9]) for d in data if len(d) > 9 and d[9]] + [0]
  125. elif data.startswith('<?xml'):
  126. match = _svn_xml_url_re.search(data)
  127. if not match:
  128. raise ValueError('Badly formatted data: %r' % data)
  129. url = match.group(1) # get repository URL
  130. revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]
  131. else:
  132. try:
  133. # subversion >= 1.7
  134. # Note that using get_remote_call_options is not necessary here
  135. # because `svn info` is being run against a local directory.
  136. # We don't need to worry about making sure interactive mode
  137. # is being used to prompt for passwords, because passwords
  138. # are only potentially needed for remote server requests.
  139. xml = cls.run_command(
  140. ['info', '--xml', location],
  141. show_stdout=False,
  142. )
  143. url = _svn_info_xml_url_re.search(xml).group(1)
  144. revs = [
  145. int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)
  146. ]
  147. except InstallationError:
  148. url, revs = None, []
  149. if revs:
  150. rev = max(revs)
  151. else:
  152. rev = 0
  153. return url, rev
  154. @classmethod
  155. def is_commit_id_equal(cls, dest, name):
  156. """Always assume the versions don't match"""
  157. return False
  158. def __init__(self, use_interactive=None):
  159. # type: (bool) -> None
  160. if use_interactive is None:
  161. use_interactive = is_console_interactive()
  162. self.use_interactive = use_interactive
  163. # This member is used to cache the fetched version of the current
  164. # ``svn`` client.
  165. # Special value definitions:
  166. # None: Not evaluated yet.
  167. # Empty tuple: Could not parse version.
  168. self._vcs_version = None # type: Optional[Tuple[int, ...]]
  169. super(Subversion, self).__init__()
  170. def call_vcs_version(self):
  171. # type: () -> Tuple[int, ...]
  172. """Query the version of the currently installed Subversion client.
  173. :return: A tuple containing the parts of the version information or
  174. ``()`` if the version returned from ``svn`` could not be parsed.
  175. :raises: BadCommand: If ``svn`` is not installed.
  176. """
  177. # Example versions:
  178. # svn, version 1.10.3 (r1842928)
  179. # compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0
  180. # svn, version 1.7.14 (r1542130)
  181. # compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu
  182. version_prefix = 'svn, version '
  183. version = self.run_command(['--version'], show_stdout=False)
  184. if not version.startswith(version_prefix):
  185. return ()
  186. version = version[len(version_prefix):].split()[0]
  187. version_list = version.split('.')
  188. try:
  189. parsed_version = tuple(map(int, version_list))
  190. except ValueError:
  191. return ()
  192. return parsed_version
  193. def get_vcs_version(self):
  194. # type: () -> Tuple[int, ...]
  195. """Return the version of the currently installed Subversion client.
  196. If the version of the Subversion client has already been queried,
  197. a cached value will be used.
  198. :return: A tuple containing the parts of the version information or
  199. ``()`` if the version returned from ``svn`` could not be parsed.
  200. :raises: BadCommand: If ``svn`` is not installed.
  201. """
  202. if self._vcs_version is not None:
  203. # Use cached version, if available.
  204. # If parsing the version failed previously (empty tuple),
  205. # do not attempt to parse it again.
  206. return self._vcs_version
  207. vcs_version = self.call_vcs_version()
  208. self._vcs_version = vcs_version
  209. return vcs_version
  210. def get_remote_call_options(self):
  211. # type: () -> CommandArgs
  212. """Return options to be used on calls to Subversion that contact the server.
  213. These options are applicable for the following ``svn`` subcommands used
  214. in this class.
  215. - checkout
  216. - export
  217. - switch
  218. - update
  219. :return: A list of command line arguments to pass to ``svn``.
  220. """
  221. if not self.use_interactive:
  222. # --non-interactive switch is available since Subversion 0.14.4.
  223. # Subversion < 1.8 runs in interactive mode by default.
  224. return ['--non-interactive']
  225. svn_version = self.get_vcs_version()
  226. # By default, Subversion >= 1.8 runs in non-interactive mode if
  227. # stdin is not a TTY. Since that is how pip invokes SVN, in
  228. # call_subprocess(), pip must pass --force-interactive to ensure
  229. # the user can be prompted for a password, if required.
  230. # SVN added the --force-interactive option in SVN 1.8. Since
  231. # e.g. RHEL/CentOS 7, which is supported until 2024, ships with
  232. # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip
  233. # can't safely add the option if the SVN version is < 1.8 (or unknown).
  234. if svn_version >= (1, 8):
  235. return ['--force-interactive']
  236. return []
  237. def export(self, location, url):
  238. # type: (str, HiddenText) -> None
  239. """Export the svn repository at the url to the destination location"""
  240. url, rev_options = self.get_url_rev_options(url)
  241. logger.info('Exporting svn repository %s to %s', url, location)
  242. with indent_log():
  243. if os.path.exists(location):
  244. # Subversion doesn't like to check out over an existing
  245. # directory --force fixes this, but was only added in svn 1.5
  246. rmtree(location)
  247. cmd_args = make_command(
  248. 'export', self.get_remote_call_options(),
  249. rev_options.to_args(), url, location,
  250. )
  251. self.run_command(cmd_args, show_stdout=False)
  252. def fetch_new(self, dest, url, rev_options):
  253. # type: (str, HiddenText, RevOptions) -> None
  254. rev_display = rev_options.to_display()
  255. logger.info(
  256. 'Checking out %s%s to %s',
  257. url,
  258. rev_display,
  259. display_path(dest),
  260. )
  261. cmd_args = make_command(
  262. 'checkout', '-q', self.get_remote_call_options(),
  263. rev_options.to_args(), url, dest,
  264. )
  265. self.run_command(cmd_args)
  266. def switch(self, dest, url, rev_options):
  267. # type: (str, HiddenText, RevOptions) -> None
  268. cmd_args = make_command(
  269. 'switch', self.get_remote_call_options(), rev_options.to_args(),
  270. url, dest,
  271. )
  272. self.run_command(cmd_args)
  273. def update(self, dest, url, rev_options):
  274. # type: (str, HiddenText, RevOptions) -> None
  275. cmd_args = make_command(
  276. 'update', self.get_remote_call_options(), rev_options.to_args(),
  277. dest,
  278. )
  279. self.run_command(cmd_args)
  280. vcs.register(Subversion)