subversion.py 12 KB

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