SubversionTool.py 34.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, thread
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 copy
46
from zLOG import LOG
Aurel's avatar
Aurel committed
47 48 49 50

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

class Error(exceptions.EnvironmentError):
    pass

56 57 58 59 60 61 62 63 64 65
class SubversionPreferencesError(Exception):
  """The base exception class for the Subversion preferences.
  """
  pass
  
class SubversionUnknownBusinessTemplateError(Exception):
  """The base exception class when business template is unknown.
  """
  pass

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
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
86 87
      
def copytree(src, dst, symlinks=False):
88
    """Recursively copy a directory tree using copy().
89 90

    If exception(s) occur, an Error is raised with a list of reasons.
91
    dst dir must exist
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

    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.
    """
    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):
108 109
                if not os.path.exists(dstname):
                  os.makedirs(dstname)
110 111
                copytree(srcname, dstname, symlinks)
            else:
112
                copy(srcname, dstname)
113
        except (IOError, os.error), why:
114
            errors.append((srcname, dstname, 'Error: ' + str(why.strerror)))
115 116
    if errors:
        raise Error, errors
117 118

  
119 120
class File :
  # Constructor
121 122 123
  def __init__(self, full_path, msg_status) :
    self.full_path = full_path
    self.msg_status = msg_status
124
    self.name = full_path.split(os.sep)[-1]
125 126 127 128
## End of File Class

class Dir :
  # Constructor
129 130 131
  def __init__(self, full_path, msg_status) :
    self.full_path = full_path
    self.msg_status = msg_status
132
    self.name = full_path.split(os.sep)[-1]
133
    self.sub_dirs = [] # list of sub directories
134 135 136

  # return a list of sub directories' names
  def getSubDirs(self) :
137
    return [d.name for d in self.sub_dirs]
138 139

  # return directory in subdirs given its name
140
  def getDir(self, name):
141
    for d in self.sub_dirs:
142
      if d.name == name:
143 144
        return d
## End of Dir Class
145 146 147 148 149 150 151 152

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

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

187
  def _escape(self, data):
188 189 190 191 192 193 194 195 196 197
    """
      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
    
198
  def toHTML(self):
199
    # Adding header of the table
200
    if self.binary:
201
      return '<b>Binary File or no changes!</b><br><br><br>'
202
    
Christophe Dumez's avatar
Christophe Dumez committed
203
    html = '''
204 205 206 207
    <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
208
      <td style="background-color: black;" width="2"></td>
209
      <td style="background-color: grey"><b><center>%s</center></b></td>
Christophe Dumez's avatar
Christophe Dumez committed
210
    </tr>'''%(self.old_revision, self.new_revision)
Christophe Dumez's avatar
Christophe Dumez committed
211
    header_color = 'grey'
212
    for child in self.children:
213
      # Adding line number of the modification
Christophe Dumez's avatar
Christophe Dumez committed
214 215 216 217 218 219
      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'
220 221 222 223 224 225
      # 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
226 227
        new_line = new_line_tuple[0] or ' '
        old_line = old_line_tuple[0] or ' '
228 229
        i+=1
        html += '''    <tr height="18px">
Christophe Dumez's avatar
Christophe Dumez committed
230 231 232 233
        <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;'))
234
    html += '''  </tbody>
Christophe Dumez's avatar
Christophe Dumez committed
235
</table><br><br>'''
236 237 238 239 240 241 242 243 244 245 246 247 248 249
    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)

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

Yoshinori Okuji's avatar
Yoshinori Okuji committed
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 430 431 432 433 434
  # 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):
    path = os.path.abspath(path)
    if not path.startswith(self.top_working_path):
      raise Unauthorized, 'unauthorized access to path %s' % path
    return path
435 436 437 438
    
  def setWorkingDirectory(self, path):
    self.workingDirectory = path
    os.chdir(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
439 440 441 442 443 444 445 446

  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
447
    
Christophe Dumez's avatar
Christophe Dumez committed
448 449
  
  # path is the path in svn working copy
450 451
  # return edit_path in zodb to edit it
  # return '#' if no zodb path is found
Christophe Dumez's avatar
Christophe Dumez committed
452 453
  def editPath(self, bt, path):
    """Return path to edit file
454
       path can be relative or absolute
