SubversionClient.py 13.5 KB
Newer Older
1
# -*- coding: utf-8 -*-
Yoshinori Okuji's avatar
Yoshinori Okuji committed
2 3 4 5
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#                    Yoshinori Okuji <yo@nexedi.com>
Christophe Dumez's avatar
Christophe Dumez committed
6
#                    Christophe Dumez <christophe@nexedi.com>
Yoshinori Okuji's avatar
Yoshinori Okuji committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from Acquisition import Implicit
32

33 34 35
import time
import os
import sys
36
from DateTime import DateTime
Yoshinori Okuji's avatar
Yoshinori Okuji committed
37 38
from Products.ERP5Type.Utils import convertToUpperCase
from MethodObject import Method
39
from Products.ERP5Type.Globals import InitializeClass
40
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Yoshinori Okuji's avatar
Yoshinori Okuji committed
41
from AccessControl import ClassSecurityInfo
42
from AccessControl.SecurityInfo import ModuleSecurityInfo
Christophe Dumez's avatar
Christophe Dumez committed
43
from Products.PythonScripts.Utility import allow_class
44
from tempfile import mkdtemp
45
import shutil
Yoshinori Okuji's avatar
Yoshinori Okuji committed
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

class getTransactionalDirectory(str):
  """Returns a temporary directory that is automatically deleted when
     transaction ends
  """
  def __new__(cls, tv_key):
    tv = getTransactionalVariable()
    try:
      return str(tv[tv_key])
    except KeyError:
      path = mkdtemp()
      tv[tv_key] = str.__new__(cls, path)
      return path

  def __del__(self):
    shutil.rmtree(str(self))


65 66 67 68
class SubversionError(Exception):
  """The base exception class for the Subversion interface.
  """
  pass
69
  
70 71 72 73 74 75 76 77 78
class SubversionInstallationError(SubversionError):
  """Raised when an installation is broken.
  """
  pass
  
class SubversionTimeoutError(SubversionError):
  """Raised when a Subversion transaction is too long.
  """
  pass
79 80 81 82 83 84 85 86 87 88 89 90 91 92

class SubversionLoginError(SubversionError):
  """Raised when an authentication is required.
  """
  # Declarative Security
  security = ClassSecurityInfo()
  def __init__(self, realm = None):
    self._realm = realm

  security.declarePublic('getRealm')
  def getRealm(self):
    return self._realm

InitializeClass(SubversionLoginError)
93 94
ModuleSecurityInfo(__name__).declarePublic('SubversionLoginError')

95 96 97 98 99
class SubversionSSLTrustError(SubversionError):
  """Raised when a SSL certificate is not trusted.
  """
  # Declarative Security
  security = ClassSecurityInfo()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
100
  
101 102 103 104 105 106
  def __init__(self, trust_dict = None):
    self._trust_dict = trust_dict
    
  security.declarePublic('getTrustDict')
  def getTrustDict(self):
    return self._trust_dict
Yoshinori Okuji's avatar
Yoshinori Okuji committed
107
  
108
InitializeClass(SubversionSSLTrustError)
109 110
ModuleSecurityInfo(__name__).declarePublic('SubversionSSLTrustError')

111 112
try:
  import pysvn
Yoshinori Okuji's avatar
Yoshinori Okuji committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  
  class Callback:
    """The base class for callback functions.
    """
    def __init__(self, client):
      self.client = client
  
    def __call__(self, *args):
      pass
  
  class CancelCallback(Callback):
    def __call__(self):
      current_time = time.time()
      if current_time - self.client.creation_time > self.client.getTimeout():
        raise SubversionTimeoutError, 'too long transaction'
        #return True
      return False
  
  class GetLogMessageCallback(Callback):
    def __call__(self):
      message = self.client.getLogMessage()
      if message:
        return True, message
      return False, ''
  
  class GetLoginCallback(Callback):
    def __call__(self, realm, username, may_save):
      user, password = self.client.getLogin(realm)
141
      if not username or not password:
Christophe Dumez's avatar
Christophe Dumez committed
142 143
        self.client.setException(SubversionLoginError(realm))
        return False, '', '', False
