CMS 3D CMS Logo

newFWLiteAna.py
Go to the documentation of this file.
1 #! /usr/bin/env python3
2 
3 from __future__ import print_function
4 from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
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 = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter, description='Creates new analysis code')
99  parser.add_argument('--copy', dest='copy', type=str, default = 'blank',
100  help='Copies example. COPY should either be a file'
101  ' _or_ an example in PhysicsTools/FWLite/examples')
102  parser.add_argument('--newPackage', dest='newPackage', action='store_true',
103  help='Will create Package/Subpackage folders if necessary')
104  parser.add_argument('--toTest', dest='toTest', action='store_true',
105  help='Will create files in test/ instead of bin/')
106  parser.add_argument("name", metavar="Package/SubPackage/name", type=str)
107  options = parser.parse_args()
108  # get the name of the copy file and make sure we can find everything
109  copy = options.copy
110  if not re.search ('\.cc$', copy):
111  copy += '.cc'
112  buildCopy = os.path.dirname (copy)
113  if len (buildCopy):
114  buildCopy += '/BuildFile'
115  else:
116  buildCopy = 'BuildFile'
117  found = False
118  searchList = ['',
119  base + "/src/PhysicsTools/FWLite/examples/",
120  release_base+ "/src/PhysicsTools/FWLite/examples/"]
121  fullName = ''
122  fullBuild = ''
123  for where in searchList:
124  name = where + copy
125  build = where + buildCopy
126  # Is the copy file here
127  if os.path.exists (name):
128  # Yes.
129  found = True
130  # Is there a Buildfile too?
131  if not os.path.exists (build):
132  print("Error: Found '%s', but no accompanying " % name, \
133  "Buildfile '%s'. Aborting" % build)
134  sys.exit()
135  fullName = name
136  fullBuild = build
137  break
138  if not found:
139  print("Error: Did not find '%s' to copy. Aborting." % copy)
140  sys.exit()
141  pieces = options.name.split('/')
142  if len (pieces) != 3:
143  print("Error: Need to provide 'Package/SubPackage/name'")
144  sys.exit()
145  target = pieces[2]
146  match = ccRE.match (target)
147  if match:
148  target = match.group (1)
149  buildPiece = extractBuildFilePiece (fullBuild, copy, target)
150  if not buildPiece:
151  print("Error: Could not extract necessary info from Buildfile. Aborting.")
152  sys.exit()
153  # print buildPiece
154  firstDir = base + '/src/' + pieces[0]
155  secondDir = firstDir + '/' + pieces[1]
156  if options.toTest:
157  bin = '/test'
158  else:
159  bin = '/bin'
160  if not os.path.exists (secondDir) and \
161  not options.newPackage:
162  raise RuntimeError("%s does not exist. Use '--newPackage' to create" \
163  % ("/".join (pieces[0:2]) ))
164  dirList = [firstDir, secondDir, secondDir + bin]
165  targetCC = dirList[2] + '/' + target + '.cc'
166  targetBuild = dirList[2] + '/BuildFile'
167  if os.path.exists (targetCC):
168  print('Error: "%s" already exists. Aborting.' % targetCC)
169  sys.exit()
170  # Start making directory structure
171  for currDir in dirList:
172  if not os.path.exists (currDir):
173  os.mkdir (currDir)
174  # copy the file over
175  shutil.copyfile (fullName, targetCC)
176  print("Copied:\n %s\nto:\n %s.\n" % (fullName, targetCC))
177  createBuildFile (targetBuild)
178  if extractBuildFilePiece (targetBuild, target):
179  print("Buildfile already has '%s'. Skipping" % target)
180  else :
181  # we don't already have a piece here
182  if addBuildPiece (targetBuild, buildPiece):
183  print("Added info to:\n %s." % targetBuild)
184  else:
185  print("Unable to modify Buildfile. Sorry.")
def addBuildPiece(targetBuild, buildPiece)
Definition: newFWLiteAna.py:63
def createBuildFile(buildfile)
Definition: newFWLiteAna.py:54
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def extractBuildFilePiece(buildfile, copy, target='dummy')
Definition: newFWLiteAna.py:12