Christophe Dumez's avatar
Christophe Dumez committed
455
    """
456
    path = self.relativeToAbsolute(path, bt).replace('\\', '/')
457
    if 'bt' in path.split('/'):
458
      # not in zodb
Christophe Dumez's avatar
Christophe Dumez committed
459
      return '#'
460 461 462
    # if file have been deleted then not in zodb
    if not os.path.exists(path):
      return '#'
463
    svn_path = self.getSubversionPath(bt).replace('\\', '/')
Christophe Dumez's avatar
Christophe Dumez committed
464
    edit_path = path.replace(svn_path, '')
465 466 467
    if edit_path.strip() == '':
      # not in zodb 
      return '#'
468
    if edit_path[0] == '/':
469
      edit_path = edit_path[1:]
470
    edit_path = '/'.join(edit_path.split('/')[1:])
471 472 473
    if edit_path.strip() == '':
      # not in zodb 
      return '#'
Christophe Dumez's avatar
Christophe Dumez committed
474 475 476 477
    tmp = re.search('\\.[\w]+$', edit_path)
    if tmp:
      extension = tmp.string[tmp.start():tmp.end()].strip()
      edit_path = edit_path.replace(extension, '')
478
    edit_path = bt.REQUEST["BASE2"] + '/' + edit_path + '/manage_main'
Christophe Dumez's avatar
Christophe Dumez committed
479 480
    return edit_path
    
Yoshinori Okuji's avatar
Yoshinori Okuji committed
481 482 483 484 485 486 487
  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))
488 489 490 491
  
  def goToWorkingCopy(self, bt):
      working_path = self.getSubversionPath(bt)
      os.chdir(working_path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
492
    
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
  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
508
    expires = (DateTime() + 7).toZone('GMT').rfc822()
509
    request.set(self.login_cookie_name, value)
510
    response.setCookie(self.login_cookie_name, value, path = '/', expires = expires)
511

Yoshinori Okuji's avatar
Yoshinori Okuji committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  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
531
    trust_item_list, permanent = loads(b64decode(trust))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
532
    return dict(trust_item_list), permanent
533
  
534 535
  def diffHTML(self, file_path, bt, revision1=None, revision2=None):
    raw_diff = self.diff(file_path, bt, revision1, revision2)
536
    return DiffFile(raw_diff).toHTML()
Christophe Dumez's avatar
Christophe Dumez committed
537 538
  
  # Display a file content in HTML
Christophe Dumez's avatar
Christophe Dumez committed
539
  def fileHTML(self, bt, file_path):
540
    file_path = self.relativeToAbsolute(file_path, bt)
541 542 543
    if os.path.exists(file_path):
      if os.path.isdir(file_path):
        text = "<b>"+file_path+"</b><hr>"
544
        text += file_path +" is a folder!"
545 546 547
      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)
548
        text = head + os.linesep.join(text.split(os.linesep)[10:-4])
549 550 551
      return text
    else:
      # see if tmp file is here (svn deleted file)
552
      if file_path[-1]==os.sep:
553
        file_path=file_path[:-1]
554 555
      filename = file_path.split(os.sep)[-1]
      tmp_path = os.sep.join(file_path.split(os.sep)[:-1])
556 557
      tmp_path = os.path.join(tmp_path,'.svn','text-base',filename+'.svn-base')
      LOG('path_HD', 1, tmp_path)
558 559 560
      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)
561
        text = head + os.linesep.join(text.split(os.linesep)[10:-4])
562 563
      else : # does not exist
        text = "<b>"+file_path+"</b><hr>"
564
        text += file_path +" does not exist!"
565 566
      return text
      
Yoshinori Okuji's avatar
Yoshinori Okuji committed
567 568 569 570 571 572 573 574 575
  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
576
      trust_list.append(cookie)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
577 578 579 580
    # 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
581
    expires = (DateTime() + 7).toZone('GMT').rfc822()
582
    request.set(self.ssl_trust_cookie_name, value)
583
    response.setCookie(self.ssl_trust_cookie_name, value, path = '/', expires = expires)
Christophe Dumez's avatar
Christophe Dumez committed
584 585 586
    
  def acceptSSLPerm(self, trust_dict):
    self.acceptSSLServer(self, trust_dict, True)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

  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)
604 605 606 607 608 609 610 611 612
  
  security.declareProtected('Import/Export objects', 'getSubversionPath')
  # with_name : with business template name at the end of the path
  def getSubversionPath(self, bt, with_name=True):
    # return the working copy path corresponding to
    # the given business template browsing
    # working copy list in preferences (looking
    # only at first level of directories)
    wc_list = self.getPortalObject().portal_preferences.getPreferredSubversionWorkingCopyList()
613 614 615
    if not wc_list:
      wc_list = self.getPortalObject().portal_preferences.default_site_preference.getPreferredSubversionWorkingCopyList()
      if not wc_list:
616
        raise SubversionPreferencesError, 'Please set at least one Subversion Working Copy in preferences first.'
617 618
    bt_name = bt.getTitle()
    if len(wc_list) == 0 :
619
      raise SubversionPreferencesError, 'Please set at least one Subversion Working Copy in preferences first.'
620 621 622 623 624 625 626 627
    for wc in wc_list:
      if bt_name in os.listdir(wc) :
        wc_path = os.path.join(wc, bt_name)
        if os.path.isdir(wc_path):
          if with_name:
            return wc_path
          else:
            return os.sep.join(wc_path.split(os.sep)[:-1])
628
    raise SubversionUnknownBusinessTemplateError, "Could not find '"+bt_name+"' at first level of working copies."
629
    
Yoshinori Okuji's avatar
Yoshinori Okuji committed
630
  security.declareProtected('Import/Export objects', 'update')
631
  def update(self, bt):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
632 633
    """Update a working copy.
    """
634
    path = self.getSubversionPath(bt)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
635
    client = self._getClient()
636 637 638 639 640
    # Revert first to import a "pure" BT after update
    self.revert(path=path, recurse=True)
    # Update from SVN
    client.update(path)
    # Import in zodb
Christophe Dumez's avatar
Christophe Dumez committed
641
    return self.importBT(bt)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
642 643

  security.declareProtected('Import/Export objects', 'add')
644 645
  # path can be a list or not (relative or absolute)
  def add(self, path, bt=None):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
646 647
    """Add a file or a directory.
    """
Christophe Dumez's avatar
Christophe Dumez committed
648
    if bt is not None:
649 650 651 652
      if isinstance(path, list) :
        path = [self.relativeToAbsolute(x, bt) for x in path]
      else:
        path = self.relativeToAbsolute(path, bt)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
653
    client = self._getClient()
654
    return client.add(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
655

656
  security.declareProtected('Import/Export objects', 'info')
657
  def info(self, bt):
658 659
    """return info of working copy
    """
660
    working_copy = self.getSubversionPath(bt)
661 662 663
    client = self._getClient()
    return client.info(working_copy)
  
Christophe Dumez's avatar
Christophe Dumez committed
664
  security.declareProtected('Import/Export objects', 'log')
665 666
  # path can be absolute or relative
  def log(self, path, bt):
Christophe Dumez's avatar
Christophe Dumez committed
667 668 669
    """return log of a file or dir
    """
    client = self._getClient()
670
    return client.log(self.relativeToAbsolute(path, bt))
Christophe Dumez's avatar
Christophe Dumez committed
671
  
672
  security.declareProtected('Import/Export objects', 'cleanup')
673
  def cleanup(self, bt):
674 675
    """remove svn locks in working copy
    """
676
    working_copy = self.getSubversionPath(bt)
677 678 679
    client = self._getClient()
    return client.cleanup(working_copy)

Yoshinori Okuji's avatar
Yoshinori Okuji committed
680
  security.declareProtected('Import/Export objects', 'remove')
681 682
  # path can be a list or not (relative or absolute)
  def remove(self, path, bt=None):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
683 684
    """Remove a file or a directory.
    """
Christophe Dumez's avatar
Christophe Dumez committed
685
    if bt is not None:
686 687 688 689
      if isinstance(path, list) :
        path = [self.relativeToAbsolute(x, bt) for x in path]
      else:
        path = self.relativeToAbsolute(path, bt)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
690
    client = self._getClient()
691
    return client.remove(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
692 693 694 695 696 697 698 699

  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
700
  security.declareProtected('Import/Export objects', 'ls')
701 702
  # path can be relative or absolute
  def ls(self, path, bt):
Christophe Dumez's avatar
Christophe Dumez committed
703 704 705
    """Display infos about a file.
    """
    client = self._getClient()
706
    return client.ls(self.relativeToAbsolute(path, bt))
Christophe Dumez's avatar
Christophe Dumez committed
707

Yoshinori Okuji's avatar
Yoshinori Okuji committed
708
  security.declareProtected('Import/Export objects', 'diff')
709 710
  # path can be relative or absolute
  def diff(self, path, bt, revision1=None, revision2=None):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
711 712 713
    """Make a diff for a file or a directory.
    """
    client = self._getClient()
714
    return client.diff(self.relativeToAbsolute(path, bt), revision1, revision2)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
715 716

  security.declareProtected('Import/Export objects', 'revert')
717
  # path can be absolute or relative
718
  def revert(self, path, bt=None, recurse=False):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
719 720 721
    """Revert local changes in a file or a directory.
    """
    client = self._getClient()
Christophe Dumez's avatar
Christophe Dumez committed
722 723
    if bt is not None:
      object_to_update = {}
724 725
      if isinstance(path, list) :
        path = [self.relativeToAbsolute(x, bt) for x in path]
726
        #for p in path:
Christophe Dumez's avatar
Christophe Dumez committed
727
          #object_to_update[p.split(os.sep)[-1]] = 'install'
728 729
      else:
        path = self.relativeToAbsolute(path, bt)
Christophe Dumez's avatar
Christophe Dumez committed
730
        #object_to_update[path.split(os.sep)[-1]] = 'install'
731
    #else:
Christophe Dumez's avatar
Christophe Dumez committed
732 733
      #bt.install(object_to_update=object_to_update)
    client.revert(path, recurse)
Christophe Dumez's avatar
Christophe Dumez committed
734 735 736 737 738 739 740 741 742 743 744 745
    
  security.declareProtected('Import/Export objects', 'resolved')
  # path can be absolute or relative
  def resolved(self, path, bt):
    """remove conflicted status
    """
    client = self._getClient()
    if isinstance(path, list) :
      path = [self.relativeToAbsolute(x, bt) for x in path]
    else:
      path = self.relativeToAbsolute(path, bt)
    return client.resolved(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
746

747 748 749 750 751 752 753 754 755 756
  def relativeToAbsolute(self, path, bt) :
    if path[0] == os.sep:
      # already absolute
      return path
    # relative path
    if path.split(os.sep)[0] == bt.getTitle():
      return os.path.join(self.getSubversionPath(bt, False), path)
    else:
      return os.path.join(self.getSubversionPath(bt), path)

Yoshinori Okuji's avatar
Yoshinori Okuji committed
757
  security.declareProtected('Import/Export objects', 'checkin')
758 759
  # path can be relative or absolute (can be a list of paths too)
  def checkin(self, path, bt, log_message=None, recurse=True):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
760 761
    """Commit local changes.
    """
762 763 764 765
    if isinstance(path, list) :
      path = [self.relativeToAbsolute(x, bt) for x in path]
    else:
      path = self.relativeToAbsolute(path, bt)
766
    client = self._getClient()
767
    return client.checkin(path, log_message, recurse)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
768 769 770 771 772 773

  security.declareProtected('Import/Export objects', 'status')
  def status(self, path, **kw):
    """Get status.
    """
    client = self._getClient()
Christophe Dumez's avatar
Christophe Dumez committed
774
    return client.status(path, **kw)
775
  
776 777 778 779 780 781 782 783 784 785 786 787 788 789
  security.declareProtected('Import/Export objects', 'unversionedFiles')
  def unversionedFiles(self, path, **kw):
    """Return unversioned files
    """
    client = self._getClient()
    status_list = client.status(path, **kw)
    unversioned_list = []
    for statusObj in status_list:
      if str(statusObj.getTextStatus()) == "unversioned":
        my_dict = {}
        my_dict['uid'] = statusObj.getPath()
        unversioned_list.append(my_dict)
    return unversioned_list
      
790 791 792 793 794 795 796 797 798 799 800 801 802 803
  security.declareProtected('Import/Export objects', 'conflictedFiles')
  def conflictedFiles(self, path, **kw):
    """Return unversioned files
    """
    client = self._getClient()
    status_list = client.status(path, **kw)
    conflicted_list = []
    for statusObj in status_list:
      if str(statusObj.getTextStatus()) == "conflicted":
        my_dict = {}
        my_dict['uid'] = statusObj.getPath()
        conflicted_list.append(my_dict)
    return conflicted_list

804 805 806 807 808 809 810
  security.declareProtected('Import/Export objects', 'removeAllInList')
  def removeAllInList(self, list):
    """Remove all files and folders in list
    """
    for file in list:
      removeAll(file)
    
811
  def getModifiedTree(self, bt) :
Christophe Dumez's avatar
Christophe Dumez committed
812
    # Remove trailing slash if it's present
813
    path = self.getSubversionPath(bt)
Christophe Dumez's avatar
Christophe Dumez committed
814
    root = Dir(path, "normal")
815
    somethingModified = False
816
    
817
    for statusObj in self.status(path) :
818
      # can be (normal, added, modified, deleted, conflicted, unversioned)
819
      msg_status = statusObj.getTextStatus()
820
      if str(msg_status) != "normal" and str(msg_status) != "unversioned":
821
        somethingModified = True
Christophe Dumez's avatar
Christophe Dumez committed
822
        full_path = statusObj.getPath()
823
        full_path_list = full_path.split(os.sep)[1:]
Christophe Dumez's avatar
Christophe Dumez committed
824
        relative_path = full_path[len(path)+1:]
825
        relative_path_list = relative_path.split(os.sep)
826
        # Processing entry
Christophe Dumez's avatar
Christophe Dumez committed
827 828 829
        filename = relative_path_list[-1]
        # Needed or files will be both File & Dir objects
        relative_path_list = relative_path_list[:-1]
830
        parent = root
831
        i = len(path.split(os.sep))-1
Christophe Dumez's avatar
Christophe Dumez committed
832 833 834 835
        
        for d in relative_path_list :
          i += 1
          if d :
836
            full_pathOfd = os.sep+os.sep.join(full_path_list[:i]).strip()
837
            if d not in parent.getSubDirs() :
838
              parent.sub_dirs.append(Dir(full_pathOfd, "normal"))
839
            parent = parent.getDir(d)
Christophe Dumez's avatar
Christophe Dumez committed
840
        if os.path.isdir(full_path) :
841 842
          if full_path == parent.full_path :
            parent.msg_status = str(msg_status)
843 844
          elif filename not in parent.getSubDirs() :
            parent.sub_dirs.append(Dir(filename, str(msg_status)))
Christophe Dumez's avatar
Christophe Dumez committed
845
          else :
846
            tmp = parent.getDir(filename)
847
            tmp.msg_status = str(msg_status)
Christophe Dumez's avatar
Christophe Dumez committed
848
        else :
Christophe Dumez's avatar
Christophe Dumez committed
849
          parent.sub_dirs.append(File(full_path, str(msg_status)))
850
    return somethingModified and root
851
  
852
  def extractBT(self, bt):
853
    svn_path = self.getSubversionPath(bt) + os.sep
854
    path = mktemp()  +os.sep
855 856
    bt.export(path=path, local=1)
    # svn del deleted files
857
    self.deleteOldFiles(svn_path, path, bt)
858
    # add new files and copy
859
    self.addNewFiles(svn_path, path, bt)
860
    self.goToWorkingCopy(bt)
861
    # Clean up
862
    self.activate().removeAllInList([path,])
863 864
    
  def importBT(self, bt):
865
    return bt.download(self.getSubversionPath(bt))
866

867 868
  # return a set with directories present in the directory
  def getSetDirsForDir(self, directory):
869 870 871 872 873 874 875
    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:
876
        i = root.replace(directory, '').count(os.sep)
877
        f = os.path.join(root, name)
878
        dir_set.add((i, f.replace(directory,'')))
879 880 881 882 883 884 885 886 887
    return dir_set
      
  # return a set with files present in the directory
  def getSetFilesForDir(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')
888
      # get Files
889 890
      for name in files:
        i = root.replace(directory, '').count(os.sep)
891
        f = os.path.join(root, name)
892
        dir_set.add((i, f.replace(directory,'')))
893
    return dir_set
894
  
895
  # return files present in new_dir but not in old_dir
896 897
  # return a set of relative paths
  def getNewFiles(self, old_dir, new_dir):
898 899 900 901
    if old_dir[-1] != os.sep:
      old_dir += os.sep
    if new_dir[-1] != os.sep:
      new_dir += os.sep
902 903
    old_set = self.getSetFilesForDir(old_dir)
    new_set = self.getSetFilesForDir(new_dir)
904 905
    return new_set.difference(old_set)

906 907 908 909 910 911 912 913 914 915 916
  # return dirs present in new_dir but not in old_dir
  # return a set of relative paths
  def getNewDirs(self, old_dir, new_dir):
    if old_dir[-1] != os.sep:
      old_dir += os.sep
    if new_dir[-1] != os.sep:
      new_dir += os.sep
    old_set = self.getSetDirsForDir(old_dir)
    new_set = self.getSetDirsForDir(new_dir)
    return new_set.difference(old_set)
    
917
  # svn del files that have been removed in new dir
918
  def deleteOldFiles(self, old_dir, new_dir, bt):
919
    # detect removed files
920
    files_set = self.getNewFiles(new_dir, old_dir)
921 922
    # detect removed directories
    dirs_set = self.getNewDirs(new_dir, old_dir)
923
    # svn del
924 925 926 927 928 929
    list = [x for x in files_set]
    list.sort()
    self.remove([os.path.join(old_dir, x[1]) for x in list])
    list = [x for x in dirs_set]
    list.sort()
    self.remove([os.path.join(old_dir, x[1]) for x in list])
930
  
931 932
  # copy files and add new files
  def addNewFiles(self, old_dir, new_dir, bt):
933
    # detect created files
934
    files_set = self.getNewFiles(old_dir, new_dir)
935 936
    # detect created directories
    dirs_set = self.getNewDirs(old_dir, new_dir)
937
    # Copy files
938
    copytree(new_dir, old_dir)
939
    # svn add
940 941 942 943 944 945
    list = [x for x in dirs_set]
    list.sort()
    self.add([os.path.join(old_dir, x[1]) for x in list])
    list = [x for x in files_set]
    list.sort()
    self.add([os.path.join(old_dir, x[1]) for x in list])
946
  
947 948
  def treeToXML(self, item, bt) :
    working_copy = self.getSubversionPath(bt, False) + os.sep
949 950
    output = "<?xml version='1.0' encoding='iso-8859-1'?>"+ os.linesep
    output += "<tree id='0'>" + os.linesep
951
    output = self._treeToXML(item, working_copy, output, 1, True)
952 953
    output += "</tree>" + os.linesep
    return output
954
  
955
  def _treeToXML(self, item, working_copy, output, ident, first) :
956
    # Choosing a color coresponding to the status
957
    itemStatus = item.msg_status
Christophe Dumez's avatar
Christophe Dumez committed
958 959
    if itemStatus == 'added' :
      itemColor='green'
960
    elif itemStatus == 'modified' or  itemStatus == 'replaced' :
Christophe Dumez's avatar
Christophe Dumez committed
961 962 963
      itemColor='orange'
    elif itemStatus == 'deleted' :
      itemColor='red'
964 965
    elif itemStatus == 'conflicted' :
      itemColor='grey'
Christophe Dumez's avatar
Christophe Dumez committed
966 967
    else :
      itemColor='black'
968 969
    if isinstance(item, Dir) :
      for i in range(ident) :
970
        output += '\t'
Christophe Dumez's avatar
Christophe Dumez committed
971
      if first :
972
        output += '<item open="1" text="%s" id="%s" aCol="%s" '\
Christophe Dumez's avatar
Christophe Dumez committed
973
        'im0="folder.png" im1="folder_open.png" '\
974 975
        'im2="folder.png">'%(item.name, item.full_path.replace(working_copy, ''), itemColor,) + os.linesep
        first = False
Christophe Dumez's avatar
Christophe Dumez committed
976
      else :
977
        output += '<item text="%s" id="%s" aCol="%s" im0="folder.png" ' \
978
      'im1="folder_open.png" im2="folder.png">'%(item.name,
979
item.full_path.replace(working_copy, ''), itemColor,) + os.linesep
980
      for it in item.sub_dirs:
981
        ident += 1
982
        output = self._treeToXML(item.getDir(it.name), working_copy, output, ident,
Christophe Dumez's avatar
Christophe Dumez committed
983
first)
984 985
        ident -= 1
      for i in range(ident) :
986 987
        output += '\t'
      output += '</item>' + os.linesep
988 989
    else :
      for i in range(ident) :
990 991
        output += '\t'
      output += '<item text="%s" id="%s" aCol="%s" im0="document.png"/>'\
992
                %(item.name, item.full_path.replace(working_copy, ''), itemColor,) + os.linesep
993
    return output
Yoshinori Okuji's avatar
Yoshinori Okuji committed
994 995
    
InitializeClass(SubversionTool)