cppcheck-py 2.9__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. cppcheck/__init__.py +55 -0
  2. cppcheck/cppcheck-2.9.tar.gz +0 -0
  3. cppcheck/data/addons/__init__.py +0 -0
  4. cppcheck/data/addons/cppcheck.py +39 -0
  5. cppcheck/data/addons/cppcheckdata.py +1529 -0
  6. cppcheck/data/addons/findcasts.py +33 -0
  7. cppcheck/data/addons/misc.py +163 -0
  8. cppcheck/data/addons/misra.py +4728 -0
  9. cppcheck/data/addons/misra_9.py +513 -0
  10. cppcheck/data/addons/naming.py +91 -0
  11. cppcheck/data/addons/namingng.py +253 -0
  12. cppcheck/data/addons/runaddon.py +12 -0
  13. cppcheck/data/addons/threadsafety.py +39 -0
  14. cppcheck/data/addons/y2038.py +252 -0
  15. cppcheck/data/cfg/avr.cfg +431 -0
  16. cppcheck/data/cfg/bento4.cfg +142 -0
  17. cppcheck/data/cfg/boost.cfg +1268 -0
  18. cppcheck/data/cfg/bsd.cfg +546 -0
  19. cppcheck/data/cfg/cairo.cfg +88 -0
  20. cppcheck/data/cfg/cppcheck-lib.cfg +72 -0
  21. cppcheck/data/cfg/cppunit.cfg +48 -0
  22. cppcheck/data/cfg/daca.cfg +31 -0
  23. cppcheck/data/cfg/dpdk.cfg +11 -0
  24. cppcheck/data/cfg/embedded_sql.cfg +4 -0
  25. cppcheck/data/cfg/emscripten.cfg +7 -0
  26. cppcheck/data/cfg/ginac.cfg +12848 -0
  27. cppcheck/data/cfg/gnu.cfg +1626 -0
  28. cppcheck/data/cfg/googletest.cfg +60 -0
  29. cppcheck/data/cfg/gtk.cfg +20584 -0
  30. cppcheck/data/cfg/icu.cfg +6 -0
  31. cppcheck/data/cfg/kde.cfg +51 -0
  32. cppcheck/data/cfg/libcerror.cfg +128 -0
  33. cppcheck/data/cfg/libcurl.cfg +487 -0
  34. cppcheck/data/cfg/libsigc++.cfg +36 -0
  35. cppcheck/data/cfg/lua.cfg +316 -0
  36. cppcheck/data/cfg/mfc.cfg +256 -0
  37. cppcheck/data/cfg/microsoft_atl.cfg +40 -0
  38. cppcheck/data/cfg/microsoft_sal.cfg +491 -0
  39. cppcheck/data/cfg/microsoft_unittest.cfg +20 -0
  40. cppcheck/data/cfg/motif.cfg +318 -0
  41. cppcheck/data/cfg/nspr.cfg +38 -0
  42. cppcheck/data/cfg/ntl.cfg +6907 -0
  43. cppcheck/data/cfg/opencv2.cfg +132 -0
  44. cppcheck/data/cfg/opengl.cfg +580 -0
  45. cppcheck/data/cfg/openmp.cfg +157 -0
  46. cppcheck/data/cfg/openssl.cfg +174 -0
  47. cppcheck/data/cfg/pcre.cfg +165 -0
  48. cppcheck/data/cfg/posix.cfg +6252 -0
  49. cppcheck/data/cfg/python.cfg +674 -0
  50. cppcheck/data/cfg/qt.cfg +5255 -0
  51. cppcheck/data/cfg/ruby.cfg +142 -0
  52. cppcheck/data/cfg/sdl.cfg +354 -0
  53. cppcheck/data/cfg/sfml.cfg +301 -0
  54. cppcheck/data/cfg/sqlite3.cfg +1527 -0
  55. cppcheck/data/cfg/std.cfg +8716 -0
  56. cppcheck/data/cfg/tinyxml2.cfg +56 -0
  57. cppcheck/data/cfg/vcl.cfg +4 -0
  58. cppcheck/data/cfg/windows.cfg +17941 -0
  59. cppcheck/data/cfg/wxsqlite3.cfg +1955 -0
  60. cppcheck/data/cfg/wxsvg.cfg +16905 -0
  61. cppcheck/data/cfg/wxwidgets.cfg +16464 -0
  62. cppcheck/data/cfg/zlib.cfg +1450 -0
  63. cppcheck/data/cppcheck-htmlreport +986 -0
  64. cppcheck/data/cppcheck.exe +0 -0
  65. cppcheck/data/platforms/aix_ppc64.xml +17 -0
  66. cppcheck/data/platforms/arm32-wchar_t2.xml +17 -0
  67. cppcheck/data/platforms/arm32-wchar_t4.xml +17 -0
  68. cppcheck/data/platforms/arm64-wchar_t2.xml +17 -0
  69. cppcheck/data/platforms/arm64-wchar_t4.xml +17 -0
  70. cppcheck/data/platforms/avr8.xml +18 -0
  71. cppcheck/data/platforms/cray_sv1.xml +17 -0
  72. cppcheck/data/platforms/elbrus-e1cp.xml +18 -0
  73. cppcheck/data/platforms/mips32.xml +18 -0
  74. cppcheck/data/platforms/msp430_eabi_large_datamodel.xml +17 -0
  75. cppcheck/data/platforms/pic16.xml +18 -0
  76. cppcheck/data/platforms/pic8-enhanced.xml +18 -0
  77. cppcheck/data/platforms/pic8.xml +18 -0
  78. cppcheck/data/platforms/unix32-unsigned.xml +17 -0
  79. cppcheck/data/platforms/unix64-unsigned.xml +17 -0
  80. cppcheck_py-2.9.dist-info/METADATA +76 -0
  81. cppcheck_py-2.9.dist-info/RECORD +84 -0
  82. cppcheck_py-2.9.dist-info/WHEEL +5 -0
  83. cppcheck_py-2.9.dist-info/entry_points.txt +4 -0
  84. cppcheck_py-2.9.dist-info/licenses/LICENSE.md +191 -0
