PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/pip/vcs/subversion.py

https://github.com/ptthiem/pip
Python | 273 lines | 222 code | 29 blank | 22 comment | 61 complexity | 32038f67b187439b225db957e7911a43 MD5 | raw file
  1. import os
  2. import re
  3. from pip.backwardcompat import urlparse
  4. from pip.index import Link
  5. from pip.util import rmtree, display_path, call_subprocess
  6. from pip.log import logger
  7. from pip.vcs import vcs, VersionControl
  8. _svn_xml_url_re = re.compile('url="([^"]+)"')
  9. _svn_rev_re = re.compile('committed-rev="(\d+)"')
  10. _svn_url_re = re.compile(r'URL: (.+)')
  11. _svn_revision_re = re.compile(r'Revision: (.+)')
  12. _svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"')
  13. _svn_info_xml_url_re = re.compile(r'<url>(.*)</url>')
  14. class Subversion(VersionControl):
  15. name = 'svn'
  16. dirname = '.svn'
  17. repo_name = 'checkout'
  18. schemes = ('svn', 'svn+ssh', 'svn+http', 'svn+https', 'svn+svn')
  19. bundle_file = 'svn-checkout.txt'
  20. guide = ('# This was an svn checkout; to make it a checkout again run:\n'
  21. 'svn checkout --force -r %(rev)s %(url)s .\n')
  22. def get_info(self, location):
  23. """Returns (url, revision), where both are strings"""
  24. assert not location.rstrip('/').endswith(self.dirname), 'Bad directory: %s' % location
  25. output = call_subprocess(
  26. [self.cmd, 'info', location], show_stdout=False, extra_environ={'LANG': 'C'})
  27. match = _svn_url_re.search(output)
  28. if not match:
  29. logger.warn('Cannot determine URL of svn checkout %s' % display_path(location))
  30. logger.info('Output that cannot be parsed: \n%s' % output)
  31. return None, None
  32. url = match.group(1).strip()
  33. match = _svn_revision_re.search(output)
  34. if not match:
  35. logger.warn('Cannot determine revision of svn checkout %s' % display_path(location))
  36. logger.info('Output that cannot be parsed: \n%s' % output)
  37. return url, None
  38. return url, match.group(1)
  39. def parse_vcs_bundle_file(self, content):
  40. for line in content.splitlines():
  41. if not line.strip() or line.strip().startswith('#'):
  42. continue
  43. match = re.search(r'^-r\s*([^ ])?', line)
  44. if not match:
  45. return None, None
  46. rev = match.group(1)
  47. rest = line[match.end():].strip().split(None, 1)[0]
  48. return rest, rev
  49. return None, None
  50. def export(self, location):
  51. """Export the svn repository at the url to the destination location"""
  52. url, rev = self.get_url_rev()
  53. rev_options = get_rev_options(url, rev)
  54. logger.notify('Exporting svn repository %s to %s' % (url, location))
  55. logger.indent += 2
  56. try:
  57. if os.path.exists(location):
  58. # Subversion doesn't like to check out over an existing directory
  59. # --force fixes this, but was only added in svn 1.5
  60. rmtree(location)
  61. call_subprocess(
  62. [self.cmd, 'export'] + rev_options + [url, location],
  63. filter_stdout=self._filter, show_stdout=False)
  64. finally:
  65. logger.indent -= 2
  66. def switch(self, dest, url, rev_options):
  67. call_subprocess(
  68. [self.cmd, 'switch'] + rev_options + [url, dest])
  69. def update(self, dest, rev_options):
  70. call_subprocess(
  71. [self.cmd, 'update'] + rev_options + [dest])
  72. def obtain(self, dest):
  73. url, rev = self.get_url_rev()
  74. rev_options = get_rev_options(url, rev)
  75. if rev:
  76. rev_display = ' (to revision %s)' % rev
  77. else:
  78. rev_display = ''
  79. if self.check_destination(dest, url, rev_options, rev_display):
  80. logger.notify('Checking out %s%s to %s'
  81. % (url, rev_display, display_path(dest)))
  82. call_subprocess(
  83. [self.cmd, 'checkout', '-q'] + rev_options + [url, dest])
  84. def get_location(self, dist, dependency_links):
  85. for url in dependency_links:
  86. egg_fragment = Link(url).egg_fragment
  87. if not egg_fragment:
  88. continue
  89. if '-' in egg_fragment:
  90. ## FIXME: will this work when a package has - in the name?
  91. key = '-'.join(egg_fragment.split('-')[:-1]).lower()
  92. else:
  93. key = egg_fragment
  94. if key == dist.key:
  95. return url.split('#', 1)[0]
  96. return None
  97. def get_revision(self, location):
  98. """
  99. Return the maximum revision for all files under a given location
  100. """
  101. # Note: taken from setuptools.command.egg_info
  102. revision = 0
  103. for base, dirs, files in os.walk(location):
  104. if self.dirname not in dirs:
  105. dirs[:] = []
  106. continue # no sense walking uncontrolled subdirs
  107. dirs.remove(self.dirname)
  108. entries_fn = os.path.join(base, self.dirname, 'entries')
  109. if not os.path.exists(entries_fn):
  110. ## FIXME: should we warn?
  111. continue
  112. dirurl, localrev = self._get_svn_url_rev(base)
  113. if base == location:
  114. base_url = dirurl + '/' # save the root url
  115. elif not dirurl or not dirurl.startswith(base_url):
  116. dirs[:] = []
  117. continue # not part of the same svn tree, skip it
  118. revision = max(revision, localrev)
  119. return revision
  120. def get_url_rev(self):
  121. # hotfix the URL scheme after removing svn+ from svn+ssh:// readd it
  122. url, rev = super(Subversion, self).get_url_rev()
  123. if url.startswith('ssh://'):
  124. url = 'svn+' + url
  125. return url, rev
  126. def get_url(self, location):
  127. # In cases where the source is in a subdirectory, not alongside setup.py
  128. # we have to look up in the location until we find a real setup.py
  129. orig_location = location
  130. while not os.path.exists(os.path.join(location, 'setup.py')):
  131. last_location = location
  132. location = os.path.dirname(location)
  133. if location == last_location:
  134. # We've traversed up to the root of the filesystem without finding setup.py
  135. logger.warn("Could not find setup.py for directory %s (tried all parent directories)"
  136. % orig_location)
  137. return None
  138. return self._get_svn_url_rev(location)[0]
  139. def _get_svn_url_rev(self, location):
  140. from pip.exceptions import InstallationError
  141. f = open(os.path.join(location, self.dirname, 'entries'))
  142. data = f.read()
  143. f.close()
  144. if data.startswith('8') or data.startswith('9') or data.startswith('10'):
  145. data = list(map(str.splitlines, data.split('\n\x0c\n')))
  146. del data[0][0] # get rid of the '8'
  147. url = data[0][3]
  148. revs = [int(d[9]) for d in data if len(d) > 9 and d[9]] + [0]
  149. elif data.startswith('<?xml'):
  150. match = _svn_xml_url_re.search(data)
  151. if not match:
  152. raise ValueError('Badly formatted data: %r' % data)
  153. url = match.group(1) # get repository URL
  154. revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]
  155. else:
  156. try:
  157. # subversion >= 1.7
  158. xml = call_subprocess([self.cmd, 'info', '--xml', location], show_stdout=False)
  159. url = _svn_info_xml_url_re.search(xml).group(1)
  160. revs = [int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)]
  161. except InstallationError:
  162. url, revs = None, []
  163. if revs:
  164. rev = max(revs)
  165. else:
  166. rev = 0
  167. return url, rev
  168. def get_tag_revs(self, svn_tag_url):
  169. stdout = call_subprocess(
  170. [self.cmd, 'ls', '-v', svn_tag_url], show_stdout=False)
  171. results = []
  172. for line in stdout.splitlines():
  173. parts = line.split()
  174. rev = int(parts[0])
  175. tag = parts[-1].strip('/')
  176. results.append((tag, rev))
  177. return results
  178. def find_tag_match(self, rev, tag_revs):
  179. best_match_rev = None
  180. best_tag = None
  181. for tag, tag_rev in tag_revs:
  182. if (tag_rev > rev and
  183. (best_match_rev is None or best_match_rev > tag_rev)):
  184. # FIXME: Is best_match > tag_rev really possible?
  185. # or is it a sign something is wacky?
  186. best_match_rev = tag_rev
  187. best_tag = tag
  188. return best_tag
  189. def get_src_requirement(self, dist, location, find_tags=False):
  190. repo = self.get_url(location)
  191. if repo is None:
  192. return None
  193. parts = repo.split('/')
  194. ## FIXME: why not project name?
  195. egg_project_name = dist.egg_name().split('-', 1)[0]
  196. rev = self.get_revision(location)
  197. if parts[-2] in ('tags', 'tag'):
  198. # It's a tag, perfect!
  199. full_egg_name = '%s-%s' % (egg_project_name, parts[-1])
  200. elif parts[-2] in ('branches', 'branch'):
  201. # It's a branch :(
  202. full_egg_name = '%s-%s-r%s' % (dist.egg_name(), parts[-1], rev)
  203. elif parts[-1] == 'trunk':
  204. # Trunk :-/
  205. full_egg_name = '%s-dev_r%s' % (dist.egg_name(), rev)
  206. if find_tags:
  207. tag_url = '/'.join(parts[:-1]) + '/tags'
  208. tag_revs = self.get_tag_revs(tag_url)
  209. match = self.find_tag_match(rev, tag_revs)
  210. if match:
  211. logger.notify('trunk checkout %s seems to be equivalent to tag %s' % match)
  212. repo = '%s/%s' % (tag_url, match)
  213. full_egg_name = '%s-%s' % (egg_project_name, match)
  214. else:
  215. # Don't know what it is
  216. logger.warn('svn URL does not fit normal structure (tags/branches/trunk): %s' % repo)
  217. full_egg_name = '%s-dev_r%s' % (egg_project_name, rev)
  218. return 'svn+%s@%s#egg=%s' % (repo, rev, full_egg_name)
  219. def get_rev_options(url, rev):
  220. if rev:
  221. rev_options = ['-r', rev]
  222. else:
  223. rev_options = []
  224. r = urlparse.urlsplit(url)
  225. if hasattr(r, 'username'):
  226. # >= Python-2.5
  227. username, password = r.username, r.password
  228. else:
  229. netloc = r[1]
  230. if '@' in netloc:
  231. auth = netloc.split('@')[0]
  232. if ':' in auth:
  233. username, password = auth.split(':', 1)
  234. else:
  235. username, password = auth, None
  236. else:
  237. username, password = None, None
  238. if username:
  239. rev_options += ['--username', username]
  240. if password:
  241. rev_options += ['--password', password]
  242. return rev_options
  243. vcs.register(Subversion)