SubversionClient.py 9.31 KB
Newer Older
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#                    Yoshinori Okuji <yo@nexedi.com>
#
# 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
30

31
import time, os
Yoshinori Okuji's avatar
Yoshinori Okuji committed
32 33 34 35
from Products.ERP5Type.Utils import convertToUpperCase
from MethodObject import Method
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
36
from Products.ERP5Type import Permissions
Christophe Dumez's avatar
Christophe Dumez committed
37
from Products.PythonScripts.Utility import allow_class
38
from zLOG import LOG
Yoshinori Okuji's avatar
Yoshinori Okuji committed
39 40 41

try:
  import pysvn
42
  
Yoshinori Okuji's avatar
Yoshinori Okuji committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

  class SubversionError(Exception):
    """The base exception class for the Subversion interface.
    """
    pass
    
  class SubversionInstallationError(SubversionError):
    """Raised when an installation is broken.
    """
    pass
    
  class SubversionTimeoutError(SubversionError):
    """Raised when a Subversion transaction is too long.
    """
    pass
  
  class SubversionLoginError(SubversionError):
    """Raised when an authentication is required.
    """
    def __init__(self, realm = None):
      self._realm = realm
  
    def getRealm(self):
      return self._realm
      
  class SubversionSSLTrustError(SubversionError):
    """Raised when a SSL certificate is not trusted.
    """
Christophe Dumez's avatar
Christophe Dumez committed
71 72 73
    # Declarative Security
    security = ClassSecurityInfo()
    
Yoshinori Okuji's avatar
Yoshinori Okuji committed
74 75
    def __init__(self, trust_dict = None):
      self._trust_dict = trust_dict
Christophe Dumez's avatar
Christophe Dumez committed
76 77
      
    security.declarePublic('getTrustDict')
Yoshinori Okuji's avatar
Yoshinori Okuji committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    def getTrustDict(self):
      return self._trust_dict
  
  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)
      if user is None:
Christophe Dumez's avatar
Christophe Dumez committed
109 110 111
        self.client.setException(SubversionLoginError(realm))
        #raise SubversionLoginError(realm)
        return False, '', '', False
Yoshinori Okuji's avatar
Yoshinori Okuji committed
112 113 114 115 116 117 118 119 120 121 122
      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):
      trust, permanent = self.client.trustSSLServer(trust_dict)
      if not trust:
123 124 125
        #raise SubversionSSLTrustError(trust_dict)
        self.client.setException(SubversionSSLTrustError(trust_dict))
        return False, 0, False
Yoshinori Okuji's avatar
Yoshinori Okuji committed
126 127 128 129 130 131 132 133 134 135 136 137 138
      # XXX SSL server certificate failure bits are not defined in pysvn.
      # 0x8 means that the CA is unknown.
      return True, 0x8, permanent

  # Wrap objects defined in pysvn so that skins have access to attributes in the ERP5 way.
  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')
139 140
      #elif isinstance(value, pysvn.Entry):
      elif str(type(value)) == "<type 'entry'>":
Yoshinori Okuji's avatar
Yoshinori Okuji committed
141
        value = Entry(value)
142 143
      #elif isinstance(value, pysvn.Revision):
      elif str(type(value)) == "<type 'revision'>":
Yoshinori Okuji's avatar
Yoshinori Okuji committed
144 145 146 147 148
        value = Revision(value)
      return value

  def initializeAccessors(klass):
    klass.security = ClassSecurityInfo()
149
    klass.security.declareObjectPublic()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
150 151
    for attr in klass.attribute_list:
      name = 'get' + convertToUpperCase(attr)
152
      print name
Yoshinori Okuji's avatar
Yoshinori Okuji committed
153 154
      setattr(klass, name, Getter(attr))
      klass.security.declarePublic(name)
155
    InitializeClass(klass)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
156 157 158 159 160 161 162 163

  class ObjectWrapper(Implicit):
    attribute_list = ()
    
    def __init__(self, obj):
      self._obj = obj
  
  class Status(ObjectWrapper):
