test
CMS 3D CMS Logo

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
duplicateReflexLibrarySearch.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 import optparse
4 import os
5 import commands
6 import re
7 import sys
8 import pprint
9 import commands
10 import subprocess
11 from XML2Python import xml2obj
12 
13 # These aren't all typedefs, but can sometimes make the output more
14 # readable
15 typedefsDict = \
16  {
17  # What we want <= What we have
18  'unsigned int' : ['unsignedint', 'UInt32_t', 'uint32_t'],
19  'unsigned long': ['unsignedlong'],
20  'int' : ['Int32_t'],
21  'float' : ['Float_t'],
22  'double' : ['Double_t'],
23  'char' : ['Char_t'],
24  '< ' : ['<', '&lt;'],
25  ' >' : ['>', '&gt;'],
26  ', ' : [','],
27  }
28 
29 
30 # Equivalent names for packages - lets script know that, for example,
31 # 'TrackReco' package should have objects 'reco::Track'.
32 #Ordered List to search for matched packages
33 equivDict = \
34  [
35  {'TrackTriggerAssociation' : ['TTClusterAssociationMap','TTStubAssociationMap', '(TTStub|TTCluster).*edm::refhelper::FindForDetSetVector.*Phase2TrackerDigi.*']},
36  {'L1TCalorimeter' : ['l1t::CaloTower.*']},
37  {'GsfTracking' : ['reco::GsfTrack(Collection|).*(MomentumConstraint|VertexConstraint)', 'Trajectory.*reco::GsfTrack']},
38  {'ParallelAnalysis' : ['examples::TrackAnalysisAlgorithm']},
39  {'PatCandidates' : ['pat::PATObject','pat::Lepton']},
40  {'BTauReco' : ['reco::.*SoftLeptonTagInfo', 'reco::SoftLeptonProperties','reco::SecondaryVertexTagInfo','reco::IPTagInfo','reco::TemplatedSecondaryVertexTagInfo', 'reco::CATopJetProperties','reco::HTTTopJetProperties']},
41  {'CastorReco' : ['reco::CastorJet']},
42  {'JetMatching' : ['reco::JetFlavourInfo', 'reco::JetFlavour','reco::MatchedPartons']},
43  {'TrackingAnalysis' : ['TrackingParticle']},
44  {'Egamma' : ['reco::ElectronID']},
45  {'TopObjects' : ['reco::CATopJetProperties']},
46  {'TauReco' : ['reco::L2TauIsolationInfo','reco::RecoTauPiZero','reco::BaseTau']},
47  {'ValidationFormats' : ['PGlobalDigi::.+','PGlobalRecHit::.+']},
48  {'TrajectorySeed' : ['TrajectorySeed']},
49  {'TrackCandidate' : ['TrackCandidate']},
50  {'PatternTools' : ['MomentumConstraint','VertexConstraint','Trajectory']},
51  {'TrackerRecHit2D' : ['SiStrip(Matched|)RecHit[12]D','SiTrackerGSRecHit[12]D','SiPixelRecHit']},
52  {'MuonReco' : ['reco::Muon(Ref|)(Vector|)']},
53  {'MuonSeed' : ['L3MuonTrajectorySeed']},
54  {'HepMCCandidate' : ['reco::GenParticle.*']},
55  {'L1Trigger' : ['l1extra::L1.+Particle']},
56  {'TrackInfo' : ['reco::TrackingRecHitInfo']},
57  {'EgammaCandidates' : ['reco::GsfElectron.*','reco::Photon.*']},
58  {'HcalIsolatedTrack' : ['reco::IsolatedPixelTrackCandidate', 'reco::EcalIsolatedParticleCandidate', 'reco::HcalIsolatedTrackCandidate']},
59  {'HcalRecHit' : ['HFRecHit','HORecHit','ZDCRecHit','HBHERecHit']},
60  {'PFRootEvent' : ['EventColin::']},
61  {'CaloTowers' : ['CaloTower.*']},
62  {'GsfTrackReco' : ['GsfTrack.*']},
63  {'METReco' : ['reco::(Calo|PF|Gen|)MET','reco::PFClusterMET']},
64  {'ParticleFlowReco' : ['reco::RecoPFClusterRefCandidateRef.*']},
65  {'ParticleFlowCandidate' : ['reco::PFCandidateRef','reco::PFCandidateFwdRef','reco::PFCandidate']},
66  {'PhysicsToolsObjects' : ['PhysicsTools::Calibration']},
67  {'RecoCandidate' : ['reco::Candidate']},
68  {'TrackReco' : ['reco::Track','reco::TrackRef']},
69  {'VertexReco' : ['reco::Vertex']},
70  {'TFWLiteSelectorTest' : ['tfwliteselectortest']},
71  {'PatCandidates' : ['reco::RecoCandidate','pat::[A-Za-z]+Ref(Vector|)']},
72  {'JetReco' : ['reco::.*Jet','reco::.*Jet(Collection|Ref)']},
73  {'HGCDigi' : ['HGCSample']},
74  ]
75 
76 ignoreEdmDP = {
77  'LCGReflex/__gnu_cxx::__normal_iterator<std::basic_string<char>*,std::vector<std::basic_string<char>%>%>' : 1,
78  '' : 1
79 }
80 
82  """ Searches through the requested directory looking at
83  'classes_def.xml' files looking for duplicate Reflex definitions."""
84  # compile necessary RE statements
85  classNameRE = re.compile (r'class\s+name\s*=\s*"([^"]*)"')
86  spacesRE = re.compile (r'\s+')
87  stdRE = re.compile (r'std::')
88  srcClassNameRE = re.compile (r'(\w+)/src/classes_def.xml')
89  ignoreSrcRE = re.compile (r'.*/FWCore/Skeletons/scripts/mkTemplates/.+')
90  braketRE = re.compile (r'<.+>')
91  print "Searching for 'classes_def.xml' in '%s'." % os.path.join(os.environ.get('CMSSW_BASE'),'src')
92  xmlFiles = []
93  for srcDir in [os.environ.get('CMSSW_BASE'),os.environ.get('CMSSW_RELEASE_BASE')]:
94  if not len(srcDir): continue
95  for xml in commands.getoutput ('cd '+os.path.join(srcDir,'src')+'; find . -name "*classes_def.xml" -follow -print').split ('\n'):
96  if xml and (not xml in xmlFiles):
97  xmlFiles.append(xml)
98  if options.showXMLs:
99  pprint.pprint (xmlFiles)
100  # try and figure out the names of the packages
101  xmlPackages = []
102  packagesREs = {}
103  equivREs = {}
104  explicitREs = []
105  for item in equivDict:
106  for pack in item:
107  for equiv in item[pack]:
108  explicitREs.append( (re.compile(r'\b' + equiv + r'\b'),pack))
109  if options.lostDefs:
110  for filename in xmlFiles:
111  if (not filename) or (ignoreSrcRE.match(filename)): continue
112  match = srcClassNameRE.search (filename)
113  if not match: continue
114  packageName = match.group(1)
115  xmlPackages.append (packageName)
116  matchString = r'\b' + packageName + r'\b'
117  packagesREs[packageName] = re.compile (matchString)
118  equivList = equivREs.setdefault (packageName, [])
119  for item in equivDict:
120  for equiv in item.get (packageName, []):
121  matchString = re.compile(r'\b' + equiv + r'\b')
122  equivList.append( (matchString, equiv) )
123  equivList.append( (packagesREs[packageName], packageName) )
124  classDict = {}
125  ncdict = {'class' : 'className', 'function' : 'functionName'}
126  for filename in xmlFiles:
127  if (not filename) or (ignoreSrcRE.match(filename)): continue
128  dupProblems = ''
129  exceptName = ''
130  regexList = []
131  localObjects = []
132  simpleObjectREs = []
133  if options.lostDefs:
134  lostMatch = srcClassNameRE.search (filename)
135  if lostMatch:
136  exceptName = lostMatch.group (1)
137  regexList = equivREs[exceptName]
138  xcount = len(regexList)-1
139  if not regexList[xcount][0].search (exceptName):
140  print '%s not found in' % exceptName,
141  print regexList[xcount][0]
142  sys.exit()
143  else: continue
144  if options.verbose:
145  print "filename", filename
146  try:
147  filepath = os.path.join(os.environ.get('CMSSW_BASE'),'src',filename)
148  if not os.path.exists(filepath):
149  filepath = os.path.join(os.environ.get('CMSSW_RELEASE_BASE'),'src',filename)
150  xmlObj = xml2obj (filename = filepath,
151  filtering = True,
152  nameChangeDict = ncdict)
153  except Exception as detail:
154  print "File %s is malformed XML. Please fix." % filename
155  print " ", detail
156  continue
157  try:
158  classList = xmlObj.selection.className
159  except:
160  try:
161  classList = xmlObj.className
162  except:
163  # this isn't a real classes_def.xml file. Skip it
164  print "**** SKIPPING '%s' - Doesn't seem to have proper information." % filename
165  continue
166  if not classList:
167  classList = xmlObj.functionName
168  if not classList:
169  print "**** SKIPPING '%s' - Dosen't seem to have proper information(not class/function)." % filename
170  continue
171  for piece in classList:
172  try:
173  className = spacesRE.sub ('', piece.name)
174  except:
175  # must be one of these class pattern things. Skip it
176  #print " skipping %s" % filename, piece.__repr__()
177  continue
178  className = stdRE.sub ('', className)
179  # print " ", className
180  # Now get rid of any typedefs
181  for typedef, tdList in typedefsDict.iteritems():
182  for alias in tdList:
183  className = re.sub (alias, typedef, className)
184  classDict.setdefault (className, set()).add (filename)
185  # should we check for lost definitions?
186  if not options.lostDefs:
187  continue
188  localObjects.append (className)
189  if options.lazyLostDefs and not braketRE.search (className):
190  #print " ", className
191  matchString = r'\b' + className + r'\b'
192  simpleObjectREs.append( (re.compile (matchString), className ) )
193  for className in localObjects:
194  # if we see our name (or equivalent) here, then let's
195  # skip complaining about this
196  foundEquiv = False
197  for equivRE in regexList:
198  #print "searching %s for %s" % (equivRE[1], className)
199  if equivRE[0].search (className):
200  foundEquiv = True
201  break
202  for simpleRE in simpleObjectREs:
203  if simpleRE[0].search (className):
204  foundEquiv = True
205  if options.verbose and simpleRE[1] != className:
206  print " Using %s to ignore %s" \
207  % (simpleRE[1], className)
208  break
209  if foundEquiv: continue
210  for exRes in explicitREs:
211  if exRes[0].search(className):
212  dupProblems += " %s : %s\n" % (exRes[1], className)
213  foundEquiv = True
214  break
215  if foundEquiv: continue
216  for packageName in xmlPackages:
217  # don't bother looking for the name of this
218  # package in this package
219  if packagesREs[packageName].search (className):
220  dupProblems += " %s : %s\n" % (packageName, className)
221  break
222  # for piece
223  if dupProblems:
224  print '\n%s\n%s\n' % (filename, dupProblems)
225  # for filename
226  if options.dups:
227  for name, fileSet in sorted( classDict.iteritems() ):
228  if len (fileSet) < 2:
229  continue
230  print name
231  fileList = list (fileSet)
232  fileList.sort()
233  for filename in fileList:
234  print " ", filename
235  print
236  # for name, fileSet
237  # if not noDups
238  #pprint.pprint (classDict)
239 
240 
242  """ Searches the edmpluginFile to find any duplicate
243  plugins."""
244  edmpluginFile = ''
245  libenv = 'LD_LIBRARY_PATH'
246  if os.environ.get('SCRAM_ARCH').startswith('osx'): libenv = 'DYLD_FALLBACK_LIBRARY_PATH'
247  biglib = '/biglib/'+os.environ.get('SCRAM_ARCH')
248  for libdir in os.environ.get(libenv).split(':'):
249  if libdir.endswith(biglib): continue
250  if os.path.exists(libdir+'/.edmplugincache'): edmpluginFile = edmpluginFile + ' ' + libdir+'/.edmplugincache'
251  if edmpluginFile == '': edmpluginFile = os.path.join(os.environ.get('CMSSW_BASE'),'lib',os.environ.get('SCRAM_ARCH'),'.edmplugincache')
252  cmd = "cat %s | awk '{print $2\" \"$1}' | sort | uniq | awk '{print $1}' | sort | uniq -c | grep '2 ' | awk '{print $2}'" % edmpluginFile
253  output = commands.getoutput (cmd).split('\n')
254  for line in output:
255  if line in ignoreEdmDP: continue
256  line = line.replace("*","\*")
257  cmd = "cat %s | grep ' %s ' | awk '{print $1}' | sort | uniq " % (edmpluginFile,line)
258  out1 = commands.getoutput (cmd).split('\n')
259  print line
260  for plugin in out1:
261  if plugin:
262  print " **"+plugin+"**"
263  print
264 
265 if __name__ == "__main__":
266  # setup options parser
267  parser = optparse.OptionParser ("Usage: %prog [options]\n"\
268  "Searches classes_def.xml for wrong/duplicate "\
269  "definitions")
270  xmlGroup = optparse.OptionGroup (parser, "ClassDef XML options")
271  dumpGroup = optparse.OptionGroup (parser, "EdmPluginDump options")
272  xmlGroup.add_option ('--dups', dest='dups', action='store_true',
273  default=False,
274  help="Search for duplicate definitions")
275  xmlGroup.add_option ('--lostDefs', dest='lostDefs', action='store_true',
276  default=False,
277  help="Looks for definitions in the wrong libraries")
278  xmlGroup.add_option ('--lazyLostDefs', dest='lazyLostDefs',
279  action='store_true',
280  default=False,
281  help="Will try to ignore as many lost defs as reasonable")
282  xmlGroup.add_option ('--verbose', dest='verbose',
283  action='store_true',
284  default=False,
285  help="Prints out a lot of information")
286  xmlGroup.add_option ('--showXMLs', dest='showXMLs', action='store_true',
287  default=False,
288  help="Shows all 'classes_def.xml' files")
289  xmlGroup.add_option ('--dir', dest='srcdir', type='string', default='',
290  help="Obsolete")
291  dumpGroup.add_option ('--edmPD', dest='edmPD', action='store_true',
292  default=False,
293  help="Searches EDM Plugin Dump for duplicates")
294  dumpGroup.add_option ('--edmFile', dest='edmFile', type='string',
295  default='',
296  help="Obsolete")
297  parser.add_option_group (xmlGroup)
298  parser.add_option_group (dumpGroup)
299  (options, args) = parser.parse_args()
300 
301  # Let's go:
302  if options.lazyLostDefs:
303  options.lostDefs = True
304  if options.showXMLs or options.lostDefs or options.dups:
305  searchClassDefXml ()
306  if options.edmPD:
307  searchDuplicatePlugins ()
std::vector< T >::const_iterator search(const cond::Time_t &val, const std::vector< T > &container)
Definition: IOVProxy.cc:308
double split
Definition: MVATrainer.cc:139