SubversionTool.py 28.6 KB
Newer Older
Yoshinori Okuji's avatar
Yoshinori Okuji committed
1 2 3 4
##############################################################################
#
# Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved.
#                    Yoshinori Okuji <yo@nexedi.com>
Christophe Dumez's avatar
Christophe Dumez committed
5
#                    Christophe Dumez <christophe@nexedi.com>
Yoshinori Okuji's avatar
Yoshinori Okuji committed
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
#
# 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 Products.ERP5Subversion.SubversionClient import newSubversionClient
37
import os, re, commands, time, exceptions
Yoshinori Okuji's avatar
Yoshinori Okuji committed
38 39 40 41
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
44
from tempfile import mktemp
45
from shutil import copy2
Aurel's avatar
Aurel committed
46 47 48 49

try:
  from base64 import b64encode, b64decode
except ImportError:
50
  from base64 import encodestring as b64encode, decodestring as b64decode
51 52 53 54

class Error(exceptions.EnvironmentError):
    pass

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
def removeAll(entry):
  '''
    Remove all files and directories under 'entry'.
    XXX: This is defined here, because os.removedirs() is buggy.
  '''
  try:
    if os.path.isdir(entry) and not os.path.islink(entry):
      pwd = os.getcwd()
      os.chmod(entry, 0755)
      os.chdir(entry)
      for e in os.listdir(os.curdir):
        removeAll(e)
      os.chdir(pwd)
      os.rmdir(entry)
    else:
      if not os.path.islink(entry):
        os.chmod(entry, 0644)
      os.remove(entry)
  except OSError:
    pass
75 76 77 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 109
      