164 165 166
    # XXX Big Hack to fix a bug
    __allow_access_to_unprotected_subobjects__ = 1
    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
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  initializeAccessors(Status)
  
  class Entry(ObjectWrapper):
    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')

  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
    
187
    def __init__(self, container, **kw):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
188 189
      self.client = pysvn.Client()
      self.client.set_auth_cache(0)
190 191 192 193
      obj = self.__of__(container)
      self.client.callback_cancel = CancelCallback(obj)
      self.client.callback_get_log_message = GetLogMessageCallback(obj)
      self.client.callback_get_login = GetLoginCallback(obj)
194
      #self.client.callback_get_login = self.callback_get_Login
195 196
      self.client.callback_notify = NotifyCallback(obj)
      self.client.callback_ssl_server_trust_prompt = SSLServerTrustPromptCallback(obj)
197
      #self.client.callback_ssl_server_trust_prompt = self.callback_ssl_server_trust_prompt
Yoshinori Okuji's avatar
Yoshinori Okuji committed
198 199 200 201 202
      self.creation_time = time.time()
      self.__dict__.update(kw)

    def getLogMessage(self):
      return self.log_message
203 204 205 206 207 208 209
    
    def _getPreferences(self):
      self.working_path = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
      if not self.working_path :
        raise "Error: Please set Subversion working path in preferences"
      self.svn_username = self.getPortalObject().portal_preferences.getPreference('preferred_subversion_user_name')
      os.chdir(self.working_path);
Yoshinori Okuji's avatar
Yoshinori Okuji committed
210 211 212 213

    def getTimeout(self):
      return self.timeout

214 215 216 217 218 219 220 221
#     def callback_get_Login( self, realm, username, may_save ):
#         #Retrieving saved username/password
#         username, password = self.login
#         if not username :
#           raise "Error: Couldn't retrieve saved username !"
#         if not password :
#           raise "Error: Couldn't retrieve saved password !"
#         return 1, username, password, True
222
        
Yoshinori Okuji's avatar
Yoshinori Okuji committed
223 224
    def trustSSLServer(self, trust_dict):
      return self.aq_parent._trustSSLServer(trust_dict)
225
    
226 227 228
#     def callback_ssl_server_trust_prompt( self, trust_data ):
#       # Always trusting
#       return True, trust_data['failures'], True
229 230 231 232 233 234

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

    def getException(self):
      return self.exception
235
    
236
    def checkin(self, path, log_message, recurse):
237
      self._getPreferences()
238 239 240 241
      try:
        return self.client.checkin(path, log_message=log_message, recurse=recurse)
      except pysvn.ClientError:
        raise self.getException()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
242 243 244 245

    def status(self, path, **kw):
      # Since plain Python classes are not convenient in Zope, convert the objects.
      return [Status(x) for x in self.client.status(path, **kw)]
Christophe Dumez's avatar
Christophe Dumez committed
246 247 248 249
    
    def diff(self, path):
      self._getPreferences()
      os.system('mkdir -p /tmp/tmp-svn/')
250 251 252 253 254
      return self.client.diff(tmp_path='/tmp/tmp-svn/', url_or_path=path, recurse=False)
    
    def revert(self, path):
      self._getPreferences()
      return self.client.revert(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
255 256

  def newSubversionClient(container, **kw):
257
    return SubversionClient(container, **kw).__of__(container)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
258
    
Christophe Dumez's avatar
Christophe Dumez committed
259 260 261
  InitializeClass(SubversionSSLTrustError)
  allow_class(SubversionSSLTrustError)
  
Yoshinori Okuji's avatar
Yoshinori Okuji committed
262
except ImportError:
263
  from zLOG import LOG, WARNING
Yoshinori Okuji's avatar
Yoshinori Okuji committed
264
  LOG('SubversionTool', WARNING,
265
      'could not import pysvn; until pysvn is installed properly, this tool will not work.')
Yoshinori Okuji's avatar
Yoshinori Okuji committed
266 267
  def newSubversionClient(container, **kw):
    raise SubversionInstallationError, 'pysvn is not installed'