Jython is just too useful

Recently I had to do this repeatedly while working on a project.
1) Revert files with extension .foo that are checked out from source control under a base directory structure.
2) Sync to the latest copy of these files.
3) Make a copy of these files with extension .foo in a directory that are in different directories underneath this base directory to files with different extension .bar.
4) Delete the original file from source control.
5) Add the copied file to the source control.
This could have been achieved manually or using a shell/perl script. Manually it would have taken me a long time, since I am not very comfortable with a shell or a perl script, thought I would write this in jython. It took me 10 minutes to come up with this script, and while doing so I found an extremely useful module, shutil. The script can be massaged a bit to make it more efficient.
Here’s the script that I wrote.

import os
import shutil
# define the source control commands here
delete = “p4 delete “
add = “p4 add “
forceSync = “p4 sync -f “
revert = “p4 revert “

def dirwalk(dir):
···”’walk a directory tree”’
···for f in os.listdir(dir):
······fullpath = os.path.join(dir, f)
······print “Looking at “+fullpath
······if os.path.isdir(fullpath) and not os.path.islink(fullpath):
·········dirwalk(fullpath)
·········if os.path.isfile(fullpath):
············s = String(fullpath)
············work(s, fullpath)

def work(myStr, thePath):
···if myStr.endsWith(sys.argv[2]):
······# first revert
······theStr = String(revert)
······cStr = theStr.concat(myStr)
······Runtime.getRuntime().exec(cStr)
······# now force sync the file
······theStr = String(forceSync)
······cStr = theStr.concat(myStr)
······Runtime.getRuntime().exec(cStr)
······# now copy the file to a different extension
······_myStr = myStr.replaceAll(sys.argv[2],sys.argv[3])
······# copy the file to the new extension
······shutil.copy(myStr, _myStr)
······# now delete the file from source control
······theStr = String(delete)
······cStr = theStr.concat(myStr)
······Runtime.getRuntime().exec(cStr)
······# now add the new file
······theStr = String(add)
······cStr = theStr.concat(_myStr)
······Runtime.getRuntime().exec(cStr)

“”"
Usage:
java weblogic.WLST c:/scripts/p4files.py d:/myfiles .foo .bar
This will revert all files under myfiles directory from source control, force sync’s the files,
copy the file to the given extension, deletes the file from source control and add the new file
to source control
“”"
dirwalk(sys.argv[1])

As you can see Jython is not only useful to call into Java objects you can also use it to call into operating system for file manipulation and also use most of the python modules with utmost ease.
This is one of the many many uses of Jython.

_uacct = “UA-2684269-2″;
urchinTracker();

Leave a Reply