CMS 3D CMS Logo

newFWLiteAna.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 from __future__ import print_function
4 import optparse
5 import os
6 import sys
7 import re
8 import shutil
9 
10 ccRE = re.compile (r'(\w+)\.cc')
11 
12 def extractBuildFilePiece (buildfile, copy, target = 'dummy'):
13  """Extracts necessary piece of the buildfile. Returns empty
14  string if not found."""
15  try:
16  build = open (buildfile, 'r')
17  except:
18  raise RuntimeError("Could not open BuildFile '%s' for reading. Aboring." \
19  % buildfile)
20  # make my regex
21  startBinRE = re.compile (r'<\s*bin\s+name=(\S+)')
22  endBinRE = re.compile (r'<\s*/bin>')
23  exeNameRE = re.compile (r'(\w+)\.exe')
24  ccName = os.path.basename (copy)
25  match = ccRE.match (ccName)
26  if match:
27  ccName = match.group (1)
28  retval = ''
29  foundBin = False
30  for line in build:
31  # Are we in the middle of copying what we need?
32  if foundBin:
33  retval += line
34  # Are we copying what we need and reach the end?
35  if foundBin and endBinRE.search (line):
36  # all done
37  break
38  # Is this the start of a bin line with the right name?
39  match = startBinRE.search (line)
40  if match:
41  # strip of .exe if it's there
42  exeName = match.group (1)
43  exeMatch = exeNameRE.search (exeName)
44  if exeMatch:
45  exeName = exeMatch.group (1)
46  if exeName == ccName:
47  foundBin = True
48  line = re.sub (exeName, target, line)
49  retval = line
50  build.close()
51  return retval
52 
53 
54 def createBuildFile (buildfile):
55  """Creates a BuildFile if one doesn't already exist"""
56  if os.path.exists (buildfile):
57  return
58  build = open (buildfile, 'w')
59  build.write ("<!-- -*- XML -*- -->\n\n<environment>\n\n</environment>\n")
60  build.close()
61 
62 
63 def addBuildPiece (targetBuild, buildPiece):
64  """Adds needed piece for new executable. Returns true upon
65  success."""
66  backup = targetBuild + ".bak"
67  shutil.copyfile (targetBuild, backup)
68  oldBuild = open (backup, 'r')
69  newBuild = open (targetBuild, 'w')
70  environRE = re.compile (r'<\s*environment')
71  success = False
72  for line in oldBuild:
73  newBuild.write (line)
74  if environRE.search (line):
75  newBuild.write ('\n\n')
76  newBuild.write (buildPiece)
77  success = True
78  oldBuild.close()
79  newBuild.close()
80  return success
81 
82 
83 
84 
89 
90 if __name__ == '__main__':
91  # We need CMSSW to already be setup
92  base = os.environ.get ('CMSSW_BASE')
93  release_base = os.environ.get ('CMSSW_RELEASE_BASE')
94  if not base or not release_base:
95  print("Error: You must have already setup a CMSSW release. Aborting.")
96  sys.exit()
97  # setup the options
98  parser = optparse.OptionParser('usage: %prog [options] '
99  'Package/SubPackage/name\n'
100  'Creates new analysis code')
101  parser.add_option ('--copy', dest='copy', type='string', default = 'blank',
102  help='Copies example. COPY should either be a file'
103  ' _or_ an example in PhysicsTools/FWLite/examples')
104  parser.add_option ('--newPackage', dest='newPackage', action='store_true',
105  help='Will create Package/Subpackage folders if necessary')
106  parser.add_option ('--toTest', dest='toTest', action='store_true',
107  help='Will create files in test/ instead of bin/')
108  (options, args) = parser.parse_args()
109  # get the name of the copy file and make sure we can find everything
110  copy = options.copy
111  if not re.search ('\.cc$', copy):
112  copy += '.cc'
113  buildCopy = os.path.dirname (copy)
114  if len (buildCopy):
115  buildCopy += '/BuildFile'
116  else:
117  buildCopy = 'BuildFile'
118  found = False
119  searchList = ['',
120  base + "/src/PhysicsTools/FWLite/examples/",
121  release_base+ "/src/PhysicsTools/FWLite/examples/"]
122  fullName = ''
123  fullBuild = ''
124  for where in searchList:
125  name = where + copy
126  build = where + buildCopy
127  # Is the copy file here
128  if os.path.exists (name):
129  # Yes.
130  found = True
131  # Is there a Buildfile too?
132  if not os.path.exists (build):
133  print("Error: Found '%s', but no accompying " % name, \
134  "Buildfile '%s'. Aborting" % build)
135  sys.exit()
136  fullName = name
137  fullBuild = build
138  break
139  if not found:
140  print("Error: Did not find '%s' to copy. Aborting." % copy)
141  sys.exit()
142  if len (args) != 1:
143  parser.print_usage()
144  sys.exit()
145  pieces = args[0].split('/')
146  if len (pieces) != 3:
147  print("Error: Need to provide 'Package/SubPackage/name'")
148  sys.exit()
149  target = pieces[2]
150  match = ccRE.match (target)
151  if match:
152  target = match.group (1)
153  buildPiece = extractBuildFilePiece (fullBuild, copy, target)
154  if not buildPiece:
155  print("Error: Could not extract necessary info from Buildfile. Aborting.")
156  sys.exit()
157  # print buildPiece
158  firstDir = base + '/src/' + pieces[0]
159  secondDir = firstDir + '/' + pieces[1]
160  if options.toTest:
161  bin = '/test'
162  else:
163  bin = '/bin'
164  if not os.path.exists (secondDir) and \
165  not options.newPackage:
166  raise RuntimeError("%s does not exist. Use '--newPackage' to create" \
167  % ("/".join (pieces[0:2]) ))
168  dirList = [firstDir, secondDir, secondDir + bin]
169  targetCC = dirList[2] + '/' + target + '.cc'
170  targetBuild = dirList[2] + '/BuildFile'
171  if os.path.exists (targetCC):
172  print('Error: "%s" already exists. Aborting.' % targetCC)
173  sys.exit()
174  # Start making directory structure
175  for currDir in dirList:
176  if not os.path.exists (currDir):
177  os.mkdir (currDir)
178  # copy the file over
179  shutil.copyfile (fullName, targetCC)
180  print("Copied:\n %s\nto:\n %s.\n" % (fullName, targetCC))
181  createBuildFile (targetBuild)
182  if extractBuildFilePiece (targetBuild, target):
183  print("Buildfile already has '%s'. Skipping" % target)
184  else :
185  # we don't already have a piece here
186  if addBuildPiece (targetBuild, buildPiece):
187  print("Added info to:\n %s." % targetBuild)
188  else:
189  print("Unable to modify Buildfile. Sorry.")
newFWLiteAna.extractBuildFilePiece
def extractBuildFilePiece(buildfile, copy, target='dummy')
Definition: newFWLiteAna.py:12
cms::dd::split
std::vector< std::string_view > split(std::string_view, const char *)
newFWLiteAna.addBuildPiece
def addBuildPiece(targetBuild, buildPiece)
Definition: newFWLiteAna.py:63
newFWLiteAna.createBuildFile
def createBuildFile(buildfile)
Definition: newFWLiteAna.py:54
edm::print
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66