def copytree(src, dst, symlinks=False):
    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.
    If exception(s) occur, an Error is raised with a list of reasons.

    If the optional symlinks flag is true, symbolic links in the
    source tree result in symbolic links in the destination tree; if
    it is false, the contents of the files pointed to by symbolic
    links are copied.

    XXX Consider this example code rather than the ultimate tool.

    """
    if not os.path.exists(dst):
      os.mkdir(dst)
    names = os.listdir(src)
    errors = []
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks)
            else:
                copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except (IOError, os.error), why:
            errors.append((srcname, dstname, why))
    if errors:
        raise Error, errors
110 111

  
112 113
class File :
  # Constructor
114 115 116 117
  def __init__(self, full_path, msg_status) :
    self.full_path = full_path
    self.msg_status = msg_status
    self.name = full_path.split('/')[-1]
118 119 120 121
## End of File Class

class Dir :
  # Constructor
122 123 124 125 126
  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
127 128 129

  # return a list of sub directories' names
  def getSubDirs(self) :
130
    return [d.name for d in self.sub_dirs]
131 132

  # return directory in subdirs given its name
133
  def getDir(self, name):
134
    for d in self.sub_dirs:
135
      if d.name == name:
136 137
        return d
## End of Dir Class
138 139 140 141 142 143 144 145

class DiffFile:
  # Members :
  # - path : path of the modified file
  # - children : sub codes modified
  # - old_revision
  # - new_revision

146
  def __init__(self, raw_diff):
147 148 149 150 151
    if '@@' not in raw_diff:
      self.binary=True
      return
    else:
      self.binary=False
152
    self.header = raw_diff.split('@@')[0][:-1]
153
    # Getting file path in header
154
    self.path = self.header.split('====')[0][:-1].strip()
155
    # Getting revisions in header
156
    for line in self.header.split('\n'):
157 158
      if line.startswith('--- '):
        tmp = re.search('\\([\w\s]+\\)$', line)
159
        self.old_revision = tmp.string[tmp.start():tmp.end()][1:-1].strip()
160 161
      if line.startswith('+++ '):
        tmp = re.search('\\([\w\s]+\\)$', line)
162
        self.new_revision = tmp.string[tmp.start():tmp.end()][1:-1].strip()
163
    # Splitting the body from the header
164
    self.body = '\n'.join(raw_diff.strip().split('\n')[4:])
165
    # Now splitting modifications
166
    self.children = []
167 168
    first = True
    tmp = []
169
    for line in self.body.split('\n'):
170 171
      if line:
        if line.startswith('@@') and not first:
172
          self.children.append(CodeBlock('\n'.join(tmp)))
173 174 175 176
          tmp = [line,]
        else:
          first = False
          tmp.append(line)
177
    self.children.append(CodeBlock('\n'.join(tmp)))
178 179
    

180
  def _escape(self, data):
181 182 183 184 185 186 187 188 189 190
    """
      Escape &, <, and > in a string of data.
      This is a copy of the xml.sax.saxutils.escape function.
    """
    if data:
      #data = data.replace("&", "&amp;")
      data = data.replace(">", "&gt;")
      data = data.replace("<", "&lt;")
      return data
    
191
  def toHTML(self):
192
    # Adding header of the table
193 194 195
    if self.binary:
      return '<b>Binary File!</b><br><br><br>'
    
Christophe Dumez's avatar
Christophe Dumez committed
196
    html = '''
197 198 199 200
    <table style="text-align: left; width: 100%%;" border="0" cellpadding="0" cellspacing="0">
  <tbody>
    <tr height="18px">
      <td style="background-color: grey"><b><center>%s</center></b></td>
Christophe Dumez's avatar
Christophe Dumez committed
201
      <td style="background-color: black;" width="2"></td>
202
      <td style="background-color: grey"><b><center>%s</center></b></td>
Christophe Dumez's avatar
Christophe Dumez committed
203
    </tr>'''%(self.old_revision, self.new_revision)
Christophe Dumez's avatar
Christophe Dumez committed
204
    header_color = 'grey'
205
    for child in self.children:
206
      # Adding line number of the modification
Christophe Dumez's avatar
Christophe Dumez committed
207 208 209 210 211 212
      html += '''<tr height="18px"><td style="background-color: %s">&nbsp;</td><td style="background-color: black;" width="2"></td><td style="background-color: %s">&nbsp;</td></tr>    <tr height="18px">
      <td style="background-color: rgb(68, 132, 255);"><b>Line %s</b></td>
      <td style="background-color: black;" width="2"></td>
      <td style="background-color: rgb(68, 132, 255);"><b>Line %s</b></td>
      </tr>'''%(header_color, header_color, child.old_line, child.new_line)
      header_color = 'white'
213 214 215 216 217 218
      # Adding diff of the modification
      old_code_list = child.getOldCodeList()
      new_code_list = child.getNewCodeList()
      i=0
      for old_line_tuple in old_code_list:
        new_line_tuple = new_code_list[i]
Christophe Dumez's avatar
Christophe Dumez committed
219 220
        new_line = new_line_tuple[0] or ' '
        old_line = old_line_tuple[0] or ' '
221 222
        i+=1
        html += '''    <tr height="18px">
Christophe Dumez's avatar
Christophe Dumez committed
223 224 225 226
        <td style="background-color: %s">%s</td>
        <td style="background-color: black;" width="2"></td>
        <td style="background-color: %s">%s</td>
        </tr>'''%(old_line_tuple[1], self._escape(old_line).replace(' ', '&nbsp;').replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'), new_line_tuple[1], self._escape(new_line).replace(' ', '&nbsp;').replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'))
227
    html += '''  </tbody>
Christophe Dumez's avatar
Christophe Dumez committed
228
</table><br><br>'''
229 230 231 232 233 234 235 236 237 238 239 240 241 242
    return html
      

# A code block contains several SubCodeBlocks
class CodeBlock:
  # Members :
  # - old_line : line in old code (before modif)
  # - new line : line in new code (after modif)
  #
  # Methods :
  # - getOldCodeList() : return code before modif
  # - getNewCodeList() : return code after modif
  # Note: the code returned is a list of tuples (code line, background color)

243
  def __init__(self, raw_diff):
244
    # Splitting body and header
245 246
    self.body = '\n'.join(raw_diff.split('\n')[1:])
    self.header = raw_diff.split('\n')[0]
247
    # Getting modifications lines
248 249
    tmp = re.search('^@@ -\d+', self.header)
    self.old_line = tmp.string[tmp.start():tmp.end()][4:]
Christophe Dumez's avatar
Christophe Dumez committed
250 251
    tmp = re.search('\+\d+', self.header)
    self.new_line = tmp.string[tmp.start():tmp.end()][1:]
252 253
    # Splitting modifications in SubCodeBlocks
    in_modif = False
254
    self.children = []
255
    tmp=[]
256
    for line in self.body.split('\n'):
257 258 259 260 261
      if line:
        if (line.startswith('+') or line.startswith('-')):
          if in_modif:
            tmp.append(line)
          else:
262
            self.children.append(SubCodeBlock('\n'.join(tmp)))
263 264 265 266
            tmp = [line,]
            in_modif = True
        else:
            if in_modif:
267
              self.children.append(SubCodeBlock('\n'.join(tmp)))
268 269 270 271
              tmp = [line,]
              in_modif = False
            else:
              tmp.append(line)
272
    self.children.append(SubCodeBlock('\n'.join(tmp)))
273 274
    
  # Return code before modification
275
  def getOldCodeList(self):
276
    tmp = []
277
    for child in self.children:
278 279 280 281
      tmp.extend(child.getOldCodeList())
    return tmp
    
  # Return code after modification
282
  def getNewCodeList(self):
283
    tmp = []
284
    for child in self.children:
285 286 287 288 289
      tmp.extend(child.getNewCodeList())
    return tmp
    
# a SubCodeBlock contain 0 or 1 modification (not more)
class SubCodeBlock:
290
  def __init__(self, code):
291 292
    self.body = code
    self.modification = self._getModif()
Christophe Dumez's avatar
Christophe Dumez committed
293 294
    self.old_code_length = self._getOldCodeLength()
    self.new_code_length = self._getNewCodeLength()
295
    # Choosing background color
296 297 298 299 300 301
    if self.modification == 'none':
      self.color = 'white'
    elif self.modification == 'change':
      self.color = 'rgb(253, 228, 6);'#light orange
    elif self.modification == 'deletion':
      self.color = 'rgb(253, 117, 74);'#light red
Christophe Dumez's avatar
Christophe Dumez committed
302
    else: # addition
303
      self.color = 'rgb(83, 253, 74);'#light green
304
    
305
  def _getModif(self):
306 307
    nb_plus = 0
    nb_minus = 0
308
    for line in self.body.split('\n'):
309 310 311 312 313 314
      if line.startswith("-"):
        nb_minus-=1
      elif line.startswith("+"):
        nb_plus+=1
    if (nb_plus==0 and nb_minus==0):
      return 'none'
Christophe Dumez's avatar
Christophe Dumez committed
315 316 317 318
    if (nb_minus==0):
      return 'addition'
    if (nb_plus==0):
      return 'deletion'
319
    return 'change'
Christophe Dumez's avatar
Christophe Dumez committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333
      
  def _getOldCodeLength(self):
    nb_lines = 0
    for line in self.body.split('\n'):
      if not line.startswith("+"):
        nb_lines+=1
    return nb_lines
      
  def _getNewCodeLength(self):
    nb_lines = 0
    for line in self.body.split('\n'):
      if not line.startswith("-"):
        nb_lines+=1
    return nb_lines
334
  
335
  # Return code before modification
336 337
  def getOldCodeList(self):
    if self.modification=='none':
338
      old_code = [(x, 'white') for x in self.body.split('\n')]
Christophe Dumez's avatar
Christophe Dumez committed
339 340 341 342 343 344
    elif self.modification=='change':
      old_code = [self._getOldCodeList(x) for x in self.body.split('\n') if self._getOldCodeList(x)[0]]
      # we want old_code_list and new_code_list to have the same length
      if(self.old_code_length < self.new_code_length):
        filling = [(None, self.color)]*(self.new_code_length-self.old_code_length)
        old_code.extend(filling)
345
    else: # deletion or addition
346 347
      old_code = [self._getOldCodeList(x) for x in self.body.split('\n')]
    return old_code
348
  
349
  def _getOldCodeList(self, line):
350
    if line.startswith('+'):
351
      return (None, self.color)
352
    if line.startswith('-'):
353 354
      return (' '+line[1:], self.color)
    return (line, self.color)
355 356
  
  # Return code after modification
357 358
  def getNewCodeList(self):
    if self.modification=='none':
359
      new_code = [(x, 'white') for x in self.body.split('\n')]
Christophe Dumez's avatar
Christophe Dumez committed
360 361 362 363 364 365
    elif self.modification=='change':
      new_code = [self._getNewCodeList(x) for x in self.body.split('\n') if self._getNewCodeList(x)[0]]
      # we want old_code_list and new_code_list to have the same length
      if(self.new_code_length < self.old_code_length):
        filling = [(None, self.color)]*(self.old_code_length-self.new_code_length)
        new_code.extend(filling)
366
    else: # deletion or addition
367 368
      new_code = [self._getNewCodeList(x) for x in self.body.split('\n')]
    return new_code
369
  
370
  def _getNewCodeList(self, line):
371
    if line.startswith('-'):
372
      return (None, self.color)
373
    if line.startswith('+'):
374 375
      return (' '+line[1:], self.color)
    return (line, self.color)
376
  
Yoshinori Okuji's avatar
Yoshinori Okuji committed
377 378 379 380 381 382 383 384 385 386 387
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')
388

Yoshinori Okuji's avatar
Yoshinori Okuji committed
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
  # 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):
      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
430 431 432 433
    
  def setWorkingDirectory(self, path):
    self.workingDirectory = path
    os.chdir(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
434 435 436 437 438 439 440 441

  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
442
    
Christophe Dumez's avatar
Christophe Dumez committed
443 444
  
  # path is the path in svn working copy
445 446
  # return edit_path in zodb to edit it
  # return '#' if no zodb path is found
Christophe Dumez's avatar
Christophe Dumez committed
447 448 449
  def editPath(self, bt, path):
    """Return path to edit file
    """
450 451
    if 'bt' in path.split('/'):
      # not in zodb
Christophe Dumez's avatar
Christophe Dumez committed
452 453 454 455 456 457
      return '#'
    svn_path = bt.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
    if not svn_path:
      raise 'Error: Please set working copy path in Subversion preferences !'
    if svn_path[-1] != '/':
      svn_path += '/'
458
    svn_path = svn_path + bt.getTitle()
Christophe Dumez's avatar
Christophe Dumez committed
459
    edit_path = path.replace(svn_path, '')
460 461 462 463 464
    if edit_path.strip() == '':
      # not in zodb 
      return '#'
    if edit_path[0] == '/':
      edit_path = edit_path[1:]
Christophe Dumez's avatar
Christophe Dumez committed
465
    edit_path = '/'.join(edit_path.split('/')[1:])
466 467 468
    if edit_path.strip() == '':
      # not in zodb 
      return '#'
Christophe Dumez's avatar
Christophe Dumez committed
469 470 471 472 473 474 475
    tmp = re.search('\\.[\w]+$', edit_path)
    if tmp:
      extension = tmp.string[tmp.start():tmp.end()].strip()
      edit_path = edit_path.replace(extension, '')
    edit_path = bt.REQUEST["BASE2"] + '/' + edit_path + '/manage_main'
    return edit_path
    
Yoshinori Okuji's avatar
Yoshinori Okuji committed
476 477 478 479 480 481 482 483
  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))
    
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  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)
Christophe Dumez's avatar
Christophe Dumez committed
499
    expires = (DateTime() + 7).toZone('GMT').rfc822()
500
    request.set(self.login_cookie_name, value)
501
    response.setCookie(self.login_cookie_name, value, path = '/', expires = expires)
502

Yoshinori Okuji's avatar
Yoshinori Okuji committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
  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.
Christophe Dumez's avatar
Christophe Dumez committed
522
    trust_item_list, permanent = loads(b64decode(trust))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
523
    return dict(trust_item_list), permanent
524 525 526 527
  
  def diffHTML(self, file_path):
    raw_diff = self.diff(file_path)
    return DiffFile(raw_diff).toHTML()
Christophe Dumez's avatar
Christophe Dumez committed
528 529
  
  # Display a file content in HTML
Christophe Dumez's avatar
Christophe Dumez committed
530
  def fileHTML(self, bt, file_path):
531 532 533
    if os.path.exists(file_path):
      if os.path.isdir(file_path):
        text = "<b>"+file_path+"</b><hr>"
534
        text += file_path +" is a folder!"
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
      else:
        head = "<b>"+file_path+"</b>  <a href='"+self.editPath(bt, file_path)+"'><img src='imgs/edit.png' border='0'></a><hr>"
        text = commands.getoutput('enscript -B --color --line-numbers --highlight=html --language=html -o - %s'%file_path)
        text = head + '\n'.join(text.split('\n')[10:-4])
      return text
    else:
      # see if tmp file is here (svn deleted file)
      if file_path[-1]=='/':
        file_path=file_path[:-1]
      filename = file_path.split('/')[-1]
      tmp_path = '/'.join(file_path.split('/')[:-1])
      tmp_path = tmp_path+'/.svn/text-base/'+filename+'.svn-base'
      if os.path.exists(tmp_path):
        head = "<b>"+tmp_path+"</b> (svn temporary file)<hr>"
        text = commands.getoutput('enscript -B --color --line-numbers --highlight=html --language=html -o - %s'%tmp_path)
        text = head + '\n'.join(text.split('\n')[10:-4])
      else : # does not exist
        text = "<b>"+file_path+"</b><hr>"
553
        text += file_path +" does not exist!"
554 555
      return text
      
Yoshinori Okuji's avatar
Yoshinori Okuji committed
556 557 558 559 560 561 562 563 564
  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:
Christophe Dumez's avatar
Christophe Dumez committed
565
      trust_list.append(cookie)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
566 567 568 569
    # Set the cookie.
    response = request.RESPONSE
    trust_list.append(self._encodeSSLTrust(trust_dict, permanent))
    value = ','.join(trust_list)
Christophe Dumez's avatar
Christophe Dumez committed
570
    expires = (DateTime() + 7).toZone('GMT').rfc822()
571
    request.set(self.ssl_trust_cookie_name, value)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
572
    response.setCookie(self.ssl_trust_cookie_name, value, path = '/', expires = expires)
Christophe Dumez's avatar
Christophe Dumez committed
573 574 575
    
  def acceptSSLPerm(self, trust_dict):
    self.acceptSSLServer(self, trust_dict, True)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

  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()
599
    return client.update(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
600 601 602 603 604 605

  security.declareProtected('Import/Export objects', 'add')
  def add(self, path):
    """Add a file or a directory.
    """
    client = self._getClient()
606
    return client.add(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
607

608 609 610 611 612 613 614 615 616 617
  security.declareProtected('Import/Export objects', 'info')
  def info(self):
    """return info of working copy
    """
    working_copy = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
    if not working_copy :
      raise 'Please set Working copy path in preferences'
    client = self._getClient()
    return client.info(working_copy)
  
Christophe Dumez's avatar
Christophe Dumez committed
618 619 620 621 622 623 624
  security.declareProtected('Import/Export objects', 'log')
  def log(self, path):
    """return log of a file or dir
    """
    client = self._getClient()
    return client.log(path)
  
625 626 627 628 629 630 631 632 633 634
  security.declareProtected('Import/Export objects', 'cleanup')
  def cleanup(self):
    """remove svn locks in working copy
    """
    working_copy = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
    if not working_copy :
      raise 'Please set Working copy path in preferences'
    client = self._getClient()
    return client.cleanup(working_copy)

Yoshinori Okuji's avatar
Yoshinori Okuji committed
635 636 637 638 639
  security.declareProtected('Import/Export objects', 'remove')
  def remove(self, path):
    """Remove a file or a directory.
    """
    client = self._getClient()
640
    return client.remove(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
641 642 643 644 645 646 647 648

  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)

Christophe Dumez's avatar
Christophe Dumez committed
649 650 651 652 653 654 655
  security.declareProtected('Import/Export objects', 'ls')
  def ls(self, path):
    """Display infos about a file.
    """
    client = self._getClient()
    return client.ls(path)

Yoshinori Okuji's avatar
Yoshinori Okuji committed
656 657 658 659 660
  security.declareProtected('Import/Export objects', 'diff')
  def diff(self, path):
    """Make a diff for a file or a directory.
    """
    client = self._getClient()
Christophe Dumez's avatar
Christophe Dumez committed
661
    return client.diff(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
662 663 664 665 666 667

  security.declareProtected('Import/Export objects', 'revert')
  def revert(self, path):
    """Revert local changes in a file or a directory.
    """
    client = self._getClient()
Christophe Dumez's avatar
Christophe Dumez committed
668
    return client.revert(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
669 670

  security.declareProtected('Import/Export objects', 'checkin')
671
  def checkin(self, path, log_message=None, recurse=True):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
672 673
    """Commit local changes.
    """
674
    client = self._getClient(login=self.login)
675
    return client.checkin(path, log_message, recurse)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
676 677 678 679 680 681

  security.declareProtected('Import/Export objects', 'status')
  def status(self, path, **kw):
    """Get status.
    """
    client = self._getClient()
Christophe Dumez's avatar
Christophe Dumez committed
682
    return client.status(path, **kw)
683 684
  
  def getModifiedTree(self, path) :
Christophe Dumez's avatar
Christophe Dumez committed
685
    # Remove trailing slash if it's present
686 687 688
    if path[-1]=="/" :
      path = path[:-1]
    
Christophe Dumez's avatar
Christophe Dumez committed
689
    root = Dir(path, "normal")
690
    somethingModified = False
691
    
692
    for statusObj in self.status(path) :
693
      # can be (normal, added, modified, deleted, conflicted, unversioned)
694
      msg_status = statusObj.getTextStatus()
695
      if str(msg_status) != "normal" and str(msg_status) != "unversioned":
696
        somethingModified = True
Christophe Dumez's avatar
Christophe Dumez committed
697 698 699 700
        full_path = statusObj.getPath()
        full_path_list = full_path.split('/')[1:]
        relative_path = full_path[len(path)+1:]
        relative_path_list = relative_path.split('/')
701
        # Processing entry
Christophe Dumez's avatar
Christophe Dumez committed
702 703 704
        filename = relative_path_list[-1]
        # Needed or files will be both File & Dir objects
        relative_path_list = relative_path_list[:-1]
705
        parent = root
Christophe Dumez's avatar
Christophe Dumez committed
706 707 708 709 710
        i = len(path.split('/'))-1
        
        for d in relative_path_list :
          i += 1
          if d :
711
            full_pathOfd = '/'+'/'.join(full_path_list[:i]).strip()
712
            if d not in parent.getSubDirs() :
713
              parent.sub_dirs.append(Dir(full_pathOfd, "normal"))
714
            parent = parent.getDir(d)
Christophe Dumez's avatar
Christophe Dumez committed
715
        if os.path.isdir(full_path) :
716 717
          if full_path == parent.full_path :
            parent.msg_status = str(msg_status)
718 719
          elif filename not in parent.getSubDirs() :
            parent.sub_dirs.append(Dir(filename, str(msg_status)))
Christophe Dumez's avatar
Christophe Dumez committed
720
          else :
721
            tmp = parent.getDir(filename)
722
            tmp.msg_status = str(msg_status)
Christophe Dumez's avatar
Christophe Dumez committed
723
        else :
Christophe Dumez's avatar
Christophe Dumez committed
724
          parent.sub_dirs.append(File(full_path, str(msg_status)))
725
    return somethingModified and root
726
  
727 728
  def extractBT(self, bt):
    path = mktemp()
729 730
    bt.export(path=path, local=1)
    svn_path = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
731
    if not svn_path :
732
      raise "Error: Please set Subversion working path in preferences"
733 734
    svn_path=os.path.join(svn_path,bt.getTitle())+'/'
    path+='/'
735
    # svn del deleted files
736
    self.deleteOldFiles(svn_path, path, bt)
737
    # add new files and copy
738
    self.addNewFiles(svn_path, path, bt)
739
    # Clean up
740
    removeAll(path)
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

  # return a set with dirs & files present in the directory
  def getSetForDir(self, directory):
    dir_set = set()
    for root, dirs, files in os.walk(directory):
      # don't visit SVN directories
      if '.svn' in dirs:
        dirs.remove('.svn')
      # get Directories
      for name in dirs:
        f = os.path.join(root, name)
        dir_set.add(f.replace(directory,''))
      # get Files
      for name in files: 
        f = os.path.join(root, name)
        dir_set.add(f.replace(directory,''))
    return dir_set
758
  
759 760 761 762 763 764 765 766 767 768 769
  # return files/dirs present in new_dir but not in old_dir
  # return a set of relative paths
  def getNewFiles(self, old_dir, new_dir):
    if old_dir[-1] != '/':
      old_dir += '/'
    if new_dir[-1] != '/':
      new_dir += '/'
    old_set = self.getSetForDir(old_dir)
    new_set = self.getSetForDir(new_dir)
    return new_set.difference(old_set)

770
  # svn del files that have been removed in new dir
771
  def deleteOldFiles(self, old_dir, new_dir, bt):
772
    # detect removed files
773
    files_set = self.getNewFiles(new_dir, old_dir)
774
    # svn del
775 776
    for file in files_set:
        self.remove(os.path.join(old_dir, file)) 
777
  
778 779
  # copy files and add new files
  def addNewFiles(self, old_dir, new_dir, bt):
780
    # detect created files
781
    files_set = self.getNewFiles(old_dir, new_dir)
782
    # Copy files
783 784
    os.system('cp -af %s/* %s'%(new_dir, old_dir))
    #copytree(new_dir, old_dir)
785
    # svn add
786 787
    for file in files_set:
          self.add(os.path.join(old_dir, file))
788
  
789
  def treeToXML(self, item) :
790 791
    output = "<?xml version='1.0' encoding='iso-8859-1'?>"+ os.linesep
    output += "<tree id='0'>" + os.linesep
Christophe Dumez's avatar
Christophe Dumez committed
792
    output = self._treeToXML(item, output, 1, True)
793 794
    output += "</tree>" + os.linesep
    return output
795
  
Christophe Dumez's avatar
Christophe Dumez committed
796
  def _treeToXML(self, item, output, ident, first) :
797 798 799 800 801 802
    # svn path
    svn_path = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
    if not svn_path :
      raise "Error: Please set Subversion working path in preferences"
    if svn_path[-1] != '/':
      svn_path += '/'
803
    # Choosing a color coresponding to the status
804
    itemStatus = item.msg_status
Christophe Dumez's avatar
Christophe Dumez committed
805 806 807 808 809 810 811 812
    if itemStatus == 'added' :
      itemColor='green'
    elif itemStatus == 'modified' :
      itemColor='orange'
    elif itemStatus == 'deleted' :
      itemColor='red'
    else :
      itemColor='black'
813
      
814 815
    if isinstance(item, Dir) :
      for i in range(ident) :
816
        output += '\t'
Christophe Dumez's avatar
Christophe Dumez committed
817
      if first :
818
        output += '<item open="1" text="%s" id="%s" aCol="%s" '\
Christophe Dumez's avatar
Christophe Dumez committed
819
        'im0="folder.png" im1="folder_open.png" '\
820
        'im2="folder.png">'%(item.name,
821
item.full_path.replace(svn_path, ''), itemColor,) + os.linesep
Christophe Dumez's avatar
Christophe Dumez committed
822 823
        first=False
      else :
824
        output += '<item text="%s" id="%s" aCol="%s" im0="folder.png" ' \
825
      'im1="folder_open.png" im2="folder.png">'%(item.name,
826
item.full_path.replace(svn_path, ''), itemColor,) + os.linesep
827
      for it in item.sub_dirs:
828
        ident += 1
829
        output = self._treeToXML(item.getDir(it.name), output, ident,
Christophe Dumez's avatar
Christophe Dumez committed
830
first)
831 832
        ident -= 1
      for i in range(ident) :
833 834
        output += '\t'
      output += '</item>' + os.linesep
835 836
    else :
      for i in range(ident) :
837 838
        output += '\t'
      output += '<item text="%s" id="%s" aCol="%s" im0="document.png"/>'\
839
                %(item.name, item.full_path.replace(svn_path, ''), itemColor,) + os.linesep
840
    return output
Yoshinori Okuji's avatar
Yoshinori Okuji committed
841 842
    
InitializeClass(SubversionTool)