from cvsgui.App import *
from cvsgui.Cvs import *
from cvsgui.CvsEntry import *
from cvsgui.Macro import *
import os, os.path
import string

"""
  WinCvs Macro "Change CVSROOT"
  $Revision: 1.1 $

  written by Oliver Giesen, Aug 2002
  contact:
    email:  ogware@gmx.net
    jabber: ogiesen@jabber.org
    icq:    18777742

  Feel free to modify or distribute in whichever way you like, 
   as long as it doesn't limit my personal rights to
   modify and redistribute this code.
   Apart from that the code is supplied "as-is", i.e. without warranty of any
   kind, either expressed or implied, regarding its quality or security.
   Have fun!

  ATTENTION:
   You will need at least WinCvs 1.3.4 to execute any Python macros
   from within WinCvs! This macro has been tested against WinCvs 1.3.8 .

  NOTE:
   In contrast to the previously existing TCL macros ChangeRoot.tcl
   and ChangeRootTk.tcl, this macro will actually look at the contents
   of each Root file and will only replace it if it matches a given
   value. This way you could run it on sandboxes that are composed from
   different repositories.
   
  ======
  Usage:

  - Select one or more folders containing valid sandboxes

  - Run the macro from the Macros|CVS menu

   ~A dialog will pop up asking you to confirm or enter the CVSROOT to be changed

  - Press "OK" when done

   ~Another dialog will pop up asking you for the new CVSROOT string.

  - Press "OK" when done

   ~The macro will dump a log of its operation to the console,
    reporting how many Root entries were changed

  =============
  Known Issues / "Un-niceties":

  - None so far.

  Please report any problems you may encounter or suggestions you might have
  to ogware@gmx.net .
    
"""

class ChangeRoot( Macro):
  def __init__( self):
    Macro.__init__( self, 'Change CVSROOT', MACRO_SELECTION, 0, 'CVS')

  def OnCmdUI( self, cmdui):
    self.sel = App.GetSelection()
    enabled = len( self.sel) > 0
    if enabled:
      for entry in self.sel:
        if entry.IsFile():
          enabled=0
          break
    cmdui.Enable( enabled)

  def getRoot( self, entry):
    if entry.IsUnknown():
      return ''
    else:
      root = os.path.join( entry.GetFullName(), 'CVS', 'Root')
      if( os.path.exists( root)):
        f_root = open( root, 'r')
        try:
          cvsroot = string.strip( f_root.readline())
          return cvsroot
        finally:
          f_root.close()
      else:
        return ''

  def changeRoot( self, entry):
    print 'checking %s ...\t'%entry.GetFullName(),
    root = os.path.join( entry.GetFullName(), 'CVS', 'Root')
    if( os.path.exists( root)):
      f_root = open( root, 'r+')
      try:
        try:
          if( self.oldroot == ''): # a blank oldroot forces replace without checking the previous value
            cvsroot = self.oldroot
          else:
            cvsroot = string.strip( f_root.readline())
            
          if( cvsroot == self.oldroot):
            f_root.seek( 0)
            f_root.write( self.newroot)
            f_root.truncate()
            self.count += 1
            print 'changed'
          else:
            print 'CVSROOT mismatch! (%s)'%cvsroot
        except:
          print 'file read/write error!'
      finally:
        f_root.close()
    else:
      print 'no Root file!'

  def changeRoots( self, dir):
    if not( dir.IsUnknown()):
      self.changeRoot( dir)
    entries = GetCvsEntriesList( dir.GetFullName())
    for entry in entries:
      if not( entry.IsFile()):
        self.changeRoots( entry)
  
  def Run( self):
    self.count = 0
    oldroot = self.getRoot( self.sel[0])
    msg = 'Enter the old CVSROOT that is to be changed\n' \
         +'(this is not the new CVSROOT!).\n\n' \
         +'Clear to change all existing CVSROOTs.\n\n' \
         +'Just press OK to accept current.'
    ok, self.oldroot = App.PromptEditMessage( msg, oldroot)
    if ok:
      if self.oldroot != '':
        oldroot = self.oldroot
      msg = 'Change old CVSROOT\n\n\t%s\n\nto new:' % self.oldroot
      ok, self.newroot = App.PromptEditMessage( msg, oldroot)
      if ok:
        print '\nchanging CVSROOT %s to %s ...' % ( self.oldroot, self.newroot)
        for entry in self.sel:
          self.changeRoots( entry)
        print 'Changed %d Root entries.\n' % self.count

ChangeRoot()
