SubversionTool.py 25.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
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
Aurel's avatar
Aurel committed
45 46 47 48

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

class Dir :
  # Constructor
61 62 63 64 65
  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
66 67 68

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

  # return directory in subdirs given its name
72
  def getDir(self, name):
73
    for d in self.sub_dirs:
74
      if d.name == name:
75 76
        return d
## End of Dir Class
77 78 79 80 81 82 83 84

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

85
  def __init__(self, raw_diff):
86 87 88 89 90
    if '@@' not in raw_diff:
      self.binary=True
      return
    else:
      self.binary=False
91
    self.header = raw_diff.split('@@')[0][:-1]
92
    # Getting file path in header
93
    self.path = self.header.split('====')[0][:-1].strip()
94
    # Getting revisions in header
95
    for line in self.header.split('\n'):
96 97
      if line.startswith('--- '):
        tmp = re.search('\\([\w\s]+\\)$', line)
98
        self.old_revision = tmp.string[tmp.start():tmp.end()][1:-1].strip()
99 100
      if line.startswith('+++ '):
        tmp = re.search('\\([\w\s]+\\)$', line)
101
        self.new_revision = tmp.string[tmp.start():tmp.end()][1:-1].strip()
102
    # Splitting the body from the header
103
    self.body = '\n'.join(raw_diff.strip().split('\n')[4:])
104
    # Now splitting modifications
105
    self.children = []
106 107
    first = True
    tmp = []
108
    for line in self.body.split('\n'):
109 110
      if line:
        if line.startswith('@@') and not first:
111
          self.children.append(CodeBlock('\n'.join(tmp)))
112 113 114 115
          tmp = [line,]
        else:
          first = False
          tmp.append(line)
116
    self.children.append(CodeBlock('\n'.join(tmp)))
117 118
    

119
  def _escape(self, data):