Yoshinori Okuji's avatar
Yoshinori Okuji committed
144 145 146 147 148 149 150 151 152
      return True, user, password, False
  
  class NotifyCallback(Callback):
    def __call__(self, event_dict):
      # FIXME: should accumulate information for the user
      pass
  
  class SSLServerTrustPromptCallback(Callback):
    def __call__(self, trust_dict):
153
      if not self.client.trustSSLServer(trust_dict):
154 155
        self.client.setException(SubversionSSLTrustError(trust_dict))
        return False, 0, False
Yoshinori Okuji's avatar
Yoshinori Okuji committed
156 157
      # XXX SSL server certificate failure bits are not defined in pysvn.
      # 0x8 means that the CA is unknown.
158
      return True, 0x8, False
159 160 161 162 163 164 165 166 167 168 169 170
    
  class SSLServerPromptCallback(Callback):
    def __call__(self):
      return
    
  class SSLClientCertPromptCallback(Callback):
    def __call__(self):
      return
    
  class SSLClientCertPasswordPromptCallback(Callback):
    def __call__(self):
      return
Yoshinori Okuji's avatar
Yoshinori Okuji committed
171

Christophe Dumez's avatar
Christophe Dumez committed
172 173
  # Wrap objects defined in pysvn so that skins
  # have access to attributes in the ERP5 way.
Yoshinori Okuji's avatar
Yoshinori Okuji committed
174 175 176 177 178 179 180 181
  class Getter(Method):
    def __init__(self, key):
      self._key = key
  
    def __call__(self, instance):
      value = getattr(instance._obj, self._key)
      if type(value) == type(u''):
        value = value.encode('utf-8')
182 183
      #elif isinstance(value, pysvn.Entry):
      elif str(type(value)) == "<type 'entry'>":
Yoshinori Okuji's avatar
Yoshinori Okuji committed
184
        value = Entry(value)
185 186
      #elif isinstance(value, pysvn.Revision):
      elif str(type(value)) == "<type 'revision'>":
Yoshinori Okuji's avatar
Yoshinori Okuji committed
187 188 189 190 191
        value = Revision(value)
      return value

  def initializeAccessors(klass):
    klass.security = ClassSecurityInfo()
192
    klass.security.declareObjectPublic()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
193 194 195 196
    for attr in klass.attribute_list:
      name = 'get' + convertToUpperCase(attr)
      setattr(klass, name, Getter(attr))
      klass.security.declarePublic(name)
197
    InitializeClass(klass)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
198 199 200 201 202 203 204 205

  class ObjectWrapper(Implicit):
    attribute_list = ()
    
    def __init__(self, obj):
      self._obj = obj
  
  class Status(ObjectWrapper):
206 207
    # XXX Big Hack to fix a bug
    __allow_access_to_unprotected_subobjects__ = 1
Christophe Dumez's avatar
Christophe Dumez committed
208 209 210
    attribute_list = ('path', 'entry', 'is_versioned', 'is_locked', \
    'is_copied', 'is_switched', 'prop_status', 'text_status', \
    'repos_prop_status', 'repos_text_status')
Yoshinori Okuji's avatar
Yoshinori Okuji committed
211 212 213
  initializeAccessors(Status)
  
  class Entry(ObjectWrapper):
Christophe Dumez's avatar
Christophe Dumez committed
214 215 216 217 218 219
    attribute_list = ('checksum', 'commit_author', 'commit_revision', \
    'commit_time', 'conflict_new', 'conflict_old', 'conflict_work', \
    'copy_from_revision', 'copy_from_url', 'is_absent', 'is_copied', \
    'is_deleted', 'is_valid', 'kind', 'name', 'properties_time', \
    'property_reject_file', 'repos', 'revision', 'schedule', \
    'text_time', 'url', 'uuid')
Yoshinori Okuji's avatar
Yoshinori Okuji committed
220 221 222 223 224 225 226 227 228 229 230 231

  class Revision(ObjectWrapper):
    attribute_list = ('kind', 'date', 'number')
  initializeAccessors(Revision)

  
  class SubversionClient(Implicit):
    """This class wraps pysvn's Client class.
    """
    log_message = None
    timeout = 60 * 5
    
