SubversionTool.py 12.8 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 30 31 32 33 34 35 36 37 38 39 40 41
##############################################################################
#
# 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 Products.CMFCore.utils import UniqueObject
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass, DTMLFile
from Products.ERP5Type.Document.Folder import Folder
from Products.ERP5Type import Permissions
from Products.ERP5Subversion import _dtmldir
from zLOG import LOG, WARNING, INFO
from Products.ERP5Subversion.SubversionClient import newSubversionClient
import os
from DateTime import DateTime
from cPickle import dumps, loads
from App.config import getConfiguration
from zExceptions import Unauthorized
Christophe Dumez's avatar
Christophe Dumez committed
42 43
from OFS.Image import manage_addFile
from cStringIO import StringIO
Aurel's avatar
Aurel committed
44 45 46 47

try:
  from base64 import b64encode, b64decode
except ImportError:
48
  from base64 import encodestring as b64encode, decodestring as b64decode
49 50 51
  
class File :
  # Constructor
52 53 54 55
  def __init__(self, full_path, msg_status) :
    self.full_path = full_path
    self.msg_status = msg_status
    self.name = full_path.split('/')[-1]
56 57 58 59
## End of File Class

class Dir :
  # Constructor
60 61 62 63 64
  def __init__(self, full_path, msg_status) :
    self.full_path = full_path
    self.msg_status = msg_status
    self.name = full_path.split('/')[-1]
    self.sub_dirs = [] # list of sub directories
65 66 67

  # return a list of sub directories' names
  def getSubDirs(self) :
68
    return [d.name for d in self.sub_dirs]
69 70

  # return directory in subdirs given its name
71
  def getDir(self, name):
72
    for d in self.sub_dirs:
73
      if d.name == name:
74 75 76
        return d
## End of Dir Class
  
Yoshinori Okuji's avatar
Yoshinori Okuji committed
77 78 79 80 81 82 83 84 85 86 87
class SubversionTool(UniqueObject, Folder):
  """The SubversionTool provides a Subversion interface to ERP5.
  """
  id = 'portal_subversion'
  meta_type = 'ERP5 Subversion Tool'
  portal_type = 'Subversion Tool'
  allowed_types = ()

  login_cookie_name = 'erp5_subversion_login'
  ssl_trust_cookie_name = 'erp5_subversion_ssl_trust'
  top_working_path = os.path.join(getConfiguration().instancehome, 'svn')
88