@@ -0,0 +1,986 @@
1
+ #!/usr/bin/env python
2
+
3
+ from __future__ import unicode_literals
4
+
5
+ from datetime import date
6
+ import io
7
+ import locale
8
+ import operator
9
+ import optparse
10
+ import os
11
+ import re
12
+ import sys
13
+ import subprocess
14
+
15
+ from collections import Counter
16
+ from pygments import highlight
17
+ from pygments.lexers import guess_lexer, guess_lexer_for_filename
18
+ from pygments.formatters import HtmlFormatter # pylint: disable=no-name-in-module
19
+ from pygments.util import ClassNotFound
20
+ from xml.sax import parse as xml_parse
21
+ from xml.sax import SAXParseException as XmlParseException
22
+ from xml.sax.handler import ContentHandler as XmlContentHandler
23
+ from xml.sax.saxutils import escape
24
+ """
25
+ Turns a cppcheck xml file into a browsable html report along
26
+ with syntax highlighted source code.
27
+ """
28
+
29
+ STYLE_FILE = """
30
+ body {
31
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
32
+ font-size: 13px;
33
+ line-height: 1.5;
34
+ height: 100%;
35
+ margin: 0;
36
+ }
37
+
38
+ #wrapper {
39
+ position: fixed;
40
+ height: 100vh;
41
+ width: 100vw;
42
+ display: grid;
43
+ grid-template-rows: fit-content(8rem) auto fit-content(8rem);
44
+ grid-template-columns: fit-content(25%) 1fr;
45
+ grid-template-areas:
46
+ "header header"
47
+ "menu content"
48
+ "footer footer";
49
+ }
50
+
51
+ h1 {
52
+ margin: 0 0 8px -2px;
53
+ font-size: 175%;
54
+ }
55
+
56
+ .header {
57
+ padding: 0 0 5px 15px;
58
+ grid-area: header;
59
+ border-bottom: thin solid #aaa;
60
+ }
61
+
62
+ .footer {
63
+ grid-area: footer;
64
+ border-top: thin solid #aaa;
65
+ font-size: 85%;
66
+
67
+ }
68
+
69
+ .footer > p {
70
+ margin: 4px;
71
+ }
72
+
73
+ #menu,
74
+ #menu_index {
75
+ grid-area: menu;
76
+ text-align: left;
77
+ overflow: auto;
78
+ padding: 0 23px 15px 15px;
79
+ border-right: thin solid #aaa;
80
+ min-width: 200px;
81
+ }
82
+
83
+ #menu > a {
84
+ display: block;
85
+ margin-left: 10px;
86
+ font-size: 12px;
87
+ }
88
+
89
+ #content,
90
+ #content_index {
91
+ grid-area: content;
92
+ padding: 0px 5px 15px 15px;
93
+ overflow: auto;
94
+ }
95
+
96
+ label {
97
+ white-space: nowrap;
98
+ }
99
+
100
+ label.checkBtn.disabled {
101
+ color: #606060;
102
+ background: #e0e0e0;
103
+ font-style: italic;
104
+ }
105
+
106
+ label.checkBtn, input[type="text"] {
107
+ border: 1px solid grey;
108
+ border-radius: 4px;
109
+ box-shadow: 1px 1px inset;
110
+ padding: 1px 5px;
111
+ }
112
+
113
+ label.checkBtn {
114
+ white-space: nowrap;
115
+ background: #ccddff;
116
+ }
117
+
118
+ label.unchecked {
119
+ background: #eff8ff;
120
+ box-shadow: 1px 1px 1px;
121
+ }
122
+
123
+ label.checkBtn:hover, label.unchecked:hover{
124
+ box-shadow: 0 0 2px;
125
+ }
126
+
127
+ label.disabled:hover {
128
+ box-shadow: 1px 1px inset;
129
+ }
130
+
131
+ label.checkBtn > input {
132
+ display:none;
133
+ }
134
+
135
+ .summaryTable {
136
+ width: 100%;
137
+ }
138
+
139
+ table.summaryTable td { padding: 0 5px 0 5px; }
140
+
141
+ .statHeader, .severityHeader {
142
+ font-weight: bold;
143
+ }
144
+
145
+ .warning {
146
+ background-color: #ffffa7;
147
+ }
148
+
149
+ .error {
150
+ background-color: #ffb7b7;
151
+ }
152
+
153
+ .error2 {
154
+ background-color: #faa;
155
+ display: inline-block;
156
+ margin-left: 4px;
157
+ }
158
+
159
+ .inconclusive {
160
+ background-color: #b6b6b4;
161
+ }
162
+
163
+ .inconclusive2 {
164
+ background-color: #b6b6b4;
165
+ display: inline-block;
166
+ margin-left: 4px;
167
+ }
168
+
169
+ .verbose {
170
+ display: inline-block;
171
+ vertical-align: top;
172
+ cursor: help;
173
+ }
174
+
175
+ .verbose .content {
176
+ display: none;
177
+ position: absolute;
178
+ padding: 10px;
179
+ margin: 4px;
180
+ max-width: 40%;
181
+ white-space: pre-wrap;
182
+ border: 1px solid #000;
183
+ background-color: #ffffcc;
184
+ cursor: auto;
185
+ }
186
+
187
+ .highlight .hll {
188
+ padding: 1px;
189
+ }
190
+
191
+ .highlighttable {
192
+ background-color: #fff;
193
+ position: relative;
194
+ margin: -10px;
195
+ }
196
+
197
+ .linenos {
198
+ border-right: thin solid #aaa;
199
+ color: #d3d3d3;
200
+ padding-right: 6px;
201
+ }
202
+
203
+ .id-filtered, .severity-filtered, .file-filtered, .tool-filtered, .text-filtered {
204
+ visibility: collapse;
205
+ }
206
+ """
207
+
208
+ HTML_HEAD = """
209
+ <!doctype html>
210
+ <html lang="en">
211
+ <head>
212
+ <meta charset="utf-8">
213
+ <title>Cppcheck - HTML report - %s</title>
214
+ <link rel="stylesheet" href="style.css">
215
+ <style>
216
+ %s
217
+ </style>
218
+ <script>
219
+ function getStyle(el, styleProp) {
220
+ var y;
221
+
222
+ if (el.currentStyle) {
223
+ y = el.currentStyle[styleProp];
224
+ } else if (window.getComputedStyle) {
225
+ y = document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
226
+ }
227
+
228
+ return y;
229
+ }
230
+
231
+ function toggle() {
232
+ var el = this.expandable_content;
233
+ var mark = this.expandable_marker;
234
+
235
+ if (el.style.display === "block") {
236
+ el.style.display = "none";
237
+ mark.textContent = "[+]";
238
+ } else {
239
+ el.style.display = "block";
240
+ mark.textContent = "[-]";
241
+ }
242
+ }
243
+
244
+ function initExpandables() {
245
+ var elements = document.querySelectorAll(".expandable");
246
+
247
+ for (var i = 0, len = elements.length; i < len; i++) {
248
+ var el = elements[i];
249
+ var clickable = el.querySelector("span");
250
+ var marker = clickable.querySelector(".marker");
251
+ var content = el.querySelector(".content");
252
+ var width = clickable.clientWidth - parseInt(getStyle(content, "padding-left")) - parseInt(getStyle(content, "padding-right"));
253
+ content.style.width = width + "px";
254
+ clickable.expandable_content = content;
255
+ clickable.expandable_marker = marker;
256
+ clickable.addEventListener("click", toggle);
257
+ }
258
+ }
259
+
260
+ function toggleDisplay(cb) {
261
+ var elements = document.querySelectorAll("." + cb.id);
262
+
263
+ for (var i = 0, len = elements.length; i < len; i++) {
264
+ elements[i].classList.toggle("id-filtered", !cb.checked);
265
+ }
266
+
267
+ updateFileRows();
268
+ }
269
+
270
+ function toggleSeverity(cb) {
271
+ cb.parentElement.classList.toggle("unchecked", !cb.checked);
272
+ var elements = document.querySelectorAll(".sev_" + cb.id);
273
+
274
+ for (var i = 0, len = elements.length; i < len; i++) {
275
+ elements[i].classList.toggle("severity-filtered", !cb.checked);
276
+ }
277
+
278
+ updateFileRows();
279
+ }
280
+
281
+ function toggleTool(cb) {
282
+ cb.parentElement.classList.toggle("unchecked", !cb.checked);
283
+
284
+ var elements;
285
+ if (cb.id == "clang-tidy")
286
+ elements = document.querySelectorAll("[class^=clang-tidy-]");
287
+ else
288
+ elements = document.querySelectorAll(".issue:not([class^=clang-tidy-])");
289
+
290
+ for (var i = 0, len = elements.length; i < len; i++) {
291
+ elements[i].classList.toggle("tool-filtered", !cb.checked);
292
+ }
293
+
294
+ updateFileRows();
295
+ }
296
+
297
+ function toggleAll() {
298
+ var elements = document.querySelectorAll(".idToggle");
299
+
300
+ // starting from 1 since 0 is the "toggle all" input
301
+ for (var i = 1, len = elements.length; i < len; i++) {
302
+ var changed = elements[i].checked != elements[0].checked;
303
+ if (changed) {
304
+ elements[i].checked = elements[0].checked;
305
+ toggleDisplay(elements[i]);
306
+ }
307
+ }
308
+ }
309
+
310
+ function filterFile(filter) {
311
+ var elements = document.querySelectorAll(".fileEntry");
312
+
313
+ for (var i = 0, len = elements.length; i < len; i++) {
314
+ var visible = elements[i].querySelector("tr").querySelector("td").textContent.toLowerCase().includes(filter.toLowerCase());
315
+ elements[i].classList.toggle("text-filtered", !visible);
316
+ }
317
+ }
318
+
319
+ function filterText(text) {
320
+ filter = text.toLowerCase();
321
+ var elements = document.querySelectorAll(".issue");
322
+
323
+ for (var i = 0, len = elements.length; i < len; i++) {
324
+ var visible = false;
325
+ var fields = elements[i].querySelectorAll("td");
326
+ for (var n = 0, num = fields.length; n < num; n++) {
327
+ if (fields[n].textContent.toLowerCase().includes(filter)) {
328
+ visible = true;
329
+ break;
330
+ }
331
+ }
332
+ elements[i].classList.toggle("text-filtered", !visible);
333
+ }
334
+
335
+ updateFileRows();
336
+ }
337
+
338
+ function updateFileRows(element) {
339
+ var elements = document.querySelectorAll(".fileEntry");
340
+
341
+ for (var i = 0, len = elements.length; i < len; i++) {
342
+ var visible = elements[i].querySelector(".issue:not(.id-filtered):not(.severity-filtered):not(.tool-filtered):not(.text-filtered)");
343
+ elements[i].classList.toggle("file-filtered", !visible);
344
+ }
345
+ }
346
+
347
+ window.addEventListener("load", initExpandables);
348
+ </script>
349
+ </head>
350
+ <body>
351
+ <div id="wrapper">
352
+ <div id="header" class="header">
353
+ <h1>Cppcheck report - %s%s</h1>
354
+ """
355
+
356
+ HTML_HEAD_END = """
357
+ </div>
358
+ """
359
+
360
+ HTML_MENU = """
361
+ <div id="menu">
362
+ <p><a href="index.html">Defects:</a> %s</p>
363
+ """
364
+
365
+ HTML_MENU_END = """
366
+ </div>
367
+ <div id="content">
368
+ """
369
+
370
+ HTML_FOOTER = """
371
+ </div>
372
+ <div id="footer" class="footer">
373
+ <p>
374
+ Created by Cppcheck %s (<a href="https://cppcheck.sourceforge.io">Sourceforge</a>, <a href="irc://irc.freenode.net/cppcheck">IRC</a>)
375
+ </p>
376
+ </div>
377
+ </div>
378
+ </body>
379
+ </html>
380
+ """
381
+
382
+ HTML_ERROR = "<span class=\"error2\">&lt;--- %s</span>\n"
383
+ HTML_INCONCLUSIVE = "<span class=\"inconclusive2\">&lt;--- %s</span>\n"
384
+
385
+ HTML_EXPANDABLE_ERROR = "<div class=\"verbose expandable\"><span class=\"error2\">&lt;--- %s <span class=\"marker\">[+]</span></span><div class=\"content\">%s</div></div>\n"""
386
+ HTML_EXPANDABLE_INCONCLUSIVE = "<div class=\"verbose expandable\"><span class=\"inconclusive2\">&lt;--- %s <span class=\"marker\">[+]</span></span><div class=\"content\">%s</div></div>\n"""
387
+
388
+ # escape() and unescape() takes care of &, < and >.
389
+ html_escape_table = {
390
+ '"': "&quot;",
391
+ "'": "&apos;"
392
+ }
393
+ html_unescape_table = {v: k for k, v in html_escape_table.items()}
394
+
395
+
396
+ def html_escape(text):
397
+ return escape(text, html_escape_table)
398
+
399
+ def filter_button(enabled_filters, id, function):
400
+ enabled = enabled_filters.get(id, False)
401
+ return '\n <label class="checkBtn%s"><input type="checkbox" onclick="%s(this)" id="%s"%s/>%s</label>'\
402
+ % (' disabled' if not enabled else '', function, id, 'checked' if enabled else 'disabled', id)
403
+
404
+ def filter_bar(enabled):
405
+ return ''.join([
406
+ ' <div id="filters">\n'
407
+ ,''.join([filter_button(enabled, severity, 'toggleSeverity') for severity in ['error', 'warning', 'portability', 'performance', 'style', 'information']])
408
+ ,'\n | '
409
+ ,''.join([filter_button(enabled, tool, 'toggleTool') for tool in ['cppcheck', 'clang-tidy']])
410
+ ,'\n | '
411
+ ,'\n <label class="severityHeader">File: <input type="text" oninput="filterFile(this.value)"/></label>'
412
+ ,'\n <label class="severityHeader">Filter: <input type="text" oninput="filterText(this.value)"/></label>'
413
+ ,'\n </div>\n'])
414
+
415
+ def git_blame(errors, path, file, blame_options):
416
+ last_line= errors[-1]['line']
417
+ if last_line == 0:
418
+ return {}
419
+
420
+ first_line = next((error for error in errors if error['line'] > 0))['line']
421
+
422
+ full_path = os.path.join(path, file)
423
+ path, filename = os.path.split(full_path)
424
+
425
+ if path:
426
+ os.chdir(path)
427
+
428
+ cmd_args = ['git', 'blame', '-L %d,%d' % (first_line, last_line)]
429
+ if '-w' in blame_options:
430
+ cmd_args.append('-w')
431
+ if '-M' in blame_options:
432
+ cmd_args.append('-M')
433
+ cmd_args = cmd_args + ['--porcelain', '--incremental', '--', filename]
434
+
435
+ try:
436
+ result = subprocess.check_output(cmd_args)
437
+ result = result.decode(locale.getpreferredencoding())
438
+ except:
439
+ return []
440
+ finally:
441
+ os.chdir(cwd)
442
+
443
+ if result.startswith('fatal'):
444
+ return []
445
+
446
+ blame_data = []
447
+ line_from = 0
448
+ line_to = 0
449
+ blame_info = dict()
450
+
451
+ for line_str in result.splitlines():
452
+ field, _, value = line_str.partition(' ')
453
+ if len(field) == 40:
454
+ line_nr, count = value.split(' ')[1:]
455
+ line_from = int(line_nr)
456
+ line_to = line_from + int(count)
457
+ elif field.startswith('author'):
458
+ blame_info[field] = value
459
+ if field == 'author-time':
460
+ author_date = date.fromtimestamp(int(blame_info['author-time']))
461
+ blame_info['author-time'] = author_date.strftime("%d/%m/%Y")
462
+ elif field == 'filename':
463
+ blame_data.append([line_from, line_to, blame_info.copy()])
464
+
465
+ return blame_data
466
+
467
+
468
+ def blame_lookup(blame_data, line):
469
+ return next((data for start, end, data in blame_data if line >= start and line < end), {})
470
+
471
+
472
+ def tr_str(td_th, line, id, cwe, severity, message, author, author_mail, date, add_author, tr_class=None, htmlfile=None, message_class=None):
473
+ ret = ''
474
+ if htmlfile:
475
+ ret += '<%s><a href="%s#line-%d">%d</a></%s>' % (td_th, htmlfile, line, line, td_th)
476
+ for item in (id, cwe, severity):
477
+ ret += '<%s>%s</%s>' % (td_th, item, td_th)
478
+ else:
479
+ for item in (line, id, cwe, severity):
480
+ ret += '<%s>%s</%s>' % (td_th, item, td_th)
481
+ if message_class:
482
+ message_attribute = ' class="%s"' % message_class
483
+ else:
484
+ message_attribute = ''
485
+ ret += '<%s%s>%s</%s>' % (td_th, message_attribute, html_escape(message), td_th)
486
+
487
+ for field in add_author:
488
+ if field == 'name':
489
+ ret += '<%s>%s</%s>' % (td_th, html_escape(author), td_th)
490
+ elif field == 'email':
491
+ ret += '<%s>%s</%s>' % (td_th, html_escape(author_mail), td_th)
492
+ elif field == 'date':
493
+ ret += '<%s>%s</%s>' % (td_th, date, td_th)
494
+
495
+ if tr_class:
496
+ tr_attributes = ' class="%s"' % tr_class
497
+ else:
498
+ tr_attributes = ''
499
+ return '<tr%s>%s</tr>' % (tr_attributes, ret)
500
+
501
+
502
+ def to_css_selector(tag):
503
+ # https://www.w3.org/TR/CSS2/syndata.html#characters
504
+ # Note: for our usage, we don't consider escaped characters
505
+ invalid_css_chars = re.compile(r"[^-_a-zA-Z0-9\u00A0-\uFFFF]")
506
+ invalid_start = re.compile(r"^([0-9]|-[0-9]|--)")
507
+ # Replace forbidden characters by an hyphen
508
+ valid_chars = invalid_css_chars.sub("-", tag)
509
+ # Check that the start of the tag doesn't break the rules
510
+ start_invalid = invalid_start.match(valid_chars)
511
+ if start_invalid:
512
+ # otherwise, append a token to make it valid
513
+ valid_chars_valid_start = "cpp" + valid_chars
514
+ else:
515
+ valid_chars_valid_start = valid_chars
516
+ return valid_chars_valid_start
517
+
518
+ class AnnotateCodeFormatter(HtmlFormatter):
519
+ errors = []
520
+
521
+ def wrap(self, *args, **kwargs):
522
+ line_no = 1
523
+ for i, t in HtmlFormatter.wrap(self, *args, **kwargs):
524
+ # If this is a source code line we want to add a span tag at the
525
+ # end.
526
+ if i == 1:
527
+ for error in self.errors:
528
+ if error['line'] == line_no:
529
+ try:
530
+ if error['inconclusive'] == 'true':
531
+ # only print verbose msg if it really differs
532
+ # from actual message
533
+ if error.get('verbose') and (error['verbose'] != error['msg']):
534
+ index = t.rfind('\n')
535
+ t = t[:index] + HTML_EXPANDABLE_INCONCLUSIVE % (error['msg'], html_escape(error['verbose'].replace("\\012", '\n'))) + t[index + 1:]
536
+ else:
537
+ t = t.replace('\n', HTML_INCONCLUSIVE % error['msg'])
538
+ except KeyError:
539
+ if error.get('verbose') and (error['verbose'] != error['msg']):
540
+ index = t.rfind('\n')
541
+ t = t[:index] + HTML_EXPANDABLE_ERROR % (error['msg'], html_escape(error['verbose'].replace("\\012", '\n'))) + t[index + 1:]
542
+ else:
543
+ t = t.replace('\n', HTML_ERROR % error['msg'])
544
+
545
+ line_no = line_no + 1
546
+ yield i, t
547
+
548
+
549
+ class CppCheckHandler(XmlContentHandler):
550
+
551
+ """Parses the cppcheck xml file and produces a list of all its errors."""
552
+
553
+ def __init__(self):
554
+ XmlContentHandler.__init__(self)
555
+ self.errors = []
556
+ self.version = '1'
557
+ self.versionCppcheck = ''
558
+
559
+ def startElement(self, name, attributes):
560
+ if name == 'results':
561
+ self.version = attributes.get('version', self.version)
562
+
563
+ if self.version == '1':
564
+ self.handleVersion1(name, attributes)
565
+ else:
566
+ self.handleVersion2(name, attributes)
567
+
568
+ def handleVersion1(self, name, attributes):
569
+ if name != 'error':
570
+ return
571
+
572
+ self.errors.append({
573
+ 'file': attributes.get('file', ''),
574
+ 'line': int(attributes.get('line', 0)),
575
+ 'locations': [{
576
+ 'file': attributes.get('file', ''),
577
+ 'line': int(attributes.get('line', 0)),
578
+ }],
579
+ 'id': attributes['id'],
580
+ 'severity': attributes['severity'],
581
+ 'msg': attributes['msg']
582
+ })
583
+
584
+ def handleVersion2(self, name, attributes):
585
+ if name == 'cppcheck':
586
+ self.versionCppcheck = attributes['version']
587
+ if name == 'error':
588
+ error = {
589
+ 'locations': [],
590
+ 'file': '',
591
+ 'line': 0,
592
+ 'id': attributes['id'],
593
+ 'severity': attributes['severity'],
594
+ 'msg': attributes['msg'],
595
+ 'verbose': attributes.get('verbose')
596
+ }
597
+
598
+ if 'inconclusive' in attributes:
599
+ error['inconclusive'] = attributes['inconclusive']
600
+ if 'cwe' in attributes:
601
+ error['cwe'] = attributes['cwe']
602
+
603
+ self.errors.append(error)
604
+ elif name == 'location':
605
+ assert self.errors
606
+ error = self.errors[-1]
607
+ locations = error['locations']
608
+ file = attributes['file']
609
+ line = int(attributes['line'])
610
+ if not locations:
611
+ error['file'] = file
612
+ error['line'] = line
613
+ locations.append({
614
+ 'file': file,
615
+ 'line': line,
616
+ 'info': attributes.get('info')
617
+ })
618
+
619
+ if __name__ == '__main__':
620
+ # Configure all the options this little utility is using.
621
+ parser = optparse.OptionParser()
622
+ parser.add_option('--title', dest='title',
623
+ help='The title of the project.',
624
+ default='[project name]')
625
+ parser.add_option('--file', dest='file', action="append",
626
+ help='The cppcheck xml output file to read defects '
627
+ 'from. You can combine results from several '
628
+ 'xml reports i.e. "--file file1.xml --file file2.xml ..". '
629
+ 'Default is reading from stdin.')
630
+ parser.add_option('--report-dir', dest='report_dir',
631
+ help='The directory where the HTML report content is '
632
+ 'written.')
633
+ parser.add_option('--source-dir', dest='source_dir',
634
+ help='Base directory where source code files can be '
635
+ 'found.')
636
+ parser.add_option('--add-author-information', dest='add_author_information',
637
+ help='Blame information to include. '
638
+ 'Adds specified author information. '
639
+ 'Specify as comma-separated list of either "name", "email", "date" or "n","e","d". '
640
+ 'Default: "n,e,d"')
641
+ parser.add_option('--source-encoding', dest='source_encoding',
642
+ help='Encoding of source code.', default='utf-8')
643
+ parser.add_option('--blame-options', dest='blame_options',
644
+ help='[-w, -M] blame options which you can use to get author and author mail '
645
+ '-w --> not including white spaces and returns original author of the line '
646
+ '-M --> not including moving of lines and returns original author of the line')
647
+
648
+ # Parse options and make sure that we have an output directory set.
649
+ options, args = parser.parse_args()
650
+
651
+ try:
652
+ sys.argv[1]
653
+ except IndexError: # no arguments give, print --help
654
+ parser.print_help()
655
+ quit()
656
+
657
+ if not options.report_dir:
658
+ parser.error('No report directory set.')
659
+
660
+ # Get the directory where source code files are located.
661
+ cwd = os.getcwd()
662
+ source_dir = os.getcwd()
663
+ if options.source_dir:
664
+ source_dir = options.source_dir
665
+
666
+ add_author_information = []
667
+ if options.add_author_information:
668
+ fields = [x.strip() for x in options.add_author_information.split(',')]
669
+ for x in fields:
670
+ if x.lower() in ['n', 'name']:
671
+ add_author_information.append('name')
672
+ elif x.lower() in ['e', 'email']:
673
+ add_author_information.append('email')
674
+ elif x.lower() in ['d', 'date']:
675
+ add_author_information.append('date')
676
+ else:
677
+ print('Unrecognized value "%s" for author information, using default (name, email, date)' % x)
678
+ add_author_information = ['name', 'email', 'date']
679
+ break
680
+
681
+ blame_options = ''
682
+ if options.blame_options:
683
+ blame_options = options.blame_options
684
+ add_author_information = add_author_information or ['name', 'email', 'date']
685
+
686
+ # Parse the xml from all files defined in file argument
687
+ # or from stdin. If no input is provided, stdin is used
688
+ # Produce a simple list of errors.
689
+ print('Parsing xml report.')
690
+ try:
691
+ contentHandler = CppCheckHandler()
692
+ for fname in options.file or [sys.stdin]:
693
+ xml_parse(fname, contentHandler)
694
+ except (XmlParseException, ValueError) as msg:
695
+ print('Failed to parse cppcheck xml file: %s' % msg)
696
+ sys.exit(1)
697
+
698
+ # We have a list of errors. But now we want to group them on
699
+ # each source code file. Lets create a files dictionary that
700
+ # will contain a list of all the errors in that file. For each
701
+ # file we will also generate a HTML filename to use.
702
+ files = {}
703
+ file_no = 0
704
+ for error in contentHandler.errors:
705
+ filename = error['file']
706
+ if filename not in files:
707
+ files[filename] = {
708
+ 'errors': [], 'htmlfile': str(file_no) + '.html'}
709
+ file_no = file_no + 1
710
+ files[filename]['errors'].append(error)
711
+
712
+ # Make sure that the report directory is created if it doesn't exist.
713
+ print('Creating %s directory' % options.report_dir)
714
+ if not os.path.exists(options.report_dir):
715
+ os.makedirs(options.report_dir)
716
+
717
+ # Generate a HTML file with syntax highlighted source code for each
718
+ # file that contains one or more errors.
719
+ print('Processing errors')
720
+
721
+ decode_errors = []
722
+ for filename, data in sorted(files.items()):
723
+ htmlfile = data['htmlfile']
724
+ errors = []
725
+
726
+ for error in data['errors']:
727
+ for location in error['locations']:
728
+ if filename == location['file']:
729
+ newError = dict(error)
730
+
731
+ del newError['locations']
732
+ newError['line'] = location['line']
733
+ if location.get('info'):
734
+ newError['msg'] = location['info']
735
+ newError['severity'] = 'information'
736
+ del newError['verbose']
737
+
738
+ errors.append(newError)
739
+
740
+ lines = []
741
+ for error in errors:
742
+ lines.append(error['line'])
743
+
744
+ if filename == '':
745
+ continue
746
+
747
+ source_filename = os.path.join(source_dir, filename)
748
+ try:
749
+ with io.open(source_filename, 'r', encoding=options.source_encoding) as input_file:
750
+ content = input_file.read()
751
+ except IOError:
752
+ if error['id'] == 'unmatchedSuppression':
753
+ continue # file not found, bail out
754
+ else:
755
+ sys.stderr.write("ERROR: Source file '%s' not found.\n" %
756
+ source_filename)
757
+ continue
758
+ except UnicodeDecodeError:
759
+ sys.stderr.write("WARNING: Unicode decode error in '%s'.\n" %
760
+ source_filename)
761
+ decode_errors.append(source_filename[2:]) # "[2:]" gets rid of "./" at beginning
762
+ continue
763
+
764
+ htmlFormatter = AnnotateCodeFormatter(linenos=True,
765
+ style='colorful',
766
+ hl_lines=lines,
767
+ lineanchors='line',
768
+ encoding=options.source_encoding)
769
+ htmlFormatter.errors = errors
770
+
771
+ with io.open(os.path.join(options.report_dir, htmlfile), 'w', encoding='utf-8') as output_file:
772
+ output_file.write(HTML_HEAD %
773
+ (options.title,
774
+ htmlFormatter.get_style_defs('.highlight'),
775
+ options.title,
776
+ ': ' + filename))
777
+ output_file.write(HTML_HEAD_END)
778
+
779
+ output_file.write(HTML_MENU % (filename.split('/')[-1]))
780
+ for error in sorted(errors, key=lambda k: k['line']):
781
+ output_file.write("<a href=\"%s#line-%d\"> %s %s</a>" % (data['htmlfile'], error['line'], error['id'], error['line']))
782
+ output_file.write(HTML_MENU_END)
783
+
784
+ try:
785
+ lexer = guess_lexer_for_filename(source_filename, '', stripnl=False)
786
+ except ClassNotFound:
787
+ try:
788
+ lexer = guess_lexer(content, stripnl=False)
789
+ except ClassNotFound:
790
+ sys.stderr.write("ERROR: Couldn't determine lexer for the file' " + source_filename + " '. Won't be able to syntax highlight this file.")
791
+ output_file.write("\n <tr><td colspan=\"5\"> Could not generate content because pygments failed to determine the code type.</td></tr>")
792
+ output_file.write("\n <tr><td colspan=\"5\"> Sorry about this.</td></tr>")
793
+ continue
794
+
795
+ if options.source_encoding:
796
+ lexer.encoding = options.source_encoding
797
+
798
+ output_file.write(
799
+ highlight(content, lexer, htmlFormatter).decode(
800
+ options.source_encoding))
801
+
802
+ output_file.write(HTML_FOOTER % contentHandler.versionCppcheck)
803
+
804
+ print(' ' + filename)
805
+
806
+ # Generate a master index.html file that will contain a list of
807
+ # all the errors created.
808
+ print('Creating index.html')
809
+
810
+ with io.open(os.path.join(options.report_dir, 'index.html'),
811
+ 'w') as output_file:
812
+
813
+ stats_count = 0
814
+ stats = []
815
+ filter_enabled = {}
816
+ for filename, data in sorted(files.items()):
817
+ for error in data['errors']:
818
+ stats.append(error['id']) # get the stats
819
+ filter_enabled[error['severity']] = True
820
+ filter_enabled['clang-tidy' if error['id'].startswith('clang-tidy-') else 'cppcheck'] = True
821
+ stats_count += 1
822
+
823
+ counter = Counter(stats)
824
+
825
+ stat_html = []
826
+ # the following lines sort the stat primary by value (occurrences),
827
+ # but if two IDs occur equally often, then we sort them alphabetically by warning ID
828
+ try:
829
+ cnt_max = counter.most_common()[0][1]
830
+ except IndexError:
831
+ cnt_max = 0
832
+
833
+ try:
834
+ cnt_min = counter.most_common()[-1][1]
835
+ except IndexError:
836
+ cnt_min = 0
837
+
838
+ stat_fmt = "\n <tr><td><input type=\"checkbox\" class=\"idToggle\" onclick=\"toggleDisplay(this)\" id=\"{}\" name=\"{}\" checked></td><td>{}</td><td>{}</td></tr>"
839
+ for occurrences in reversed(range(cnt_min, cnt_max + 1)):
840
+ for _id in [k for k, v in sorted(counter.items()) if v == occurrences]:
841
+ stat_html.append(stat_fmt.format(
842
+ to_css_selector(_id),
843
+ to_css_selector(_id),
844
+ dict(counter.most_common())[_id],
845
+ _id
846
+ ))
847
+
848
+ output_file.write(HTML_HEAD % (options.title, '', options.title, ''))
849
+ output_file.write(filter_bar(filter_enabled))
850
+ output_file.write(HTML_HEAD_END)
851
+ output_file.write(HTML_MENU.replace('id="menu"', 'id="menu_index"', 1).replace("Defects:", "Defect summary", 1) % (''))
852
+ output_file.write('\n <label><input type="checkbox" class=\"idToggle\" onclick="toggleAll()" checked> Toggle all</label>')
853
+ output_file.write('\n <table>')
854
+ output_file.write('\n <tr><th>Show</th><th>#</th><th>Defect ID</th></tr>')
855
+ output_file.write(''.join(stat_html))
856
+ output_file.write('\n <tr><td></td><td>' + str(stats_count) + '</td><td>total</td></tr>')
857
+ output_file.write('\n </table>')
858
+ output_file.write('\n <p><a href="stats.html">Statistics</a></p>')
859
+ output_file.write(HTML_MENU_END.replace("content", "content_index", 1))
860
+
861
+ output_file.write('\n <table class=\"summaryTable\">')
862
+ output_file.write(
863
+ '\n %s' %
864
+ tr_str('th', 'Line', 'Id', 'CWE', 'Severity', 'Message', 'Author', 'Author mail', 'Date (DD/MM/YYYY)', add_author=add_author_information))
865
+
866
+ for filename, data in sorted(files.items()):
867
+ file_error = filename in decode_errors or filename.endswith('*')
868
+ is_file = filename != '' and not file_error
869
+ row_content = filename if file_error else "<a href=\"%s\">%s</a>" % (data['htmlfile'], filename)
870
+ htmlfile = data.get('htmlfile') if is_file else None
871
+
872
+ output_file.write("\n <tbody class=\"fileEntry\">")
873
+ output_file.write("\n <tr><td colspan=\"5\">%s</td></tr>" % row_content)
874
+
875
+ if filename in decode_errors:
876
+ output_file.write("\n <tr><td colspan=\"5\">Could not generated due to UnicodeDecodeError</td></tr>")
877
+
878
+ sorted_errors = sorted(data['errors'], key=lambda k: k['line'])
879
+ blame_data = git_blame(sorted_errors, source_dir, filename, blame_options) if add_author_information else []
880
+ for error in sorted_errors:
881
+ git_blame_dict = blame_lookup(blame_data, error['line'])
882
+ message_class = None
883
+ try:
884
+ if error['inconclusive'] == 'true':
885
+ message_class = 'inconclusive'
886
+ error['severity'] += ", inconcl."
887
+ except KeyError:
888
+ pass
889
+
890
+ try:
891
+ if error['cwe']:
892
+ cwe_url = "<a href=\"https://cwe.mitre.org/data/definitions/" + error['cwe'] + ".html\">" + error['cwe'] + "</a>"
893
+ except KeyError:
894
+ cwe_url = ""
895
+
896
+ if error['severity'] in ['error', 'warning']:
897
+ message_class = error['severity']
898
+
899
+ line = error["line"] if is_file else ""
900
+
901
+ output_file.write(
902
+ '\n %s' %
903
+ tr_str('td', line, error["id"], cwe_url, error["severity"], error["msg"],
904
+ git_blame_dict.get('author', 'Unknown'), git_blame_dict.get('author-mail', '---'),
905
+ git_blame_dict.get('author-time', '---'),
906
+ tr_class=to_css_selector(error["id"]) + ' sev_' + error["severity"] + ' issue',
907
+ message_class=message_class,
908
+ add_author=add_author_information,
909
+ htmlfile=htmlfile))
910
+ output_file.write("\n </tbody>")
911
+ output_file.write('\n </table>')
912
+ output_file.write(HTML_FOOTER % contentHandler.versionCppcheck)
913
+
914
+ if decode_errors:
915
+ sys.stderr.write("\nGenerating html failed for the following files: " + ' '.join(decode_errors))
916
+ sys.stderr.write("\nConsider changing source-encoding (for example: \"htmlreport ... --source-encoding=\"iso8859-1\"\"\n")
917
+
918
+ print('Creating style.css file')
919
+ os.chdir(cwd) # going back to the cwd to find style.css
920
+ with io.open(os.path.join(options.report_dir, 'style.css'), 'w') as css_file:
921
+ css_file.write(STYLE_FILE)
922
+
923
+ print("Creating stats.html (statistics)\n")
924
+ stats_countlist = {}
925
+
926
+ for filename, data in sorted(files.items()):
927
+ if filename == '':
928
+ continue
929
+ stats_tmplist = []
930
+ for error in sorted(data['errors'], key=lambda k: k['line']):
931
+ stats_tmplist.append(error['severity'])
932
+
933
+ stats_countlist[filename] = dict(Counter(stats_tmplist))
934
+
935
+ # get top ten for each severity
936
+ SEVERITIES = "error", "warning", "portability", "performance", "style", "unusedFunction", "information", "missingInclude", "internal"
937
+
938
+ with io.open(os.path.join(options.report_dir, 'stats.html'), 'w') as stats_file:
939
+
940
+ stats_file.write(HTML_HEAD % (options.title, '', options.title, ': Statistics'))
941
+ stats_file.write(HTML_HEAD_END)
942
+
943
+ stats_file.write(HTML_MENU.replace('id="menu"', 'id="menu_index"', 1).replace("Defects:", "Back to summary", 1) % (''))
944
+ stats_file.write(HTML_MENU_END.replace("content", "content_index", 1))
945
+
946
+
947
+ for sev in SEVERITIES:
948
+ _sum = 0
949
+ stats_templist = {}
950
+
951
+ # if the we have an style warning but we are checking for
952
+ # portability, we have to skip it to prevent KeyError
953
+ try:
954
+ for filename in stats_countlist:
955
+ try: # also bail out if we have a file with no sev-results
956
+ _sum += stats_countlist[filename][sev]
957
+ stats_templist[filename] = int(stats_countlist[filename][sev]) # file : amount,
958
+ except KeyError:
959
+ continue
960
+ # don't print "0 style" etc, if no style warnings were found
961
+ if _sum == 0:
962
+ continue
963
+ except KeyError:
964
+ continue
965
+ stats_file.write("<p><span class=\"statHeader\">Top 10 files for " + sev + " severity, total findings: " + str(_sum) + "</span><br>\n")
966
+
967
+ # sort, so that the file with the most severities per type is first
968
+ stats_list_sorted = sorted(stats_templist.items(), key=operator.itemgetter(1, 0), reverse=True)
969
+ it = 0
970
+ LENGTH = 0
971
+
972
+ for i in stats_list_sorted: # printing loop
973
+ # for aesthetics: if it's the first iteration of the loop, get
974
+ # the max length of the number string
975
+ if it == 0:
976
+ LENGTH = len(str(i[1])) # <- length of longest number, now get the difference and try to make other numbers align to it
977
+
978
+ stats_file.write("&#160;" * 3 + str(i[1]) + "&#160;" * (1 + LENGTH - len(str(i[1]))) + "<a href=\"" + files[i[0]]['htmlfile'] + "\"> " + i[0] + "</a><br>\n")
979
+ it += 1
980
+ if it == 10: # print only the top 10
981
+ break
982
+ stats_file.write("</p>\n")
983
+
984
+ stats_file.write(HTML_FOOTER % contentHandler.versionCppcheck)
985
+
986
+ print("\nOpen '" + options.report_dir + "/index.html' to see the results.")