CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_6_1_2_SLHC2_patch1/src/PhysicsTools/FWLite/scripts/newFWLiteAna.py

Go to the documentation of this file.
00001 #! /usr/bin/env python
00002 
00003 import optparse
00004 import os
00005 import sys
00006 import re
00007 import shutil
00008 
00009 ccRE = re.compile (r'(\w+)\.cc')
00010 
00011 def extractBuildFilePiece (buildfile, copy, target = 'dummy'):
00012     """Extracts necessary piece of the buildfile.  Returns empty
00013     string if not found."""    
00014     try:
00015         build = open (buildfile, 'r')
00016     except:        
00017         raise RuntimeError, \
00018               "Could not open BuildFile '%s' for reading. Aboring." \
00019               % buildfile
00020     # make my regex
00021     startBinRE = re.compile (r'<\s*bin\s+name=(\S+)')
00022     endBinRE   = re.compile (r'<\s*/bin>')
00023     exeNameRE  = re.compile (r'(\w+)\.exe')
00024     ccName = os.path.basename (copy)
00025     match = ccRE.match (ccName)
00026     if match:
00027         ccName = match.group (1)
00028     retval = ''
00029     foundBin = False
00030     for line in build:
00031         # Are we in the middle of copying what we need?
00032         if foundBin:
00033             retval += line
00034         # Are we copying what we need and reach the end?
00035         if foundBin and endBinRE.search (line):
00036             # all done
00037             break
00038         # Is this the start of a bin line with the right name?
00039         match = startBinRE.search (line)
00040         if match:
00041             # strip of .exe if it's there
00042             exeName = match.group (1)
00043             exeMatch = exeNameRE.search (exeName)
00044             if exeMatch:
00045                 exeName = exeMatch.group (1)
00046             if exeName == ccName:
00047                 foundBin = True
00048                 line = re.sub (exeName, target, line)
00049                 retval = line
00050     build.close()
00051     return retval
00052 
00053 
00054 def createBuildFile (buildfile):
00055     """Creates a BuildFile if one doesn't already exist"""
00056     if os.path.exists (buildfile):
00057         return
00058     build = open (buildfile, 'w')
00059     build.write ("<!-- -*- XML -*- -->\n\n<environment>\n\n</environment>\n")
00060     build.close()
00061 
00062 
00063 def addBuildPiece (targetBuild, buildPiece):
00064     """Adds needed piece for new executable.  Returns true upon
00065     success."""
00066     backup = targetBuild + ".bak"
00067     shutil.copyfile (targetBuild, backup)
00068     oldBuild = open (backup, 'r')
00069     newBuild = open (targetBuild, 'w')
00070     environRE = re.compile (r'<\s*environment')
00071     success = False
00072     for line in oldBuild:
00073         newBuild.write (line)
00074         if environRE.search (line):
00075             newBuild.write ('\n\n')
00076             newBuild.write (buildPiece)
00077             success = True
00078     oldBuild.close()
00079     newBuild.close()
00080     return success
00081         
00082 
00083 
00084 ########################
00085 ## ################## ##
00086 ## ## Main Program ## ##
00087 ## ################## ##
00088 ########################
00089 
00090 if __name__ == '__main__':
00091     # We need CMSSW to already be setup
00092     base         = os.environ.get ('CMSSW_BASE')
00093     release_base = os.environ.get ('CMSSW_RELEASE_BASE')
00094     if not base or not release_base:
00095         print "Error: You must have already setup a CMSSW release.  Aborting."
00096         sys.exit()
00097     # setup the options
00098     parser = optparse.OptionParser('usage: %prog [options] '
00099                                    'Package/SubPackage/name\n'
00100                                                                    'Creates new analysis code')
00101     parser.add_option ('--copy', dest='copy', type='string', default = 'blank',
00102                        help='Copies example. COPY should either be a file'
00103                        ' _or_ an example in PhysicsTools/FWLite/examples')
00104     parser.add_option ('--newPackage', dest='newPackage', action='store_true',
00105                        help='Will create Package/Subpackage folders if necessary')
00106     parser.add_option ('--toTest', dest='toTest', action='store_true',
00107                        help='Will create files in test/ instead of bin/')
00108     (options, args) = parser.parse_args()
00109     # get the name of the copy file and make sure we can find everything
00110     copy = options.copy
00111     if not re.search ('\.cc$', copy):
00112         copy += '.cc'
00113     buildCopy = os.path.dirname (copy)
00114     if len (buildCopy):
00115         buildCopy += '/BuildFile'
00116     else:
00117         buildCopy = 'BuildFile'
00118     found = False
00119     searchList = ['',
00120                   base + "/src/PhysicsTools/FWLite/examples/",
00121                   release_base+ "/src/PhysicsTools/FWLite/examples/"]
00122     fullName  = ''
00123     fullBuild = ''
00124     for where in searchList:        
00125         name  = where + copy
00126         build = where + buildCopy
00127         # Is the copy file here
00128         if os.path.exists (name):
00129             # Yes.
00130             found = True
00131             # Is there a Buildfile too?
00132             if not os.path.exists (build):
00133                 print "Error: Found '%s', but no accompying " % name, \
00134                       "Buildfile '%s'. Aborting" % build
00135                 sys.exit()
00136             fullName = name
00137             fullBuild = build
00138             break
00139     if not found:
00140         print "Error: Did not find '%s' to copy.  Aborting." % copy
00141         sys.exit()
00142     if len (args) != 1:
00143         parser.print_usage()
00144         sys.exit()
00145     pieces = args[0].split('/')
00146     if len (pieces) != 3:
00147         print "Error: Need to provide 'Package/SubPackage/name'"
00148         sys.exit()    
00149     target = pieces[2]
00150     match = ccRE.match (target)
00151     if match:
00152         target = match.group (1)    
00153     buildPiece = extractBuildFilePiece (fullBuild, copy, target)
00154     if not buildPiece:
00155         print "Error: Could not extract necessary info from Buildfile. Aborting."
00156         sys.exit()
00157     # print buildPiece
00158     firstDir  = base + '/src/' + pieces[0]
00159     secondDir = firstDir + '/' + pieces[1]
00160     if options.toTest:
00161         bin = '/test'
00162     else:
00163         bin = '/bin'
00164     if not os.path.exists (secondDir) and \
00165        not options.newPackage:
00166         raise RuntimeError, "%s does not exist.  Use '--newPackage' to create" \
00167               % ("/".join (pieces[0:2]) )
00168     dirList = [firstDir, secondDir, secondDir + bin]
00169     targetCC = dirList[2] + '/' + target + '.cc'
00170     targetBuild = dirList[2] + '/BuildFile'
00171     if os.path.exists (targetCC):
00172         print 'Error: "%s" already exists.  Aborting.' % targetCC
00173         sys.exit()
00174     # Start making directory structure
00175     for currDir in dirList:
00176         if not os.path.exists (currDir):
00177             os.mkdir (currDir)
00178     # copy the file over
00179     shutil.copyfile (fullName, targetCC)
00180     print "Copied:\n   %s\nto:\n   %s.\n" % (fullName, targetCC)
00181     createBuildFile (targetBuild)
00182     if extractBuildFilePiece (targetBuild, target):
00183         print "Buildfile already has '%s'.  Skipping" % target
00184     else :
00185         # we don't already have a piece here
00186         if addBuildPiece (targetBuild, buildPiece):
00187             print "Added info to:\n   %s." % targetBuild
00188         else:
00189             print "Unable to modify Buildfile.  Sorry."