Yoshinori Okuji's avatar
Yoshinori Okuji committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  # Declarative Security
  security = ClassSecurityInfo()

  #
  #   ZMI methods
  #
  manage_options = ( ( { 'label'      : 'Overview'
                        , 'action'     : 'manage_overview'
                        }
                      ,
                      )
                    + Folder.manage_options
                    )

  security.declareProtected( Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainSubversionTool', _dtmldir )

  # Filter content (ZMI))
  def __init__(self):
108 109
# working_path = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
# svn_username = self.getPortalObject().portal_preferences.getPreference('preferred_subversion_user_name')
Yoshinori Okuji's avatar
Yoshinori Okuji committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
      return Folder.__init__(self, SubversionTool.id)

  # Filter content (ZMI))
  def filtered_meta_types(self, user=None):
      # Filters the list of available meta types.
      all = SubversionTool.inheritedAttribute('filtered_meta_types')(self)
      meta_types = []
      for meta_type in self.all_meta_types():
          if meta_type['name'] in self.allowed_types:
              meta_types.append(meta_type)
      return meta_types

  def getTopWorkingPath(self):
    return self.top_working_path

  def _getWorkingPath(self, path):
    if path[0] != '/':
      path = os.path.join(self.top_working_path, path)
    path = os.path.abspath(path)
    if not path.startswith(self.top_working_path):
      raise Unauthorized, 'unauthorized access to path %s' % path
    return path
132 133 134 135
    
  def setWorkingDirectory(self, path):
    self.workingDirectory = path
    os.chdir(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
136 137 138 139 140 141 142 143

  def getDefaultUserName(self):
    """Return a default user name.
    """
    name = self.portal_preferences.getPreferredSubversionUserName()
    if not name:
      name = self.portal_membership.getAuthenticatedMember().getUserName()
    return name
Yoshinori Okuji's avatar
Yoshinori Okuji committed
144 145 146 147 148 149 150 151 152
    
  def _encodeLogin(self, realm, user, password):
    # Encode login information.
    return b64encode(dumps((realm, user, password)))

  def _decodeLogin(self, login):
    # Decode login information.
    return loads(b64decode(login))
    
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  def setLogin(self, realm, user, password):
    """Set login information.
    """
    # Get existing login information. Filter out old information.
    login_list = []
    request = self.REQUEST
    cookie = request.get(self.login_cookie_name)
    if cookie:
      for login in cookie.split(','):
        if self._decodeLogin(login)[0] != realm:
          login_list.append(login)
    # Set the cookie.
    response = request.RESPONSE
    login_list.append(self._encodeLogin(realm, user, password))
    value = ','.join(login_list)
    expires = (DateTime() + 1).toZone('GMT').rfc822()
    response.setCookie(self.login_cookie_name, value, path = '/', expires = expires)
170

171 172
#   def setLogin(self, username, passwd):
#     self.login = (username, passwd)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

  def _getLogin(self, target_realm):
    request = self.REQUEST
    cookie = request.get(self.login_cookie_name)
    if cookie:
      for login in cookie.split(','):
        realm, user, password = self._decodeLogin(login)
        if target_realm == realm:
          return user, password
    return None, None

  def _encodeSSLTrust(self, trust_dict, permanent=False):
    # Encode login information.
    key_list = trust_dict.keys()
    key_list.sort()
    trust_item_list = tuple([(key, trust_dict[key]) for key in key_list])
    return b64encode(dumps((trust_item_list, permanent)))

  def _decodeSSLTrust(self, trust):
    # Decode login information.
    trust_item_list, permanent = loads(b64decode(login))
    return dict(trust_item_list), permanent
    
  security.declareProtected(Permissions.ManagePortal, 'acceptSSLServer')
  def acceptSSLServer(self, trust_dict, permanent=False):
    """Accept a SSL server.
    """
    # Get existing trust information.
    trust_list = []
    request = self.REQUEST
    cookie = request.get(self.ssl_trust_cookie_name)
    if cookie:
      trust.append(cookie)
    # Set the cookie.
    response = request.RESPONSE
    trust_list.append(self._encodeSSLTrust(trust_dict, permanent))
    value = ','.join(trust_list)
    expires = (DateTime() + 1).toZone('GMT').rfc822()
    response.setCookie(self.ssl_trust_cookie_name, value, path = '/', expires = expires)

  def _trustSSLServer(self, target_trust_dict):
    request = self.REQUEST
    cookie = request.get(self.ssl_trust_cookie_name)
    if cookie:
      for trust in cookie.split(','):
        trust_dict, permanent = self._decodeSSLTrust(trust)
        for key in target_trust_dict.keys():
          if target_trust_dict[key] != trust_dict.get(key):
            continue
        else:
          return True, permanent
    return False, False
    
  def _getClient(self, **kw):
    # Get the svn client object.
    return newSubversionClient(self, **kw)

  security.declareProtected('Import/Export objects', 'update')
  def update(self, path):
    """Update a working copy.
    """
    client = self._getClient()
    return client.update(self._getWorkingPath(path))

  security.declareProtected('Import/Export objects', 'add')
  def add(self, path):
    """Add a file or a directory.
    """
    client = self._getClient()
    return client.add(self._getWorkingPath(path))

  security.declareProtected('Import/Export objects', 'remove')
  def remove(self, path):
    """Remove a file or a directory.
    """
    client = self._getClient()
    return client.remove(self._getWorkingPath(path))

  security.declareProtected('Import/Export objects', 'move')
  def move(self, src, dest):
    """Move/Rename a file or a directory.
    """
    client = self._getClient()
    return client.move(src, dest)

  security.declareProtected('Import/Export objects', 'diff')
  def diff(self, path):
    """Make a diff for a file or a directory.
    """
    client = self._getClient()
    return client.diff(self._getWorkingPath(path))

  security.declareProtected('Import/Export objects', 'revert')
  def revert(self, path):
    """Revert local changes in a file or a directory.
    """
    client = self._getClient()
    return client.revert(self._getWorkingPath(path))

  security.declareProtected('Import/Export objects', 'checkin')
273
  def checkin(self, path, log_message = 'None', recurse=True):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
274 275
    """Commit local changes.
    """
276
    client = self._getClient(login=self.login)
277 278
    #return client.checkin(self._getWorkingPath(path), log_message, recurse)
    return client.checkin(path, log_message, recurse)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
279 280 281 282 283 284 285

  security.declareProtected('Import/Export objects', 'status')
  def status(self, path, **kw):
    """Get status.
    """
    client = self._getClient()
    return client.status(self._getWorkingPath(path), **kw)
286 287
  
  def getModifiedTree(self, path) :
Christophe Dumez's avatar
Christophe Dumez committed
288
    # Remove trailing slash if it's present
289 290 291
    if path[-1]=="/" :
      path = path[:-1]
    
Christophe Dumez's avatar
Christophe Dumez committed
292
    root = Dir(path, "normal")
293
    somethingModified = False
294
    
295
    for statusObj in self.status(path) :
296
      # can be (normal, added, modified, deleted)
297 298
      msg_status = statusObj.getTextStatus()
      if str(msg_status) != "normal" :
299
        somethingModified = True
Christophe Dumez's avatar
Christophe Dumez committed
300 301 302 303
        full_path = statusObj.getPath()
        full_path_list = full_path.split('/')[1:]
        relative_path = full_path[len(path)+1:]
        relative_path_list = relative_path.split('/')
304
        # Processing entry
Christophe Dumez's avatar
Christophe Dumez committed
305 306 307
        filename = relative_path_list[-1]
        # Needed or files will be both File & Dir objects
        relative_path_list = relative_path_list[:-1]
308
        parent = root
Christophe Dumez's avatar
Christophe Dumez committed
309 310 311 312 313
        i = len(path.split('/'))-1
        
        for d in relative_path_list :
          i += 1
          if d :
314
            full_pathOfd = '/'+'/'.join(full_path_list[:i]).strip()
315
            if d not in parent.getSubDirs() :
316
              parent.sub_dirs.append(Dir(full_pathOfd, "normal"))
317
            parent = parent.getDir(d)
Christophe Dumez's avatar
Christophe Dumez committed
318
        if os.path.isdir(full_path) :
319 320
          if full_path == parent.full_path :
            parent.msg_status = str(msg_status)
321 322
          elif filename not in parent.getSubDirs() :
            parent.sub_dirs.append(Dir(filename, str(msg_status)))
Christophe Dumez's avatar
Christophe Dumez committed
323
          else :
324
            tmp = parent.getDir(filename)
325
            tmp.msg_status = str(msg_status)
Christophe Dumez's avatar
Christophe Dumez committed
326
        else :
327
          parent.sub_dirs.append(File(filename, str(msg_status)))
328
    return somethingModified and root
329 330
            
  def treeToXML(self, item) :
331 332
    output = "<?xml version='1.0' encoding='iso-8859-1'?>"+ os.linesep
    output += "<tree id='0'>" + os.linesep
Christophe Dumez's avatar
Christophe Dumez committed
333
    output = self._treeToXML(item, output, 1, True)
334 335
    output += "</tree>" + os.linesep
    return output
336
  
Christophe Dumez's avatar
Christophe Dumez committed
337
  def _treeToXML(self, item, output, ident, first) :
338
    # Choosing a color coresponding to the status
339
    itemStatus = item.msg_status
Christophe Dumez's avatar
Christophe Dumez committed
340 341 342 343 344 345 346 347
    if itemStatus == 'added' :
      itemColor='green'
    elif itemStatus == 'modified' :
      itemColor='orange'
    elif itemStatus == 'deleted' :
      itemColor='red'
    else :
      itemColor='black'
348
      
349 350
    if isinstance(item, Dir) :
      for i in range(ident) :
351
        output += '\t'
Christophe Dumez's avatar
Christophe Dumez committed
352
      if first :
353
        output += '<item open="1" text="%s" id="%s" aCol="%s" '\
Christophe Dumez's avatar
Christophe Dumez committed
354
        'im0="folder.png" im1="folder_open.png" '\
355
        'im2="folder.png">'%(item.name,
356
item.full_path, itemColor,) + os.linesep
Christophe Dumez's avatar
Christophe Dumez committed
357 358
        first=False
      else :
359
        output += '<item text="%s" id="%s" aCol="%s" im0="folder.png" ' \
360
      'im1="folder_open.png" im2="folder.png">'%(item.name,
361
item.full_path, itemColor,) + os.linesep
362
      for it in item.sub_dirs:
363
        ident += 1
364
        output = self._treeToXML(item.getDir(it.name), output, ident,
Christophe Dumez's avatar
Christophe Dumez committed
365
first)
366 367
        ident -= 1
      for i in range(ident) :
368 369
        output += '\t'
      output += '</item>' + os.linesep
370 371
    else :
      for i in range(ident) :
372 373 374
        output += '\t'
      output += '<item text="%s" id="%s" aCol="%s" im0="document.png"/>'\
                %(item.name, item.full_path, itemColor,) + os.linesep
375
    return output
Yoshinori Okuji's avatar
Yoshinori Okuji committed
376 377
    
InitializeClass(SubversionTool)