232
    def __init__(self, container, **kw):
233
      self.client = pysvn.Client()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
234
      self.client.set_auth_cache(0)
235
      obj = self.__of__(container)
236
      self.client.exception_style = 1
237 238 239 240
      self.client.callback_cancel = CancelCallback(obj)
      self.client.callback_get_log_message = GetLogMessageCallback(obj)
      self.client.callback_get_login = GetLoginCallback(obj)
      self.client.callback_notify = NotifyCallback(obj)
Christophe Dumez's avatar
Christophe Dumez committed
241 242
      self.client.callback_ssl_server_trust_prompt = \
      SSLServerTrustPromptCallback(obj)
243 244 245
      self.client.callback_ssl_server_prompt = SSLServerPromptCallback(obj)
      self.client.callback_ssl_client_cert_prompt = SSLClientCertPromptCallback(obj)
      self.client.callback_ssl_client_cert_password_prompt = SSLClientCertPasswordPromptCallback(obj)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
246
      self.creation_time = time.time()
247
      self.__dict__.update(kw)
248
      self.exception = None
Yoshinori Okuji's avatar
Yoshinori Okuji committed
249 250 251

    def getLogMessage(self):
      return self.log_message
252
    
253 254
    def getLogin(self, realm):
      return self.aq_parent._getLogin(realm)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
255 256 257

    def getTimeout(self):
      return self.timeout
258
        
Yoshinori Okuji's avatar
Yoshinori Okuji committed
259 260
    def trustSSLServer(self, trust_dict):
      return self.aq_parent._trustSSLServer(trust_dict)
261 262 263 264 265 266

    def setException(self, exc):
      self.exception = exc

    def getException(self):
      return self.exception
267
    
268
    def checkin(self, path, log_message, recurse):
269
      try:
270 271 272
        return Revision(self.client.checkin(path,
                                            log_message=log_message or 'none',
                                            recurse=recurse))
273 274 275 276 277 278
      except pysvn.ClientError, error:
        excep = self.getException()
        if excep:
          raise excep
        else:
          raise error
279
        
280 281
    def update(self, path):
      try:
282
        return [Revision(x) for x in self.client.update(path)]
283 284 285 286 287 288 289
      except pysvn.ClientError, error:
        excep = self.getException()
        if excep:
          raise excep
        else:
          raise error
        
Yoshinori Okuji's avatar
Yoshinori Okuji committed
290
    def status(self, path, **kw):
Christophe Dumez's avatar
Christophe Dumez committed
291 292
      # Since plain Python classes are not convenient in 
      # Zope, convert the objects.
293
      try:
Jérome Perrin's avatar
Jérome Perrin committed
294
        status_list = [Status(x) for x in self.client.status(path=path, **kw)]
295 296 297 298 299 300
      except pysvn.ClientError, error:
        excep = self.getException()
        if excep:
          raise excep
        else:
          raise error
Christophe Dumez's avatar
Christophe Dumez committed
301 302
      # XXX: seems that pysvn return a list that is 
      # upside-down, we reverse it...
303 304
      status_list.reverse()
      return status_list
Christophe Dumez's avatar
Christophe Dumez committed
305
    
306
    def diff(self, path, revision1=None, revision2=None):
307 308 309 310 311
      tmp_path = getTransactionalDirectory('SubversionClient.diff:tmp_dir')
      if revision1 and revision2:
        return self.client.diff(tmp_path, url_or_path=path, recurse=False,
          revision1=pysvn.Revision(pysvn.opt_revision_kind.number,revision1),
          revision2=pysvn.Revision(pysvn.opt_revision_kind.number,revision2))
312
      else:
313
        return self.client.diff(tmp_path, url_or_path=path, recurse=False)
314
    
315 316
    def revert(self, path, recurse=False):
      return self.client.revert(path, recurse)
Christophe Dumez's avatar
Christophe Dumez committed
317
    
