CmpRuns.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #!/usr/bin/env python
  2. """
  3. CmpRuns - A simple tool for comparing two static analyzer runs to determine
  4. which reports have been added, removed, or changed.
  5. This is designed to support automated testing using the static analyzer, from
  6. two perspectives:
  7. 1. To monitor changes in the static analyzer's reports on real code bases, for
  8. regression testing.
  9. 2. For use by end users who want to integrate regular static analyzer testing
  10. into a buildbot like environment.
  11. Usage:
  12. # Load the results of both runs, to obtain lists of the corresponding
  13. # AnalysisDiagnostic objects.
  14. #
  15. resultsA = loadResultsFromSingleRun(singleRunInfoA, deleteEmpty)
  16. resultsB = loadResultsFromSingleRun(singleRunInfoB, deleteEmpty)
  17. # Generate a relation from diagnostics in run A to diagnostics in run B
  18. # to obtain a list of triples (a, b, confidence).
  19. diff = compareResults(resultsA, resultsB)
  20. """
  21. import os
  22. import plistlib
  23. import CmpRuns
  24. # Information about analysis run:
  25. # path - the analysis output directory
  26. # root - the name of the root directory, which will be disregarded when
  27. # determining the source file name
  28. class SingleRunInfo:
  29. def __init__(self, path, root="", verboseLog=None):
  30. self.path = path
  31. self.root = root.rstrip("/\\")
  32. self.verboseLog = verboseLog
  33. class AnalysisDiagnostic:
  34. def __init__(self, data, report, htmlReport):
  35. self._data = data
  36. self._loc = self._data['location']
  37. self._report = report
  38. self._htmlReport = htmlReport
  39. def getFileName(self):
  40. root = self._report.run.root
  41. fileName = self._report.files[self._loc['file']]
  42. if fileName.startswith(root) and len(root) > 0:
  43. return fileName[len(root)+1:]
  44. return fileName
  45. def getLine(self):
  46. return self._loc['line']
  47. def getColumn(self):
  48. return self._loc['col']
  49. def getCategory(self):
  50. return self._data['category']
  51. def getDescription(self):
  52. return self._data['description']
  53. def getIssueIdentifier(self) :
  54. id = self.getFileName() + "+"
  55. if 'issue_context' in self._data :
  56. id += self._data['issue_context'] + "+"
  57. if 'issue_hash' in self._data :
  58. id += str(self._data['issue_hash'])
  59. return id
  60. def getReport(self):
  61. if self._htmlReport is None:
  62. return " "
  63. return os.path.join(self._report.run.path, self._htmlReport)
  64. def getReadableName(self):
  65. return '%s:%d:%d, %s: %s' % (self.getFileName(), self.getLine(),
  66. self.getColumn(), self.getCategory(),
  67. self.getDescription())
  68. # Note, the data format is not an API and may change from one analyzer
  69. # version to another.
  70. def getRawData(self):
  71. return self._data
  72. class multidict:
  73. def __init__(self, elts=()):
  74. self.data = {}
  75. for key,value in elts:
  76. self[key] = value
  77. def __getitem__(self, item):
  78. return self.data[item]
  79. def __setitem__(self, key, value):
  80. if key in self.data:
  81. self.data[key].append(value)
  82. else:
  83. self.data[key] = [value]
  84. def items(self):
  85. return self.data.items()
  86. def values(self):
  87. return self.data.values()
  88. def keys(self):
  89. return self.data.keys()
  90. def __len__(self):
  91. return len(self.data)
  92. def get(self, key, default=None):
  93. return self.data.get(key, default)
  94. class CmpOptions:
  95. def __init__(self, verboseLog=None, rootA="", rootB=""):
  96. self.rootA = rootA
  97. self.rootB = rootB
  98. self.verboseLog = verboseLog
  99. class AnalysisReport:
  100. def __init__(self, run, files):
  101. self.run = run
  102. self.files = files
  103. self.diagnostics = []
  104. class AnalysisRun:
  105. def __init__(self, info):
  106. self.path = info.path
  107. self.root = info.root
  108. self.info = info
  109. self.reports = []
  110. # Cumulative list of all diagnostics from all the reports.
  111. self.diagnostics = []
  112. self.clang_version = None
  113. def getClangVersion(self):
  114. return self.clang_version
  115. def readSingleFile(self, p, deleteEmpty):
  116. data = plistlib.readPlist(p)
  117. # We want to retrieve the clang version even if there are no
  118. # reports. Assume that all reports were created using the same
  119. # clang version (this is always true and is more efficient).
  120. if 'clang_version' in data:
  121. if self.clang_version == None:
  122. self.clang_version = data.pop('clang_version')
  123. else:
  124. data.pop('clang_version')
  125. # Ignore/delete empty reports.
  126. if not data['files']:
  127. if deleteEmpty == True:
  128. os.remove(p)
  129. return
  130. # Extract the HTML reports, if they exists.
  131. if 'HTMLDiagnostics_files' in data['diagnostics'][0]:
  132. htmlFiles = []
  133. for d in data['diagnostics']:
  134. # FIXME: Why is this named files, when does it have multiple
  135. # files?
  136. assert len(d['HTMLDiagnostics_files']) == 1
  137. htmlFiles.append(d.pop('HTMLDiagnostics_files')[0])
  138. else:
  139. htmlFiles = [None] * len(data['diagnostics'])
  140. report = AnalysisReport(self, data.pop('files'))
  141. diagnostics = [AnalysisDiagnostic(d, report, h)
  142. for d,h in zip(data.pop('diagnostics'),
  143. htmlFiles)]
  144. assert not data
  145. report.diagnostics.extend(diagnostics)
  146. self.reports.append(report)
  147. self.diagnostics.extend(diagnostics)
  148. # Backward compatibility API.
  149. def loadResults(path, opts, root = "", deleteEmpty=True):
  150. return loadResultsFromSingleRun(SingleRunInfo(path, root, opts.verboseLog),
  151. deleteEmpty)
  152. # Load results of the analyzes from a given output folder.
  153. # - info is the SingleRunInfo object
  154. # - deleteEmpty specifies if the empty plist files should be deleted
  155. def loadResultsFromSingleRun(info, deleteEmpty=True):
  156. path = info.path
  157. run = AnalysisRun(info)
  158. if os.path.isfile(path):
  159. run.readSingleFile(path, deleteEmpty)
  160. else:
  161. for (dirpath, dirnames, filenames) in os.walk(path):
  162. for f in filenames:
  163. if (not f.endswith('plist')):
  164. continue
  165. p = os.path.join(dirpath, f)
  166. run.readSingleFile(p, deleteEmpty)
  167. return run
  168. def cmpAnalysisDiagnostic(d) :
  169. return d.getIssueIdentifier()
  170. def compareResults(A, B):
  171. """
  172. compareResults - Generate a relation from diagnostics in run A to
  173. diagnostics in run B.
  174. The result is the relation as a list of triples (a, b, confidence) where
  175. each element {a,b} is None or an element from the respective run, and
  176. confidence is a measure of the match quality (where 0 indicates equality,
  177. and None is used if either element is None).
  178. """
  179. res = []
  180. # Quickly eliminate equal elements.
  181. neqA = []
  182. neqB = []
  183. eltsA = list(A.diagnostics)
  184. eltsB = list(B.diagnostics)
  185. eltsA.sort(key = cmpAnalysisDiagnostic)
  186. eltsB.sort(key = cmpAnalysisDiagnostic)
  187. while eltsA and eltsB:
  188. a = eltsA.pop()
  189. b = eltsB.pop()
  190. if (a.getIssueIdentifier() == b.getIssueIdentifier()) :
  191. res.append((a, b, 0))
  192. elif a.getIssueIdentifier() > b.getIssueIdentifier():
  193. eltsB.append(b)
  194. neqA.append(a)
  195. else:
  196. eltsA.append(a)
  197. neqB.append(b)
  198. neqA.extend(eltsA)
  199. neqB.extend(eltsB)
  200. # FIXME: Add fuzzy matching. One simple and possible effective idea would be
  201. # to bin the diagnostics, print them in a normalized form (based solely on
  202. # the structure of the diagnostic), compute the diff, then use that as the
  203. # basis for matching. This has the nice property that we don't depend in any
  204. # way on the diagnostic format.
  205. for a in neqA:
  206. res.append((a, None, None))
  207. for b in neqB:
  208. res.append((None, b, None))
  209. return res
  210. def dumpScanBuildResultsDiff(dirA, dirB, opts, deleteEmpty=True):
  211. # Load the run results.
  212. resultsA = loadResults(dirA, opts, opts.rootA, deleteEmpty)
  213. resultsB = loadResults(dirB, opts, opts.rootB, deleteEmpty)
  214. # Open the verbose log, if given.
  215. if opts.verboseLog:
  216. auxLog = open(opts.verboseLog, "wb")
  217. else:
  218. auxLog = None
  219. diff = compareResults(resultsA, resultsB)
  220. foundDiffs = 0
  221. for res in diff:
  222. a,b,confidence = res
  223. if a is None:
  224. print "ADDED: %r" % b.getReadableName()
  225. foundDiffs += 1
  226. if auxLog:
  227. print >>auxLog, ("('ADDED', %r, %r)" % (b.getReadableName(),
  228. b.getReport()))
  229. elif b is None:
  230. print "REMOVED: %r" % a.getReadableName()
  231. foundDiffs += 1
  232. if auxLog:
  233. print >>auxLog, ("('REMOVED', %r, %r)" % (a.getReadableName(),
  234. a.getReport()))
  235. elif confidence:
  236. print "CHANGED: %r to %r" % (a.getReadableName(),
  237. b.getReadableName())
  238. foundDiffs += 1
  239. if auxLog:
  240. print >>auxLog, ("('CHANGED', %r, %r, %r, %r)"
  241. % (a.getReadableName(),
  242. b.getReadableName(),
  243. a.getReport(),
  244. b.getReport()))
  245. else:
  246. pass
  247. TotalReports = len(resultsB.diagnostics)
  248. print "TOTAL REPORTS: %r" % TotalReports
  249. print "TOTAL DIFFERENCES: %r" % foundDiffs
  250. if auxLog:
  251. print >>auxLog, "('TOTAL NEW REPORTS', %r)" % TotalReports
  252. print >>auxLog, "('TOTAL DIFFERENCES', %r)" % foundDiffs
  253. return foundDiffs, len(resultsA.diagnostics), len(resultsB.diagnostics)
  254. def main():
  255. from optparse import OptionParser
  256. parser = OptionParser("usage: %prog [options] [dir A] [dir B]")
  257. parser.add_option("", "--rootA", dest="rootA",
  258. help="Prefix to ignore on source files for directory A",
  259. action="store", type=str, default="")
  260. parser.add_option("", "--rootB", dest="rootB",
  261. help="Prefix to ignore on source files for directory B",
  262. action="store", type=str, default="")
  263. parser.add_option("", "--verbose-log", dest="verboseLog",
  264. help="Write additional information to LOG [default=None]",
  265. action="store", type=str, default=None,
  266. metavar="LOG")
  267. (opts, args) = parser.parse_args()
  268. if len(args) != 2:
  269. parser.error("invalid number of arguments")
  270. dirA,dirB = args
  271. dumpScanBuildResultsDiff(dirA, dirB, opts)
  272. if __name__ == '__main__':
  273. main()