120 121 122 123 124 125 126 127 128 129
    """
      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
    
130
  def toHTML(self):
131
    # Adding header of the table
132 133 134
    if self.binary:
      return '<b>Binary File!</b><br><br><br>'
    
Christophe Dumez's avatar
Christophe Dumez committed
135
    html = '''
136 137 138 139
    <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
140
      <td style="background-color: black;" width="2"></td>
141
      <td style="background-color: grey"><b><center>%s</center></b></td>
Christophe Dumez's avatar
Christophe Dumez committed
142
    </tr>'''%(self.old_revision, self.new_revision)
Christophe Dumez's avatar
Christophe Dumez committed
143
    header_color = 'grey'
144
    for child in self.children:
145
      # Adding line number of the modification
Christophe Dumez's avatar
Christophe Dumez committed
146 147 148 149 150 151
      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'
152 153 154 155 156 157
      # 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
158 159
        new_line = new_line_tuple[0] or ' '
        old_line = old_line_tuple[0] or ' '
160 161
        i+=1
        html += '''    <tr height="18px">
Christophe Dumez's avatar
Christophe Dumez committed
162 163 164 165
        <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;'))
166
    html += '''  </tbody>
Christophe Dumez's avatar
Christophe Dumez committed
167
</table><br><br>'''
168 169 170 171 172 173 174 175 176 177 178 179 180 181
    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)

182
  def __init__(self, raw_diff):
183
    # Splitting body and header
184 185
    self.body = '\n'.join(raw_diff.split('\n')[1:])
    self.header = raw_diff.split('\n')[0]
186
    # Getting modifications lines
187 188
    tmp = re.search('^@@ -\d+', self.header)
    self.old_line = tmp.string[tmp.start():tmp.end()][4:]
Christophe Dumez's avatar
Christophe Dumez committed
189 190
    tmp = re.search('\+\d+', self.header)
    self.new_line = tmp.string[tmp.start():tmp.end()][1:]
191 192
    # Splitting modifications in SubCodeBlocks
    in_modif = False
193
    self.children = []
194
    tmp=[]
195
    for line in self.body.split('\n'):
196 197 198 199 200
      if line:
        if (line.startswith('+') or line.startswith('-')):
          if in_modif:
            tmp.append(line)
          else:
201
            self.children.append(SubCodeBlock('\n'.join(tmp)))
202 203 204 205
            tmp = [line,]
            in_modif = True
        else:
            if in_modif:
206
              self.children.append(SubCodeBlock('\n'.join(tmp)))
207 208 209 210
              tmp = [line,]
              in_modif = False
            else:
              tmp.append(line)
211
    self.children.append(SubCodeBlock('\n'.join(tmp)))
212 213
    
  # Return code before modification
214
  def getOldCodeList(self):
215
    tmp = []
216
    for child in self.children:
217 218 219 220
      tmp.extend(child.getOldCodeList())
    return tmp
    
  # Return code after modification
221
  def getNewCodeList(self):
222
    tmp = []
223
    for child in self.children:
224 225 226 227 228
      tmp.extend(child.getNewCodeList())
    return tmp
    
# a SubCodeBlock contain 0 or 1 modification (not more)
class SubCodeBlock:
229
  def __init__(self, code):
230 231
    self.body = code
    self.modification = self._getModif()
Christophe Dumez's avatar
Christophe Dumez committed
232 233
    self.old_code_length = self._getOldCodeLength()
    self.new_code_length = self._getNewCodeLength()
234
    # Choosing background color
235 236 237 238 239 240
    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
241
    else: # addition
242
      self.color = 'rgb(83, 253, 74);'#light green
243
    
244
  def _getModif(self):
245 246
    nb_plus = 0
    nb_minus = 0
247
    for line in self.body.split('\n'):
248 249 250 251 252 253
      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
254 255 256 257
    if (nb_minus==0):
      return 'addition'
    if (nb_plus==0):
      return 'deletion'
258
    return 'change'
Christophe Dumez's avatar
Christophe Dumez committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272
      
  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
273
  
274
  # Return code before modification
275 276
  def getOldCodeList(self):
    if self.modification=='none':
277
      old_code = [(x, 'white') for x in self.body.split('\n')]
Christophe Dumez's avatar
Christophe Dumez committed
278 279 280 281 282 283
    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)
284
    else: # deletion or addition
285 286
      old_code = [self._getOldCodeList(x) for x in self.body.split('\n')]
    return old_code
287
  
288
  def _getOldCodeList(self, line):
289
    if line.startswith('+'):
290
      return (None, self.color)
291
    if line.startswith('-'):
292 293
      return (' '+line[1:], self.color)
    return (line, self.color)
294 295
  
  # Return code after modification
296 297
  def getNewCodeList(self):
    if self.modification=='none':
298
      new_code = [(x, 'white') for x in self.body.split('\n')]
Christophe Dumez's avatar
Christophe Dumez committed
299 300 301 302 303 304
    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)
305
    else: # deletion or addition
306 307
      new_code = [self._getNewCodeList(x) for x in self.body.split('\n')]
    return new_code
308
  
309
  def _getNewCodeList(self, line):
310
    if line.startswith('-'):
311
      return (None, self.color)
312
    if line.startswith('+'):
313 314
      return (' '+line[1:], self.color)
    return (line, self.color)
315
  
Yoshinori Okuji's avatar
Yoshinori Okuji committed
316 317 318 319 320 321 322 323 324 325 326
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')
327

Yoshinori Okuji's avatar
Yoshinori Okuji committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  # 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
369 370 371 372
    
  def setWorkingDirectory(self, path):
    self.workingDirectory = path
    os.chdir(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
373 374 375 376 377 378 379 380

  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
381
    
Christophe Dumez's avatar
Christophe Dumez committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
  
  # path is the path in svn working copy
  def editPath(self, bt, path):
    """Return path to edit file
    """
    if os.path.isdir(path):
      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 += '/'
    svn_path = svn_path + bt.getTitle() + '/'
    edit_path = path.replace(svn_path, '')
    edit_path = '/'.join(edit_path.split('/')[1:])
    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
404 405 406 407 408 409 410 411
  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))
    
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
  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
427
    expires = (DateTime() + 7).toZone('GMT').rfc822()
428
    request.set(self.login_cookie_name, value)
429
    response.setCookie(self.login_cookie_name, value, path = '/', expires = expires)
430

Yoshinori Okuji's avatar
Yoshinori Okuji committed
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
  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
450
    trust_item_list, permanent = loads(b64decode(trust))
Yoshinori Okuji's avatar
Yoshinori Okuji committed
451
    return dict(trust_item_list), permanent
452 453 454 455
  
  def diffHTML(self, file_path):
    raw_diff = self.diff(file_path)
    return DiffFile(raw_diff).toHTML()
Christophe Dumez's avatar
Christophe Dumez committed
456 457
  
  # Display a file content in HTML
Christophe Dumez's avatar
Christophe Dumez committed
458
  def fileHTML(self, bt, file_path):
Christophe Dumez's avatar
Christophe Dumez committed
459 460 461 462 463 464 465 466 467 468 469
#     file = open(file_path, 'r')
#     text = file.read()
#     file.close()
#     # Escaping
#     text = text.replace("&", "&amp;")
#     text = text.replace(">", "&gt;")
#     text = text.replace("<", "&lt;")
#     # Adding HTML stuff
#     text = text.replace('\n', '<br>')
#     text = text.replace('\t', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
#     text = text.replace('  ', '&nbsp;&nbsp;')
Christophe Dumez's avatar
Christophe Dumez committed
470
    head = "<b>"+file_path+"</b>  <a href='"+self.editPath(bt, file_path)+"'><img src='imgs/edit.png' border='0'></a><hr>"
471
    text = commands.getoutput('enscript -B --color --line-numbers --highlight=html --language=html -o - %s'%file_path)
Christophe Dumez's avatar
Christophe Dumez committed
472
    text = head + '\n'.join(text.split('\n')[10:-4])
Christophe Dumez's avatar
Christophe Dumez committed
473
    return text
Yoshinori Okuji's avatar
Yoshinori Okuji committed
474 475 476 477 478 479 480 481 482 483
    
  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
484
      trust_list.append(cookie)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
485 486 487 488
    # 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
489
    expires = (DateTime() + 7).toZone('GMT').rfc822()
490
    request.set(self.ssl_trust_cookie_name, value)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
491
    response.setCookie(self.ssl_trust_cookie_name, value, path = '/', expires = expires)
Christophe Dumez's avatar
Christophe Dumez committed
492 493 494
    
  def acceptSSLPerm(self, trust_dict):
    self.acceptSSLServer(self, trust_dict, True)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

  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()
518
    return client.update(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
519 520 521 522 523 524

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

527 528 529 530 531 532 533 534 535 536
  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
537 538 539 540 541 542 543
  security.declareProtected('Import/Export objects', 'log')
  def log(self, path):
    """return log of a file or dir
    """
    client = self._getClient()
    return client.log(path)
  
544 545 546 547 548 549 550 551 552 553
  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
554 555 556 557 558
  security.declareProtected('Import/Export objects', 'remove')
  def remove(self, path):
    """Remove a file or a directory.
    """
    client = self._getClient()
559
    return client.remove(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
560 561 562 563 564 565 566 567

  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
568 569 570 571 572 573 574
  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
575 576 577 578 579
  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
580
    return client.diff(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
581 582 583 584 585 586

  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
587
    return client.revert(path)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
588 589

  security.declareProtected('Import/Export objects', 'checkin')
590
  def checkin(self, path, log_message = 'None', recurse=True):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
591 592
    """Commit local changes.
    """
593
    client = self._getClient(login=self.login)
594
    return client.checkin(path, log_message, recurse)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
595 596 597 598 599 600

  security.declareProtected('Import/Export objects', 'status')
  def status(self, path, **kw):
    """Get status.
    """
    client = self._getClient()
Christophe Dumez's avatar
Christophe Dumez committed
601
    return client.status(path, **kw)
602 603
  
  def getModifiedTree(self, path) :
Christophe Dumez's avatar
Christophe Dumez committed
604
    # Remove trailing slash if it's present
605 606 607
    if path[-1]=="/" :
      path = path[:-1]
    
Christophe Dumez's avatar
Christophe Dumez committed
608
    root = Dir(path, "normal")
609
    somethingModified = False
610
    
611
    for statusObj in self.status(path) :
612
      # can be (normal, added, modified, deleted, conflicted, unversioned)
613
      msg_status = statusObj.getTextStatus()
614
      if str(msg_status) != "normal" and str(msg_status) != "unversioned":
615
        somethingModified = True
Christophe Dumez's avatar
Christophe Dumez committed
616 617 618 619
        full_path = statusObj.getPath()
        full_path_list = full_path.split('/')[1:]
        relative_path = full_path[len(path)+1:]
        relative_path_list = relative_path.split('/')
620
        # Processing entry
Christophe Dumez's avatar
Christophe Dumez committed
621 622 623
        filename = relative_path_list[-1]
        # Needed or files will be both File & Dir objects
        relative_path_list = relative_path_list[:-1]
624
        parent = root
Christophe Dumez's avatar
Christophe Dumez committed
625 626 627 628 629
        i = len(path.split('/'))-1
        
        for d in relative_path_list :
          i += 1
          if d :
630
            full_pathOfd = '/'+'/'.join(full_path_list[:i]).strip()
631
            if d not in parent.getSubDirs() :
632
              parent.sub_dirs.append(Dir(full_pathOfd, "normal"))
633
            parent = parent.getDir(d)
Christophe Dumez's avatar
Christophe Dumez committed
634
        if os.path.isdir(full_path) :
635 636
          if full_path == parent.full_path :
            parent.msg_status = str(msg_status)
637 638
          elif filename not in parent.getSubDirs() :
            parent.sub_dirs.append(Dir(filename, str(msg_status)))
Christophe Dumez's avatar
Christophe Dumez committed
639
          else :
640
            tmp = parent.getDir(filename)
641
            tmp.msg_status = str(msg_status)
Christophe Dumez's avatar
Christophe Dumez committed
642
        else :
Christophe Dumez's avatar
Christophe Dumez committed
643
          parent.sub_dirs.append(File(full_path, str(msg_status)))
644
    return somethingModified and root
645
  
646 647 648
  def extractBT(self, bt):
    path = mktemp()
    #os.system('rm -rf %s'%path)
649 650
    bt.export(path=path, local=1)
    svn_path = self.getPortalObject().portal_preferences.getPreference('subversion_working_copy')
651
    if not svn_path :
652 653 654 655 656 657 658 659 660 661
      raise "Error: Please set Subversion working path in preferences"
    if svn_path[-1]!='/':
      svn_path+='/'
    svn_path += bt.getTitle()+'/'
    if path[-1]!='/':
      path+='/'
    # svn del deleted files
    self.deleteOldFiles(svn_path, path)
    # add new files and copy
    self.addNewFiles(svn_path, path)
662 663
    # Clean up
    os.system('rm -rf %s'%path)
664 665 666 667
  
  # svn del files that have been removed in new dir
  def deleteOldFiles(self, old_dir, new_dir):
    # detect removed files
668
    output = commands.getoutput('export LC_ALL=c;diff -rq %s %s --exclude .svn | grep "Only in " | grep -v "svn-commit." | grep %s | cut -d" " -f3,4'%(new_dir, old_dir, old_dir)).replace(': ', '/')
669 670 671 672
    files_list = output.split('\n')
    # svn del
    for file in files_list:
      if file:
673
        self.remove(file) 
674 675 676
  
  def addNewFiles(self, old_dir, new_dir):
    # detect created files
Christophe Dumez's avatar
Christophe Dumez committed
677
    output = commands.getoutput('LC_ALL=C diff -rq %s %s --exclude .svn | grep "Only in " | grep -v "svn-commit." | grep %s | cut -d" " -f3,4'%(new_dir, old_dir, new_dir)).replace(': ', '/')
678 679
    files_list = output.split('\n')
    # Copy files
680
    os.system('cp -af %s/* %s'%(new_dir, old_dir))
681 682 683
    # svn add
    for file in files_list:
      if file:
684
          self.add(file.replace(new_dir, old_dir))
685
  
686
  def treeToXML(self, item) :
687 688
    output = "<?xml version='1.0' encoding='iso-8859-1'?>"+ os.linesep
    output += "<tree id='0'>" + os.linesep
Christophe Dumez's avatar
Christophe Dumez committed
689
    output = self._treeToXML(item, output, 1, True)
690 691
    output += "</tree>" + os.linesep
    return output
692
  
Christophe Dumez's avatar
Christophe Dumez committed
693
  def _treeToXML(self, item, output, ident, first) :
694 695 696 697 698 699
    # 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 += '/'
700
    # Choosing a color coresponding to the status
701
    itemStatus = item.msg_status
Christophe Dumez's avatar
Christophe Dumez committed
702 703 704 705 706 707 708 709
    if itemStatus == 'added' :
      itemColor='green'
    elif itemStatus == 'modified' :
      itemColor='orange'
    elif itemStatus == 'deleted' :
      itemColor='red'
    else :
      itemColor='black'
710
      
711 712
    if isinstance(item, Dir) :
      for i in range(ident) :
713
        output += '\t'
Christophe Dumez's avatar
Christophe Dumez committed
714
      if first :
715
        output += '<item open="1" text="%s" id="%s" aCol="%s" '\
Christophe Dumez's avatar
Christophe Dumez committed
716
        'im0="folder.png" im1="folder_open.png" '\
717
        'im2="folder.png">'%(item.name,
718
item.full_path.replace(svn_path, ''), itemColor,) + os.linesep
Christophe Dumez's avatar
Christophe Dumez committed
719 720
        first=False
      else :
721
        output += '<item text="%s" id="%s" aCol="%s" im0="folder.png" ' \
722
      'im1="folder_open.png" im2="folder.png">'%(item.name,
723
item.full_path.replace(svn_path, ''), itemColor,) + os.linesep
724
      for it in item.sub_dirs:
725
        ident += 1
726
        output = self._treeToXML(item.getDir(it.name), output, ident,
Christophe Dumez's avatar
Christophe Dumez committed
727
first)
728 729
        ident -= 1
      for i in range(ident) :
730 731
        output += '\t'
      output += '</item>' + os.linesep
732 733
    else :
      for i in range(ident) :
734 735
        output += '\t'
      output += '<item text="%s" id="%s" aCol="%s" im0="document.png"/>'\
736
                %(item.name, item.full_path.replace(svn_path, ''), itemColor,) + os.linesep
737
    return output
Yoshinori Okuji's avatar
Yoshinori Okuji committed
738 739
    
InitializeClass(SubversionTool)