318 319
    def switch(self, path, url):
      return self.client.switch(path=path, url=url)
320 321 322 323

    def checkout(self, path, url):
      return self.client.checkout(path=path, url=url)

Christophe Dumez's avatar
Christophe Dumez committed
324
    def log(self, path):
325 326 327
      try:
        log_list = self.client.log(path)
      except pysvn.ClientError, error:
328 329
        if 'path not found' in error.args[0]:
          return
330 331 332 333 334 335
        excep = self.getException()
        if excep:
          raise excep
        else:
          raise error
      # Edit list to make it more usable in zope
336
      revision_log_list = []
337
      for rev_dict in log_list:
338 339 340 341
        rev_log_dict = {}
        rev_log_dict['message'] = rev_dict.message
        rev_log_dict['author'] = rev_dict.author
        rev_log_dict['revision'] = rev_dict['revision'].number
342
        rev_log_dict['date'] = DateTime(rev_dict['date'])
343 344
        revision_log_list.append(rev_log_dict)
      return revision_log_list
345
        
346
    def add(self, path):
347
      self.client.add(path=path, force=True)
348

Christophe Dumez's avatar
Christophe Dumez committed
349 350 351
    def resolved(self, path):
      return self.client.resolved(path=path)
    
352
    def info(self, path):
353 354 355 356 357
      if not os.path.exists(path):
        raise ValueError, "Repository %s does not exist" % path
      # symlinks are not well supported by pysvn
      if os.path.islink(path):
        path = os.path.realpath(path)
358 359 360 361 362 363 364 365
      try:
        entry = self.client.info(path=path)
      except pysvn.ClientError, error:
        excep = self.getException()
        if excep:
          raise excep
        else:
          raise error
366 367
      if entry is None:
        raise ValueError, "Could not open SVN repository %s" % path
368
      # transform entry to dict to make it more usable in zope
Christophe Dumez's avatar
Christophe Dumez committed
369 370 371 372
      members_tuple = ('url', 'uuid', 'revision', 'kind', \
      'commit_author', 'commit_revision', 'commit_time',)
      entry_dict = dict([(member, getattr(entry, member)) \
      for member in members_tuple])
373 374
      entry_dict['revision'] = entry_dict['revision'].number
      entry_dict['commit_revision'] = entry_dict['commit_revision'].number
375
      entry_dict['commit_time'] = DateTime(entry_dict['commit_time'])
376 377
      return entry_dict
      
Christophe Dumez's avatar
Christophe Dumez committed
378
    def ls(self, path):
379 380 381
      try:
        dict_list = self.client.ls(url_or_path=path, recurse=False)
      except pysvn.ClientError, error:
382 383
        if 'non-existent' in error.args[0]:
          return
384 385 386 387 388 389
        excep = self.getException()
        if excep:
          raise excep
        else:
          raise error
       #Modify the list to make it more usable in zope
Christophe Dumez's avatar
Christophe Dumez committed
390 391
      for dictionary in dict_list:
        dictionary['created_rev'] = dictionary['created_rev'].number
392
        dictionary['time'] = DateTime(dictionary['time'])
393
      return dict_list
Christophe Dumez's avatar
Christophe Dumez committed
394

395 396 397
    def cleanup(self, path):
      return self.client.cleanup(path=path)

398
    def remove(self, path):
399
      self.client.remove(url_or_path=path, force=True)
400

401 402 403
    def cat(self, *args, **kw):
      return self.client.cat(*args, **kw)

Yoshinori Okuji's avatar
Yoshinori Okuji committed
404
  def newSubversionClient(container, **kw):
405
    return SubversionClient(container, **kw).__of__(container)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
406 407
    
except ImportError:
408
  from zLOG import LOG, WARNING
409
  LOG('Subversion', WARNING,
410 411
      'could not import pysvn; until pysvn is installed properly,'
      ' this tool will not work.', error=sys.exc_info())
Yoshinori Okuji's avatar
Yoshinori Okuji committed
412
  def newSubversionClient(container, **kw):
413
    raise SubversionInstallationError, 'pysvn library is not installed'