diff --git a/.codacy.yml b/.codacy.yml
index dcfec8e5c10..8fabf99bc72 100644
--- a/.codacy.yml
+++ b/.codacy.yml
@@ -1,7 +1,7 @@
exclude_paths:
- addons/test/**
- addons/y2038/test/*.c
- - htmlreport/example.cc
+ - reports/htmlreport/example.cc
- samples/**/bad.c
- samples/**/bad.cpp
- test/cfg/*.c
diff --git a/.github/workflows/release-windows.yml b/.github/workflows/release-windows.yml
index 63c570f0ea7..d58f5f92b1a 100644
--- a/.github/workflows/release-windows.yml
+++ b/.github/workflows/release-windows.yml
@@ -127,7 +127,7 @@ jobs:
# TODO: include in installer?
- name: Compile cppcheck-htmlreport executable
run: |
- cd htmlreport || exit /b !errorlevel!
+ cd reports\htmlreport || exit /b !errorlevel!
pyinstaller cppcheck-htmlreport || exit /b !errorlevel!
del *.spec || exit /b !errorlevel!
@@ -153,7 +153,7 @@ jobs:
del win_installer\files\platforms\*.rng || exit /b !errorlevel!
del win_installer\files\translations\*.qm || exit /b !errorlevel!
move build\gui\*.qm win_installer\files\translations || exit /b !errorlevel!
- copy htmlreport\dist\cppcheck-htmlreport\*.* win_installer\files || exit /b !errorlevel!
+ copy reports\htmlreport\dist\cppcheck-htmlreport\*.* win_installer\files || exit /b !errorlevel!
:: copy libcrypto-3-x64.dll and libssl-3-x64.dll
copy %RUNNER_WORKSPACE%\Qt\Tools\OpenSSLv3\Win_x64\bin\lib*.dll win_installer\files || exit /b !errorlevel!
diff --git a/.github/workflows/scriptcheck.yml b/.github/workflows/scriptcheck.yml
index cde4ec3407d..b3448fb85ee 100644
--- a/.github/workflows/scriptcheck.yml
+++ b/.github/workflows/scriptcheck.yml
@@ -109,7 +109,7 @@ jobs:
if: matrix.python-latest
run: |
shopt -s globstar
- pylint --jobs $(nproc) --py-version 3.7 addons/**/*.py htmlreport/cppcheck-htmlreport htmlreport/**/*.py test/**/*.py tools/**/*.py
+ pylint --jobs $(nproc) --py-version 3.7 addons/**/*.py reports/htmlreport/cppcheck-htmlreport reports/**/*.py test/**/*.py tools/**/*.py
- name: check .json files
if: matrix.python-latest
@@ -125,8 +125,8 @@ jobs:
run: |
shopt -s globstar
python -m py_compile addons/**/*.py
- python -m py_compile htmlreport/cppcheck-htmlreport
- python -m py_compile htmlreport/**/*.py
+ python -m py_compile reports/htmlreport/cppcheck-htmlreport
+ python -m py_compile reports/**/*.py
python -m py_compile test/**/*.py
python -m py_compile tools/**/*.py
@@ -167,7 +167,7 @@ jobs:
python -m venv venv
source venv/bin/activate
python -m pip install -U pip
- pip install ./htmlreport/
+ pip install ./reports/htmlreport/
which cppcheck-htmlreport
PIP_PACKAGE_TEST=1 test/tools/htmlreport/test_htmlreport.py
# TODO: does not test the pip binary
@@ -199,6 +199,12 @@ jobs:
env:
PYTHONPATH: ./tools
+ # the javascript tests use the node that is installed on the runner
+ - name: test explorer report
+ run: |
+ node --version
+ python -m pytest -Werror --strict-markers -vv test/tools/explorer/
+
- name: Show all ignored files
if: false # TODO: currently lists all the contents of ignored folders - we only need what actually matched
run: |
diff --git a/.gitignore b/.gitignore
index e99599a4186..36f3ff81106 100644
--- a/.gitignore
+++ b/.gitignore
@@ -113,7 +113,7 @@ stage
**/*.egg-info/
# cppcheck-htmlreport auto files
-/htmlreport/cppcheck_htmlreport/run.py
+/reports/htmlreport/cppcheck_htmlreport/run.py
# GDB configuration
.gdbinit
@@ -121,8 +121,8 @@ stage
# pyinstaller output
/addons/dist
/addons/misra.spec
-/htmlreport/cppcheck-htmlreport.spec
-/htmlreport/dist
+/reports/htmlreport/cppcheck-htmlreport.spec
+/reports/htmlreport/dist
# ccache folder in CI
/.ccache
diff --git a/Makefile b/Makefile
index 53c8b4c7aea..b931fa3209f 100644
--- a/Makefile
+++ b/Makefile
@@ -414,7 +414,7 @@ tags:
install: cppcheck
install -d ${BIN}
install cppcheck ${BIN}
- install htmlreport/cppcheck-htmlreport ${BIN}
+ install reports/htmlreport/cppcheck-htmlreport ${BIN}
ifdef FILESDIR
install -d ${DESTDIR}${FILESDIR}
install -d ${DESTDIR}${FILESDIR}/addons
diff --git a/cli/CMakeLists.txt b/cli/CMakeLists.txt
index 52103bdb8ec..ae46117d149 100644
--- a/cli/CMakeLists.txt
+++ b/cli/CMakeLists.txt
@@ -43,7 +43,7 @@ if (BUILD_CLI)
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT applications)
- install(PROGRAMS ${CMAKE_SOURCE_DIR}/htmlreport/cppcheck-htmlreport
+ install(PROGRAMS ${CMAKE_SOURCE_DIR}/reports/htmlreport/cppcheck-htmlreport
DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT applications)
diff --git a/man/manual-ja.docbook b/man/manual-ja.docbook
index 0b2a39cc59e..772ad6005d7 100644
--- a/man/manual-ja.docbook
+++ b/man/manual-ja.docbook
@@ -1814,11 +1814,11 @@ for arg in sys.argv[1:]:
HTML 形式での報告
- cppcheckのXML出力をHTML形式に変更できます。これを利用するには、Python と pygments module (http://pygments.org/) が必要です。Cppcheckのソースツリーにhtmlreportというフォルダがあります。このフォルダには、CppcheckのXMLファイルをHTML出力に変換するスクリプトがあります。
+ cppcheckのXML出力をHTML形式に変更できます。これを利用するには、Python と pygments module (http://pygments.org/) が必要です。Cppcheckのソースツリーにreports/htmlreportというフォルダがあります。このフォルダには、CppcheckのXMLファイルをHTML出力に変換するスクリプトがあります。このコマンドでヘルプ画面を生成するには次のように実行します。
- htmlreport/cppcheck-htmlreport -h
+ reports/htmlreport/cppcheck-htmlreport -h出力画面には次の内容が表示されます。:
@@ -1836,7 +1836,7 @@ Options:
使用例:./cppcheck gui/test.cpp --xml 2> err.xml
-htmlreport/cppcheck-htmlreport --file=err.xml --report-dir=test1 --source-dir=.
+reports/htmlreport/cppcheck-htmlreport --file=err.xml --report-dir=test1 --source-dir=.
diff --git a/man/manual.md b/man/manual.md
index cf5d83487bb..0d2af0b7050 100644
--- a/man/manual.md
+++ b/man/manual.md
@@ -1341,11 +1341,22 @@ The `.cfg` file format is documented in the `Reference: Cppcheck .cfg format` (<
# HTML report
-You can convert the XML output from Cppcheck into a HTML report. You'll need Python and the pygments module () for this to work. In the Cppcheck source tree there is a folder htmlreport that contains a script that transforms a Cppcheck XML file into HTML output.
+## Overview
+
+Using AI, you can easily and quickly create a script that converts the Cppcheck XML output into a nice-looking HTML report with any features you want.
+
+We provide 2 ready made scripts:
+
+ * htmlreport: results view
+ * explorer: dashboard, results view, metrics (if available)
+
+## htmlreport
+
+The script `cppcheck-htmlreport` converts a Cppcheck XML file into a HTML output. You'll need Python and the pygments module () for this to work.
This command generates the help screen:
- htmlreport/cppcheck-htmlreport -h
+ reports/htmlreport/cppcheck-htmlreport -h
The output screen says:
@@ -1374,7 +1385,7 @@ or
cppcheck-htmlreport --file=err.xml --report-dir=test1 \
--source-dir=https://github.com///blob//
-## Choosing between local annotated HTML and remote repository links
+### Choosing between local annotated HTML and remote repository links
`cppcheck-htmlreport` supports two modes for linking to source files:
@@ -1394,6 +1405,81 @@ handled by the hosting service.
In general, local mode fits air-gapped environments, while remote mode works
best for CI workflows and large or private repositories.
+## Explorer report
+
+The script `reports/explorer/report.py` creates a Cppcheck Explorer report. The report has a dashboard with graphs, and a results view where you can filter the warnings and see the related source code. If the XML file contains metrics, these are shown as well. The report is designed to be responsive also when there are thousands of warnings.
+
+You only need Python to run the script, no extra modules are required.
+
+### Generating a report
+
+First analyze the code and save the results in an XML file, then generate the report:
+
+ cppcheck --enable=style --xml src 2> results.xml
+ python3 reports/explorer/report.py results.xml -o cppcheck-report
+
+Open `cppcheck-report/index.html` in a browser. To share the report, copy the whole `cppcheck-report` folder. Note that the report contains the source code.
+
+The source files are searched for in the current folder and in the folder of the XML file. Use `--source-dir` if they are located somewhere else:
+
+ python3 reports/explorer/report.py results.xml --source-dir=path/to/project -o cppcheck-report
+
+### New and old warnings
+
+If you provide the XML results from an earlier analysis as a baseline, then the report shows which warnings are new:
+
+ # Analyze the code and save the results as a baseline
+ cppcheck --enable=style --xml src 2> baseline.xml
+
+ # Later: analyze the code again and compare with the baseline
+ cppcheck --enable=style --xml src 2> results.xml
+ python3 reports/explorer/report.py results.xml --baseline=baseline.xml -o cppcheck-report
+
+### Trend graphs
+
+Save the XML results from each analysis in a folder and use `--history` to get trend graphs. The results are ordered by the date in the filename:
+
+ mkdir -p history
+ cppcheck --enable=style --xml src 2> history/results-2026-05-01.xml
+
+ # Later: analyze the code again and show the trend
+ cppcheck --enable=style --xml src 2> results.xml
+ python3 reports/explorer/report.py results.xml --history=history -o cppcheck-report
+
+If no `--baseline` is given, then the newest report in the history is used as baseline.
+
+::: {.content-visible when-profile="premium"}
+
+### Metrics
+
+To generate metrics, add option `--premium=metrics`. The metrics are saved in the XML v3 report.
+Example:
+
+ cppcheck --premium=metrics test.c --xml-version=3 2> res.xml
+ python3 reports/explorer/report.py res.xml -o cppcheck-report
+
+The dashboard shows a summary of the metrics and the metrics view shows the values for each
+function and file. Values that exceed the thresholds are highlighted.
+
+The default thresholds are the HIS limits. You can change them by providing a JSON file. Example `thresholds.json`:
+
+ {
+ "cyclomaticComplexity": {"max": 15},
+ "HISCOMF": {"min": 10}
+ }
+
+Use the option `--metrics-thresholds` to load the file:
+
+ python3 reports/explorer/report.py res.xml --metrics-thresholds=thresholds.json -o cppcheck-report
+
+:::
+
+### All options
+
+To see all options, run:
+
+ python3 reports/explorer/report.py -h
+
# Check level
## Reduced
@@ -1550,16 +1636,15 @@ Example:
cppcheck --premium=metrics test.c --xml-version=3 2> res.xml
-We provide a small simple python script that creates a metrics report in CSV format:
+A report that shows the metrics can be created, for example see the chapter [Explorer report](#explorer-report).
+
+If you want the metrics in CSV format, we provide a small simple python script for that:
python3 HISReport.py -f res.xml -j path/to/cppcheck-id-mapping.json -o test.csv
The `cppcheck-id-mapping.json` is provided in the Cppcheck premium installation folder, i.e.
`/opt/cppcheckpremium` or `C:\Program Files\Cppcheck Premium`.
-We do not have a ready-made solution to generate a HTML/pdf report. You can easily tweak our
-`HISReport.py` script so that it generates HTML and get the report exactly as you want.
-
## Licenses
### Commercial terms
diff --git a/reports/explorer/README.md b/reports/explorer/README.md
new file mode 100644
index 00000000000..d16a1f1e06d
--- /dev/null
+++ b/reports/explorer/README.md
@@ -0,0 +1,127 @@
+
+# Report
+
+## Overview
+
+This folder contains a script report.py that converts a cppcheck xml report into a html report.
+
+Only the python standard libraries are used. No extra dependencies shall be needed.
+
+The html report is interactive, there are toggle buttons and stuff.
+
+## Performance
+
+Very important. The report needs to be responsive for large projects with thousands of warnings. It's preferable that multiple files are created instead of a single HTML that contains everything.
+
+## Themes
+
+There will be different themes. light/dark/etc
+
+## Dashboard
+
+A dashboard shows an overview of warnings. The dashboard is designed for a team-leader that wants to see status. The dashboard should primarily present information in graphs.
+
+### Sections
+
+- Executive summary: A text summary. Green/Red Badge if there are undefined behavior. A Green/red badge if there are security/safety issues (misra/cert). The badge is gray if misra/cert was not checked.
+- Product filter strip: Buttons per "product". Products are guessed from the directory (src/core/ becomes "Core"), or set with --product-map. Clicking one filters the whole dashboard. Hide this if all source files are in the same folder.
+- If several reports are provided we can show trend graphs.
+- Show graphs both for "new" warnings and "all" warnings.
+- 5 KPI tiles: Errors, warnings, style+perf+portability, total and affected files, with "+N vs previous".
+- Quality trend over time: Line chart of total/errors/warnings across snapshots (--history DIR or --snapshot). With "new" warnings selected it shows the new warnings in each report, compared with the report before. Hide this if there is only 1 result file.
+- Warnings by product: Bar chart. Hide this if there is only one product, or if a product is selected.
+- Risk domain breakdown: Bar chart of IDs grouped into made-up groups ("Memory & Crash Safety", "Security", "Maintainability"…) by keyword matching or by CWE.
+- If there are metrics then show some summary about that.
+
+## Result details
+
+There is a result details view. All results are shown here. It's possible to toggle different warnings severities. It's possible to toggle IDs.
+
+All warnings are shown in a list and if a warning is clicked the related code is shown in a tab.
+
+## Metrics
+
+If there are metrics, a metrics report.
+
+# Baseline : New and old warnings
+
+Each warning has a hash in the xml report, if old baseline report(s) are provided then those warnings are "old". A warning in a new report is "new" if its hash does not match any baseline warning.
+
+It should be indicated in the dashboard how many new/old warnings there are. It should be possible to see if warnings are new in the results view and it should be possible to hide old warnings.
+
+## Classification/guideline mode (MISRA, CERT, Cppcheck Premium)
+
+When the XML has classification attributes, the report switches to a different mode:
+
+- In the results list the severity is replaced by Classification and Guideline columns. Click on a column header to sort.
+- A filter bar for Mandatory, Required, Advisory, Document, Disapplied and L1/L2/L3 replaces the severity filter. Classifications that are not used in the report are disabled.
+- The dashboard graphs and KPI tiles use the classification instead of the severity, and there is a graph of the most violated guidelines.
+- The severity is still shown in the warning details.
+
+
+# Usage
+
+ cppcheck --xml ... 2> results.xml
+ python3 report.py results.xml -o cppcheck-report
+
+ # mark new/old warnings by comparing with a previous report
+ python3 report.py results.xml --baseline old-results.xml -o cppcheck-report
+
+ # trend graphs: older reports in a directory (results-2026-05-01.xml, ...)
+ python3 report.py results.xml --history history -o cppcheck-report
+
+ # metrics (Cppcheck Premium)
+ cppcheck --premium=metrics --xml-version=3 ... 2> results.xml
+ python3 report.py results.xml -o cppcheck-report
+
+Then open `cppcheck-report/index.html` in a browser.
+
+Options:
+
+ * `-o DIR`, `--output-dir DIR` directory where the report is written (default: cppcheck-report)
+ * `--xml FILE` xml report (xml files can also be given as positional arguments)
+ * `--baseline FILE` baseline xml report, warnings that are not in the baseline are new (can be given several times). `--old` is an alias. If it is not given, the newest `--history`/`--snapshot` report is used.
+ * `--history DIR` directory with older xml reports for the trend graphs. They are ordered by the date in the file name (`results-2026-05-01.xml`), or by file time.
+ * `--snapshot FILE` older xml report for the trend graphs (can be given several times, oldest first)
+ * `--product-map FILE` json file that maps path prefixes to product names: `{"src/core": "Core", "lib/net": "Network"}`. Without it, products are guessed from the first directory below the common source directory (`src/core/x.cpp` becomes "Core").
+ * `--metrics-thresholds FILE` json file with metric thresholds, overrides the defaults: `{"cyclomaticComplexity": {"max": 15}, "HISCOMF": {"min": 10}}`
+ * `--source-dir DIR` where the source files are located (can be given several times). By default the current directory and the directories of the xml files are searched.
+ * `--source-encoding ENCODING` encoding of the source files (default: utf-8)
+ * `--title TITLE` report title
+ * `--theme THEME` default theme: light, apple, microsoft, dark, midnight, solarized (the viewer can switch theme in the report)
+
+## Report directory
+
+ index.html open this in a browser
+ report.css
+ report.js
+ data/results.js all warnings, trend data
+ data/metrics.js metrics (if the xml has metrics), loaded when needed
+ data/src/.js source code, one file per source file, loaded when it is shown
+
+The report works directly from the file system (no web server needed). Copy the whole directory to share it.
+
+## Combining several XML files
+
+Multiple xml files can be provided: `--xml file1.xml --xml file2.xml`. Duplicate warnings (same hash and location) are only shown once.
+
+## Metric thresholds
+
+The default thresholds are the HIS limits (same as Cppcheck Premium `HISReport.py`):
+
+| Metric | Id | Threshold |
+|---|---|---|
+| Cyclomatic complexity v(G) | cyclomaticComplexity | max 10 |
+| Statements STMT | HISStmt | max 50 |
+| Execution paths PATH | HISPath | max 80 |
+| Nesting depth LEVEL | HISLevel | max 4 |
+| Called functions CALLS | HISCall | max 7 |
+| Calling functions CALLING | HISCalling | max 5 |
+| Parameters PARAM | HISParam | max 5 |
+| Return points RETURN | HISReturn | max 1 |
+| Goto statements GOTO | HISGoto | max 0 |
+| Language scope VOCF | HISVOCF | max 4 (computed from HISVocf_N / HISVocf_D) |
+| Comment density COMF % | HISCOMF | min 20 (computed from HISComment / HISStmtFile) |
+
+They can be changed with `--metrics-thresholds`.
+
diff --git a/reports/explorer/report.py b/reports/explorer/report.py
new file mode 100755
index 00000000000..e5d576e7c41
--- /dev/null
+++ b/reports/explorer/report.py
@@ -0,0 +1,3021 @@
+#!/usr/bin/env python3
+"""
+Convert Cppcheck XML report(s) into a Cppcheck Explorer report.
+
+Usage:
+ report.py results.xml [more.xml ...] [-o report-dir] [--baseline old-results.xml]
+ [--history DIR] [--snapshot FILE] [--product-map FILE]
+ [--metrics-thresholds FILE] [--source-dir DIR] [--title TITLE] [--theme THEME]
+
+The report is written to a directory:
+ index.html the report, open this in a browser
+ report.css styles
+ report.js application code
+ data/results.js all warnings, trend data
+ data/metrics.js metrics (only if the xml contains metrics), loaded on demand
+ data/src/.js source code of each file, loaded on demand
+
+Only the Python standard library is used.
+"""
+
+import argparse
+import datetime
+import glob
+import html
+import json
+import os
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+THEMES = ['light', 'apple', 'microsoft', 'dark', 'midnight', 'solarized']
+
+MAX_SOURCE_SIZE = 8 * 1024 * 1024 # do not include source files larger than this
+
+# Default HIS metric thresholds (same as Cppcheck Premium HISReport.py).
+# Can be overridden with --metrics-thresholds and edited in the report.
+DEFAULT_THRESHOLDS = {
+ 'cyclomaticComplexity': {'max': 10},
+ 'HISStmt': {'max': 50},
+ 'HISPath': {'max': 80},
+ 'HISLevel': {'max': 4},
+ 'HISCall': {'max': 7},
+ 'HISCalling': {'max': 5},
+ 'HISParam': {'max': 5},
+ 'HISReturn': {'max': 1},
+ 'HISGoto': {'max': 0},
+ 'HISVOCF': {'max': 4},
+ 'HISCOMF': {'min': 20},
+}
+
+# column order of function and file metrics, unknown metric ids are appended
+FUNCTION_METRICS = ['cyclomaticComplexity', 'HISStmt', 'HISPath', 'HISLevel', 'HISCall', 'HISCalling',
+ 'HISParam', 'HISReturn', 'HISGoto', 'HISVOCF']
+FILE_METRICS = ['HISStmtFile', 'HISComment', 'HISCOMF']
+
+
+# ---------------------------------------------------------------------------
+# Reading the xml reports
+# ---------------------------------------------------------------------------
+
+def parse_report(path):
+ """Parse a cppcheck xml report.
+
+ Returns a dict with version, results, function/file metrics, checkers and critical errors."""
+ try:
+ tree = ET.parse(path)
+ except ET.ParseError as e:
+ sys.exit('error: failed to parse %s: %s' % (path, e))
+ except OSError as e:
+ sys.exit('error: failed to read %s: %s' % (path, e.strerror))
+
+ root = tree.getroot()
+ report = {'version': '', 'results': [], 'functions': {}, 'files': {}, 'checkers': set(), 'critical': set()}
+ cppcheck = root.find('cppcheck')
+ if cppcheck is not None:
+ report['version'] = cppcheck.get('version', '')
+
+ errors = root.find('errors')
+ if errors is not None:
+ elements = errors.findall('error')
+ else:
+ # xml version 1:
+ elements = root.findall('error')
+
+ for e in elements:
+ locations = []
+ for loc in e.findall('location'):
+ locations.append({
+ 'file': _file(loc.get('file', '')),
+ 'line': _int(loc.get('line')),
+ 'column': _int(loc.get('column')),
+ 'info': loc.get('info', ''),
+ })
+ if not locations and e.get('file'):
+ locations.append({'file': _file(e.get('file')), 'line': _int(e.get('line')),
+ 'column': 0, 'info': ''})
+ msg = e.get('msg', '')
+ report['results'].append({
+ 'id': e.get('id', ''),
+ 'severity': e.get('severity', 'none'),
+ 'msg': msg,
+ 'verbose': e.get('verbose', msg),
+ 'cwe': _int(e.get('cwe')),
+ 'hash': e.get('hash', ''),
+ 'inconclusive': e.get('inconclusive') == 'true',
+ 'file0': e.get('file0', ''),
+ 'remark': e.get('remark', ''),
+ 'classification': e.get('classification', ''),
+ 'guideline': e.get('guideline', ''),
+ 'locations': locations,
+ 'symbols': [s.text for s in e.findall('symbol') if s.text],
+ })
+
+ # xml version 3: syntaxError,...
+ crit = root.find('critical-errors')
+ if crit is not None and crit.text:
+ report['critical'].update(x.strip() for x in crit.text.split(',') if x.strip())
+ checkers = root.find('checkers-report')
+ if checkers is not None:
+ report['checkers'].update(c.get('id', '') for c in checkers.findall('checker'))
+
+ # metrics generated by Cppcheck Premium --premium=metrics
+ metrics = root.find('metrics')
+ if metrics is not None:
+ for m in metrics.findall('metric'):
+ value = _num(m.get('value'))
+ if value is None or not m.get('id'):
+ continue
+ filename = m.get('fileName', '')
+ if m.get('function') is None:
+ report['files'].setdefault(filename, {})[m.get('id')] = value
+ else:
+ key = (filename, m.get('function'), _int(m.get('lineNumber')))
+ report['functions'].setdefault(key, {})[m.get('id')] = value
+ return report
+
+
+def _file(name):
+ # Cppcheck Premium reports license messages with this pseudo file name
+ return '' if name == 'Cppcheck Premium' else name
+
+
+def _int(value):
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _num(value):
+ try:
+ f = float(value)
+ except (TypeError, ValueError):
+ return None
+ return int(f) if f.is_integer() else f
+
+
+def parse_reports(paths):
+ """Parse and combine several reports. Duplicated warnings are only kept once."""
+ combined = {'version': '', 'results': [], 'functions': {}, 'files': {}, 'checkers': set(), 'critical': set()}
+ seen = set()
+ for path in paths:
+ report = parse_report(path)
+ combined['version'] = combined['version'] or report['version']
+ for r in report['results']:
+ loc = r['locations'][0] if r['locations'] else {'file': '', 'line': 0, 'column': 0}
+ k = (result_key(r), loc['file'], loc['line'], loc['column'])
+ if k in seen:
+ continue
+ seen.add(k)
+ combined['results'].append(r)
+ for key in ('functions', 'files'):
+ for k, v in report[key].items():
+ combined[key].setdefault(k, {}).update(v)
+ combined['checkers'] |= report['checkers']
+ combined['critical'] |= report['critical']
+ return combined
+
+
+# warnings without hash whose message is ignored when matching old and new warnings
+# checkersReport: "Active checkers: 176/189 (use --checkers-report= to see details)"
+VARYING_MESSAGE_IDS = {'checkersReport'}
+
+
+def result_key(r):
+ """Key used to match warnings between the old and the new report."""
+ if r['hash']:
+ return 'h:' + r['hash']
+ # No hash (e.g. missingInclude). Use a key that does not depend on line numbers.
+ files = '|'.join(loc['file'] for loc in r['locations'])
+ # the message of these changes with the cppcheck version and xml version
+ msg = '' if r['id'] in VARYING_MESSAGE_IDS else r['msg']
+ return 'k:%s|%s|%s' % (r['id'], msg, files)
+
+
+def primary_file(r):
+ return r['locations'][0]['file'] if r['locations'] else ''
+
+
+# ---------------------------------------------------------------------------
+# Products, risk domains, snapshots
+# ---------------------------------------------------------------------------
+
+GENERIC_DIRS = {'src', 'source', 'sources', 'lib', 'libs', 'code', 'modules', 'components',
+ 'packages', 'apps', 'services', 'products', 'projects'}
+
+
+def load_product_map(path):
+ """--product-map: json object {"path/prefix": "Name"} or {"path/prefix": {"name": "Name"}}"""
+ try:
+ with open(path, 'rt', encoding='utf-8') as f:
+ data = json.load(f)
+ except (OSError, ValueError) as e:
+ sys.exit('error: failed to read product map %s: %s' % (path, e))
+ if not isinstance(data, dict):
+ sys.exit('error: product map %s must be a json object' % path)
+ out = []
+ for prefix, v in data.items():
+ name = v.get('name') if isinstance(v, dict) else v
+ if name:
+ out.append((prefix.replace('\\', '/').rstrip('/'), str(name)))
+ out.sort(key=lambda x: -len(x[0]))
+ return out
+
+
+def make_product_mapper(files, product_map):
+ """Return a function that maps a file name to a product name.
+
+ Products are taken from the product map, or guessed from the first directory
+ below the common directory of all files (src/core/x.cpp -> "Core")."""
+ dirs = [f.replace('\\', '/').split('/')[:-1] for f in files if f]
+ prefix = dirs[0] if dirs else []
+ for d in dirs[1:]:
+ n = 0
+ while n < len(prefix) and n < len(d) and prefix[n] == d[n]:
+ n += 1
+ prefix = prefix[:n]
+ cache = {}
+
+ def product(f):
+ if not f:
+ return ''
+ if f in cache:
+ return cache[f]
+ n = f.replace('\\', '/')
+ name = None
+ for p, pname in product_map:
+ if n == p or n.startswith(p + '/'):
+ name = pname
+ break
+ if name is None:
+ parts = n.split('/')[:-1]
+ if parts[:len(prefix)] == prefix:
+ parts = parts[len(prefix):]
+ while len(parts) > 1 and parts[0].lower() in GENERIC_DIRS:
+ parts = parts[1:]
+ parts = [p for p in parts if p not in ('', '.', '..')]
+ if not parts:
+ name = 'Root'
+ else:
+ name = re.sub(r'[-_]+', ' ', parts[0]).strip() or parts[0]
+ name = name[0].upper() + name[1:]
+ cache[f] = name
+ return name
+ return product
+
+
+# Risk domains: grouping of warnings for the dashboard. Determined from the
+# CWE, the MISRA/CERT guideline, keywords in the id and finally the severity.
+D_MEMORY = 'Memory & crash safety'
+D_RESOURCE = 'Resource management'
+D_SECURITY = 'Security & input validation'
+D_CONCURRENCY = 'Concurrency'
+D_LOGIC = 'Logic & correctness'
+D_TYPES = 'Types & portability'
+D_PERFORMANCE = 'Performance'
+D_MAINTAIN = 'Maintainability'
+D_CONFIG = 'Configuration & analysis'
+
+CWE_DOMAIN = {}
+for _domain, _cwes in (
+ (D_MEMORY, (119, 120, 121, 122, 125, 129, 131, 170, 369, 415, 416, 457, 476, 562, 590, 628, 664,
+ 665, 672, 690, 761, 762, 786, 787, 788, 823, 824, 825, 908, 909)),
+ (D_RESOURCE, (400, 401, 404, 459, 772, 773, 775)),
+ (D_SECURITY, (20, 78, 134, 190, 191, 242, 676, 680, 732)),
+ (D_CONCURRENCY, (362, 364, 366, 367, 667, 820, 821, 833)),
+ (D_LOGIC, (128, 252, 480, 481, 482, 483, 484, 561, 570, 571, 581, 595, 597, 628, 682, 683, 685,
+ 686, 687, 688, 697, 768, 783)),
+ (D_TYPES, (188, 192, 194, 195, 196, 197, 467, 468, 469, 474, 475, 477, 681, 704, 758)),
+ (D_PERFORMANCE, (1050,)),
+ (D_MAINTAIN, (398, 563, 1041, 1164))):
+ for _c in _cwes:
+ CWE_DOMAIN.setdefault(_c, _domain)
+
+# MISRA C 2012 rule chapters
+MISRA_DOMAIN = {1: D_TYPES, 2: D_MAINTAIN, 3: D_MAINTAIN, 4: D_MAINTAIN, 5: D_MAINTAIN, 6: D_TYPES,
+ 7: D_TYPES, 8: D_MAINTAIN, 9: D_MEMORY, 10: D_TYPES, 11: D_TYPES, 12: D_LOGIC,
+ 13: D_LOGIC, 14: D_LOGIC, 15: D_MAINTAIN, 16: D_LOGIC, 17: D_LOGIC, 18: D_MEMORY,
+ 19: D_MEMORY, 20: D_MAINTAIN, 21: D_SECURITY, 22: D_RESOURCE, 23: D_MAINTAIN}
+# CERT rule categories
+CERT_DOMAIN = {'ARR': D_MEMORY, 'MEM': D_MEMORY, 'EXP': D_LOGIC, 'STR': D_SECURITY, 'INT': D_SECURITY,
+ 'FIO': D_RESOURCE, 'FLP': D_TYPES, 'DCL': D_MAINTAIN, 'PRE': D_MAINTAIN, 'ERR': D_LOGIC,
+ 'CON': D_CONCURRENCY, 'POS': D_SECURITY, 'SIG': D_SECURITY, 'ENV': D_SECURITY,
+ 'MSC': D_SECURITY, 'API': D_SECURITY, 'WIN': D_SECURITY, 'CTR': D_MEMORY, 'OOP': D_LOGIC}
+
+KEYWORD_DOMAIN = [
+ (re.compile(r'leak|resource|fclose|fopen', re.I), D_RESOURCE),
+ (re.compile(r'null|uninit|bounds|outofbounds|dangling|free|dealloc|lifetime|deref|invalidcontainer|'
+ r'zerodiv|moved|negativeindex|negativeArraySize|invalidIterator', re.I), D_MEMORY),
+ (re.compile(r'overflow|format|printf|scanf|insecure|gets|strncpy|sprintf|taint|cmdline', re.I), D_SECURITY),
+ (re.compile(r'lock|race|thread|mutex|atomic', re.I), D_CONCURRENCY),
+ (re.compile(r'missingInclude|checkLevel|toomany|syntax|internal|unknownMacro|config|checkersReport', re.I), D_CONFIG),
+ (re.compile(r'cast|sign|shift|portab|pointerSize|64|float|char', re.I), D_TYPES),
+ (re.compile(r'condition|duplicate|identical|redundant|always|compare|mismatch|return|assign|bitwise|incorrect', re.I), D_LOGIC),
+ (re.compile(r'passedByValue|postfix|stl|inefficient|copy|useStlAlgorithm|reserve', re.I), D_PERFORMANCE),
+]
+
+SEVERITY_DOMAIN = {'error': D_LOGIC, 'warning': D_LOGIC, 'style': D_MAINTAIN, 'performance': D_PERFORMANCE,
+ 'portability': D_TYPES, 'information': D_CONFIG}
+
+
+def risk_domain(r):
+ if r['cwe'] in CWE_DOMAIN:
+ return CWE_DOMAIN[r['cwe']]
+ guideline = r['guideline']
+ rid = r['id']
+ if guideline or re.match(r'(premium-)?(misra|cert|autosar)', rid, re.I):
+ g = guideline or rid
+ cert = re.search(r'\b([A-Z]{3})\d{2}-(C|CPP)\b', g.upper())
+ if cert:
+ return CERT_DOMAIN.get(cert.group(1), D_MAINTAIN)
+ misra_c = not re.search(r'cert|autosar|c\+\+|cpp', rid, re.I)
+ if misra_c and re.search(r'dir[\s-]*\d', g, re.I):
+ return D_CONFIG if re.search(r'dir[\s-]*[123]\.', g, re.I) else D_MAINTAIN
+ rule = re.search(r'(?:^|[^\d.])(\d+)\.\d+$', g)
+ if misra_c and rule:
+ return MISRA_DOMAIN.get(int(rule.group(1)), D_MAINTAIN)
+ for regex, domain in KEYWORD_DOMAIN:
+ if regex.search(rid):
+ return domain
+ return SEVERITY_DOMAIN.get(r['severity'], D_MAINTAIN)
+
+
+def file_date(path):
+ """The date in the file name (YYYY-MM-DD), or an empty string."""
+ m = re.search(r'(\d{4})-?(\d{2})-?(\d{2})', os.path.basename(path))
+ return '%s-%s-%s' % m.groups() if m else ''
+
+
+def date_label(path):
+ """Label of a snapshot: date in the file name, or the file name."""
+ return file_date(path) or re.sub(r'\.xml$', '', os.path.basename(path), flags=re.I)
+
+
+def history_files(directory):
+ if not os.path.isdir(directory):
+ sys.exit('error: history directory %s not found' % directory)
+ files = glob.glob(os.path.join(directory, '*.xml'))
+
+ def key(p):
+ return (file_date(p), os.path.getmtime(p), os.path.basename(p))
+ return sorted(files, key=key)
+
+
+def select_old_files(args, xml_files):
+ """Determine the older reports and the baseline.
+
+ Returns (snapshots, baseline). A snapshot is a list of files, the snapshots are ordered with
+ the oldest first. The baseline is one of the snapshots, or None."""
+ def unique(files, exclude):
+ seen = {os.path.abspath(f) for f in exclude}
+ out = []
+ for f in files:
+ if os.path.abspath(f) not in seen:
+ seen.add(os.path.abspath(f))
+ out.append(f)
+ return out
+
+ files = unique((history_files(args.history) if args.history else []) + list(args.snapshot or []), xml_files)
+ baseline = unique(args.baseline or [], [])
+ if not baseline:
+ snapshots = [[f] for f in files]
+ return snapshots, snapshots[-1] if snapshots else None
+
+ paths = [os.path.abspath(f) for f in files]
+ if len(baseline) == 1 and os.path.abspath(baseline[0]) in paths:
+ # the baseline is one of the reports in the trend, keep its position
+ snapshots = [[f] for f in files]
+ return snapshots, snapshots[paths.index(os.path.abspath(baseline[0]))]
+
+ # insert the baseline before the first newer report. If there are no dates in
+ # the file names it is assumed to be the newest one.
+ snapshots = [[f] for f in unique(files, baseline)]
+ date = max(file_date(f) for f in baseline)
+ pos = len(snapshots)
+ if date:
+ pos = next((i for i, x in enumerate(snapshots) if file_date(x[0]) > date), pos)
+ snapshots.insert(pos, baseline)
+ return snapshots, baseline
+
+
+def snapshot_stats(results, cls_mode, product_of, prev_keys):
+ """Counts per product and category, new and fixed compared with the previous snapshot."""
+ cats, files, new, new_cats, fixed = {}, {}, {}, {}, {}
+ keys = {}
+ for r in results:
+ f = primary_file(r)
+ p = product_of(f)
+ c = (r['classification'] or 'None') if cls_mode else r['severity']
+ pc = cats.setdefault(p, {})
+ pc[c] = pc.get(c, 0) + 1
+ if f:
+ files.setdefault(p, set()).add(f)
+ k = result_key(r)
+ keys[k] = p
+ if prev_keys is not None and k not in prev_keys:
+ new[p] = new.get(p, 0) + 1
+ pc = new_cats.setdefault(p, {})
+ pc[c] = pc.get(c, 0) + 1
+ if prev_keys is not None:
+ for k, p in prev_keys.items():
+ if k not in keys:
+ fixed[p] = fixed.get(p, 0) + 1
+ stats = {'cats': cats, 'files': {p: len(s) for p, s in files.items()}}
+ if prev_keys is not None:
+ stats['new'] = new
+ stats['newCats'] = new_cats
+ stats['fixed'] = fixed
+ return stats, keys
+
+
+# ---------------------------------------------------------------------------
+# Metrics
+# ---------------------------------------------------------------------------
+
+def load_thresholds(path):
+ """--metrics-thresholds: {"cyclomaticComplexity": {"max": 15}, "HISCOMF": {"min": 10}, "HISParam": 6}"""
+ thresholds = {k: dict(v) for k, v in DEFAULT_THRESHOLDS.items()}
+ if not path:
+ return thresholds
+ try:
+ with open(path, 'rt', encoding='utf-8') as f:
+ data = json.load(f)
+ except (OSError, ValueError) as e:
+ sys.exit('error: failed to read thresholds %s: %s' % (path, e))
+ if not isinstance(data, dict):
+ sys.exit('error: thresholds %s must be a json object' % path)
+ for k, v in data.items():
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ thresholds[k] = {'max': v}
+ elif isinstance(v, dict):
+ thresholds[k] = {b: v[b] for b in ('min', 'max') if isinstance(v.get(b), (int, float))}
+ elif v is None:
+ thresholds.pop(k, None)
+ return thresholds
+
+
+def build_metrics(functions, files):
+ """Compact representation of the metrics (written to data/metrics.js)."""
+ if not functions and not files:
+ return None
+ for v in functions.values():
+ # language scope: VOCF = (N1+N2)/(n1+n2)
+ if 'HISVOCF' not in v and 'HISVocf_N' in v and 'HISVocf_D' in v:
+ v['HISVOCF'] = round(v['HISVocf_N'] / v['HISVocf_D'], 2) if v['HISVocf_D'] else 0
+ v.pop('HISVocf_N', None)
+ v.pop('HISVocf_D', None)
+ for v in files.values():
+ # comment density in percent
+ if 'HISCOMF' not in v and 'HISComment' in v and 'HISStmtFile' in v:
+ v['HISCOMF'] = round(100.0 * v['HISComment'] / v['HISStmtFile'], 1) if v['HISStmtFile'] else 0
+
+ def columns(rows, order):
+ present = set()
+ for v in rows:
+ present.update(v)
+ return [m for m in order if m in present] + sorted(present - set(order))
+
+ fids = columns(functions.values(), FUNCTION_METRICS)
+ lids = columns(files.values(), FILE_METRICS)
+ names = sorted({k[0] for k in functions} | set(files))
+ index = {f: i for i, f in enumerate(names)}
+ return {
+ 'files': names,
+ 'functionIds': fids,
+ 'functions': [[index[k[0]], k[1], k[2]] + [v.get(m) for m in fids]
+ for k, v in sorted(functions.items(), key=lambda x: (x[0][0], x[0][2], x[0][1]))],
+ 'fileIds': lids,
+ 'fileRows': [[index[f]] + [v.get(m) for m in lids] for f, v in sorted(files.items())],
+ }
+
+
+# ---------------------------------------------------------------------------
+# Source files
+# ---------------------------------------------------------------------------
+
+def find_source(filename, search_dirs):
+ if os.path.isabs(filename):
+ return filename if os.path.isfile(filename) else None
+ for d in search_dirs:
+ p = os.path.join(d, filename)
+ if os.path.isfile(p):
+ return p
+ return None
+
+
+def read_source(path, encoding):
+ try:
+ if os.path.getsize(path) > MAX_SOURCE_SIZE:
+ return None
+ with open(path, 'rb') as fh:
+ data = fh.read()
+ except OSError:
+ return None
+ text = data.decode(encoding, errors='replace')
+ return text.replace('\r\n', '\n').replace('\r', '\n')
+
+
+# ---------------------------------------------------------------------------
+# Writing the report
+# ---------------------------------------------------------------------------
+
+def compact_result(r, domains):
+ """Compact json representation of a result, empty fields are left out."""
+ c = {'id': r['id'], 'severity': r['severity'], 'msg': r['msg']}
+ if r['verbose'] and r['verbose'] != r['msg']:
+ c['verbose'] = r['verbose']
+ for key in ('hash', 'remark', 'classification', 'guideline'):
+ if r[key]:
+ c[key] = r[key]
+ if r['cwe']:
+ c['cwe'] = r['cwe']
+ if r['inconclusive']:
+ c['inconclusive'] = 1
+ if r.get('isNew'):
+ c['isNew'] = 1
+ if r['symbols']:
+ c['symbols'] = r['symbols']
+ if r['file0'] and (not r['locations'] or r['file0'] != r['locations'][0]['file']):
+ c['file0'] = r['file0']
+ d = risk_domain(r)
+ if d not in domains:
+ domains[d] = len(domains)
+ c['d'] = domains[d]
+ locs = []
+ for loc in r['locations']:
+ item = [loc['file'], loc['line'], loc['column']]
+ if loc['info'] and loc['info'] != r['msg']:
+ item.append(loc['info'])
+ locs.append(item)
+ c['locations'] = locs
+ return c
+
+
+def write_js(path, prefix, obj, suffix=';\n'):
+ with open(path, 'wt', encoding='utf-8') as f:
+ f.write(prefix)
+ f.write(json.dumps(obj, ensure_ascii=False, separators=(',', ':')))
+ f.write(suffix)
+
+
+def safety_checked(checkers):
+ """True if MISRA/CERT/AUTOSAR checking was enabled (according to the checkers report)."""
+ n_cert = 0
+ for c in checkers:
+ low = c.lower()
+ if low.startswith('misra') or low.startswith('autosar'):
+ return True
+ if low.startswith('cert'):
+ n_cert += 1
+ # some CERT rules are always checked by normal cppcheck checkers
+ return n_cert >= 20
+
+
+def generate(args):
+ xml_files = list(args.files or []) + list(args.xml or [])
+ if not xml_files:
+ sys.exit('error: no xml report given')
+
+ current = parse_reports(xml_files)
+ results = current['results']
+ cls_mode = any(r['classification'] for r in results)
+
+ # older reports, used as baseline and for the trend graphs
+ snapshot_files, baseline_files = select_old_files(args, xml_files)
+ snapshot_reports = []
+ old_results = None
+ for files in snapshot_files:
+ rs = parse_reports(files)['results']
+ if files == baseline_files:
+ old_results = rs
+ snapshot_reports.append((date_label(files[0]) if len(files) == 1 else 'baseline', files, rs))
+
+ all_files = {primary_file(r) for r in results}
+ all_files.update(k[0] for k in current['functions'])
+ all_files.update(current['files'])
+ product_map = load_product_map(args.product_map) if args.product_map else []
+ product_of = make_product_mapper(sorted(f for f in all_files if f), product_map)
+
+ comparison = None
+ if old_results is not None:
+ old_keys = {result_key(r) for r in old_results}
+ new_keys = set()
+ for r in results:
+ k = result_key(r)
+ new_keys.add(k)
+ r['isNew'] = k not in old_keys
+ fixed = [r for r in old_results if result_key(r) not in new_keys]
+ fixed_by_product = {}
+ for r in fixed:
+ p = product_of(primary_file(r))
+ fixed_by_product[p] = fixed_by_product.get(p, 0) + 1
+ comparison = {
+ 'oldFile': ', '.join(os.path.basename(f) for f in baseline_files),
+ 'fixed': len(fixed),
+ 'fixedByProduct': fixed_by_product,
+ 'fixedList': [{'id': r['id'], 'severity': r['severity'], 'msg': r['msg'],
+ 'classification': r['classification'], 'guideline': r['guideline'],
+ 'file': primary_file(r), 'product': product_of(primary_file(r)),
+ 'line': r['locations'][0]['line'] if r['locations'] else 0}
+ for r in fixed[:1000]],
+ }
+
+ # trend: one entry per report, the current report last
+ snapshots = []
+ prev_keys = None
+ for label, files, rs in snapshot_reports + [(datetime.date.today().isoformat(), xml_files, results)]:
+ stats, prev_keys = snapshot_stats(rs, cls_mode, product_of, prev_keys)
+ stats['label'] = label
+ stats['file'] = ', '.join(os.path.basename(f) for f in files)
+ snapshots.append(stats)
+
+ out = args.output_dir
+ data_dir = os.path.join(out, 'data')
+ src_dir = os.path.join(data_dir, 'src')
+ try:
+ os.makedirs(src_dir, exist_ok=True)
+ # remove files from a previous run
+ for f in glob.glob(os.path.join(src_dir, '*.js')) + glob.glob(os.path.join(data_dir, 'metrics.js')):
+ os.remove(f)
+ except OSError as e:
+ sys.exit('error: failed to create %s: %s' % (src_dir, e.strerror))
+
+ search_dirs = list(args.source_dir or [])
+ search_dirs.append(os.getcwd())
+ search_dirs.extend(os.path.dirname(os.path.abspath(f)) for f in xml_files)
+
+ metrics = build_metrics(current['functions'], current['files'])
+ if metrics:
+ write_js(os.path.join(data_dir, 'metrics.js'), 'CPPCHECK_METRICS(', metrics, ');\n')
+
+ # write each source file as a separate js file that is loaded when it is needed
+ sources = {}
+ missing = []
+ files = {loc['file'] for r in results for loc in r['locations'] if loc['file']}
+ if metrics:
+ files.update(metrics['files'])
+ for f in sorted(files):
+ p = find_source(f, search_dirs)
+ text = read_source(p, args.source_encoding) if p else None
+ if text is None:
+ missing.append(f)
+ continue
+ n = len(sources)
+ write_js(os.path.join(src_dir, '%d.js' % n), 'CPPCHECK_SOURCE(%d,' % n, text, ');\n')
+ sources[f] = n
+
+ domains = {}
+ compact = [compact_result(r, domains) for r in results]
+ products = {}
+ for f in sorted(all_files):
+ if f:
+ products[f] = product_of(f)
+ data = {
+ 'title': args.title,
+ 'cppcheckVersion': current['version'],
+ 'reportFile': ', '.join(os.path.basename(f) for f in xml_files),
+ 'generated': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
+ 'theme': args.theme,
+ 'comparison': comparison,
+ 'snapshots': snapshots,
+ 'products': products,
+ 'domains': sorted(domains, key=domains.get),
+ 'safetyChecked': safety_checked(current['checkers']),
+ 'criticalErrors': sorted(current['critical']),
+ 'metrics': {'functions': len(metrics['functions']), 'files': len(metrics['files'])} if metrics else None,
+ 'thresholds': load_thresholds(args.metrics_thresholds),
+ 'sources': sources,
+ 'missingSources': missing,
+ 'results': compact,
+ }
+ write_js(os.path.join(data_dir, 'results.js'), 'window.CPPCHECK_REPORT=', data)
+
+ page = HTML_TEMPLATE.replace('%%TITLE%%', html.escape(args.title)).replace('%%THEME%%', html.escape(args.theme))
+ for name, content in (('index.html', page), ('report.css', CSS), ('report.js', JS_LIB + JS)):
+ with open(os.path.join(out, name), 'wt', encoding='utf-8') as f:
+ f.write(content)
+
+ return results, comparison, missing, metrics, snapshots
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description='Convert Cppcheck XML report(s) into a Cppcheck Explorer report.')
+ parser.add_argument('files', nargs='*', metavar='FILE',
+ help='cppcheck xml report(s) (generated with --xml)')
+ parser.add_argument('--xml', metavar='FILE', action='append',
+ help='cppcheck xml report, can be given several times to combine reports')
+ parser.add_argument('-o', '--output-dir', default='cppcheck-report', metavar='DIR',
+ help='directory where the report is written (default: cppcheck-report)')
+ parser.add_argument('--baseline', '--old', dest='baseline', metavar='FILE', action='append',
+ help='baseline cppcheck xml report, warnings that are not in the baseline are new '
+ '(can be given several times). If it is not given, the newest '
+ '--history/--snapshot report is used')
+ parser.add_argument('--history', metavar='DIR',
+ help='directory with older xml reports, used for trend graphs. Reports are ordered '
+ 'by the date in the file name (e.g. results-2026-05-31.xml) or the file time')
+ parser.add_argument('--snapshot', metavar='FILE', action='append',
+ help='older xml report used for trend graphs (can be given several times, oldest first)')
+ parser.add_argument('--product-map', metavar='FILE',
+ help='json file that maps path prefixes to product names: {"src/core": "Core"}')
+ parser.add_argument('--metrics-thresholds', metavar='FILE',
+ help='json file with metric thresholds: {"cyclomaticComplexity": {"max": 15}}')
+ parser.add_argument('--source-dir', metavar='DIR', action='append',
+ help='directory where source files are searched (can be given several times)')
+ parser.add_argument('--source-encoding', default='utf-8', metavar='ENCODING',
+ help='encoding of the source files (default: utf-8)')
+ parser.add_argument('--title', default='Cppcheck report', help='report title')
+ parser.add_argument('--theme', default='light', choices=THEMES,
+ help='default theme (default: light)')
+ args = parser.parse_args()
+
+ if not args.files and not args.xml:
+ parser.error('no xml report given')
+ try:
+ ''.encode(args.source_encoding)
+ except LookupError:
+ parser.error('unknown encoding: %s' % args.source_encoding)
+
+ results, comparison, missing, metrics, snapshots = generate(args)
+
+ n = len(results)
+ msg = 'Wrote %s (%d warning%s' % (os.path.join(args.output_dir, 'index.html'), n, '' if n == 1 else 's')
+ if comparison is not None:
+ new = sum(1 for r in results if r.get('isNew'))
+ msg += ', %d new, %d fixed' % (new, comparison['fixed'])
+ if len(snapshots) > 1:
+ msg += ', %d reports in trend' % len(snapshots)
+ if metrics:
+ msg += ', metrics for %d functions' % len(metrics['functions'])
+ msg += ')'
+ print(msg)
+ if missing:
+ print('note: %d source file(s) not found, use --source-dir to specify where they are'
+ % len(missing))
+
+
+HTML_TEMPLATE = r'''
+
+
+
+
+%%TITLE%%
+
+
+
+
+
+
';
+
+ if (HAS_PRODUCTS) {
+ const n = countBy(NEWONLY ? RESULTS.filter(r => r.isNew) : RESULTS, r => r.product);
+ h += `
` +
+ PRODUCTS.map(p => ``).join('') + '
';
+ }
+
+ h += summaryHtml(P);
+ h += kpiHtml(P);
+
+ const cards = []; // [span, html]
+ const half = html => cards.push(['half', html]);
+
+ // trend graphs
+ if (HAS_TREND) {
+ const S = SNAPSHOTS.slice(1);
+ // new warnings can't be determined for the oldest report
+ const T = NEWONLY ? S : SNAPSHOTS;
+ const cats = T.map(s => snapCats(s, prod, NEWONLY ? 'newCats' : 'cats'));
+ const series = [{ label: 'Total', color: 'var(--text)', values: cats.map(sumValues) }]
+ .concat(GROUPS.map(g => ({ label: g.label, color: g.color, values: cats.map(c => groupCount(c, g)) })));
+ cards.push(['span-8', `
Quality trend
${NEWONLY ? 'New warnings in each report, compared with the report before' : `All warnings in the last ${T.length} reports`}${prod ? ' · ' + esc(prod) : ''}
In ${esc(RAW.comparison.oldFile)} but not in this report${RAW.comparison.fixed > RAW.comparison.fixedList.length ? ` (showing ${fmt(fl.length)})` : ''}
');
+ }
+ }
+
+ // an odd number of half width cards: the last one gets the full width
+ const halves = cards.filter(c => c[0] === 'half');
+ if (halves.length % 2) halves[halves.length - 1][0] = 'span-12';
+ if (RAW.metrics) cards.push(['span-12', metricsCardHtml()]);
+
+ h += '
' + cards.map(([span, html]) => `
${html}
`).join('') + '
';
+ const el = $('#view-dashboard');
+ el.innerHTML = h;
+}
+
+function summaryHtml(P) {
+ const prod = state.product;
+ const nFiles = new Set(P.map(r => r.loc.file).filter(Boolean)).size;
+ const s = [];
+ const plural = (n, one, many) => n === 1 ? one : many;
+ s.push(`${prod ? '' + esc(prod) + '' : 'The project'} has ${fmt(P.length)} ${plural(P.length, 'warning', 'warnings')} in ${fmt(nFiles)} ${plural(nFiles, 'file', 'files')}.`);
+ if (HAS_CMP) {
+ const nNew = P.filter(r => r.isNew).length;
+ const nFixed = fixedCount(prod);
+ const net = nNew - nFixed;
+ s.push(`Since the baseline (${esc(RAW.comparison.oldFile)}), ${fmt(nNew)} new ${plural(nNew, 'warning has', 'warnings have')} appeared and ${fmt(nFixed)} ${plural(nFixed, 'was', 'were')} fixed` +
+ (net > 0 ? ` — the number of warnings went up by ${fmt(net)}.` : net < 0 ? ` — the number of warnings went down by ${fmt(-net)}.` : '.'));
+ }
+ const ub = P.filter(r => r.ub);
+ if (ub.length) {
+ let t = `${fmt(ub.length)} ${plural(ub.length, 'warning indicates', 'warnings indicate')} undefined behavior or crashes`;
+ if (!prod && HAS_PRODUCTS) {
+ const top = [...countBy(ub, r => r.product).entries()].filter(x => x[0]).sort((a, b) => b[1] - a[1])[0];
+ if (top) t += `, most of them in ${esc(top[0])} (${fmt(top[1])})`;
+ }
+ s.push(t + '. These should be fixed first.');
+ } else if (P.length) s.push('No warnings indicate undefined behavior.');
+ const doms = [...countBy(P.filter(r => r.domain), r => r.domain).entries()].sort((a, b) => b[1] - a[1]);
+ if (doms.length) s.push(`The largest risk domain is ${esc(doms[0][0].toLowerCase())} (${pct(doms[0][1], P.length)} of the warnings).`);
+ if (METRICS) {
+ const fs = metricFuncs();
+ const bad = fs.filter(f => f.viol).length;
+ if (fs.length) s.push(`${fmt(bad)} of ${fmt(fs.length)} functions exceed one or more metric thresholds.`);
+ }
+
+ const badge = (cls, icon, title, small, go) => `
${metricsError ? 'Failed to load data/metrics.js' : 'Loading metrics…'}
`;
+ const fs = metricFuncs(), fl = metricFiles();
+ const bad = fs.filter(f => f.viol).length;
+ const ccj = METRICS.fids.indexOf('cyclomaticComplexity');
+ let maxcc = 0;
+ if (ccj >= 0) for (const f of fs) if ((f.v[ccj] || 0) > maxcc) maxcc = f.v[ccj];
+ const comfj = METRICS.lids.indexOf('HISCOMF');
+ const lowCom = comfj < 0 ? null : fl.filter(f => f.bad[comfj]).length;
+ h += `
HIS metrics for ${fmt(fs.length)} functions in ${fmt(fl.length)} files${state.product ? ' · ' + esc(state.product) : ''}. Thresholds can be changed in the metrics view.