From 70909e7f7cc57fba117e98b6e067a919370b4f92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Tue, 1 Dec 2026 15:34:03 +0100 Subject: [PATCH 1/3] Fix #15295 (report : new html-report with dashboard) --- .codacy.yml | 2 +- .github/workflows/release-windows.yml | 4 +- .github/workflows/scriptcheck.yml | 8 +- .gitignore | 6 +- Makefile | 2 +- cli/CMakeLists.txt | 2 +- man/manual-ja.docbook | 6 +- man/manual.md | 74 +- reports/explorer/README.md | 127 + reports/explorer/report.py | 2991 +++++++++++++++++ {htmlreport => reports/htmlreport}/README.txt | 0 .../htmlreport}/cppcheck-htmlreport | 0 .../cppcheck_htmlreport/__init__.py | 0 .../htmlreport}/requirements.txt | 0 {htmlreport => reports/htmlreport}/setup.py | 2 +- test/tools/htmlreport/check.sh | 10 +- test/tools/htmlreport/test_htmlreport.py | 2 +- tools/dmake/dmake.cpp | 2 +- 18 files changed, 3209 insertions(+), 29 deletions(-) create mode 100644 reports/explorer/README.md create mode 100755 reports/explorer/report.py rename {htmlreport => reports/htmlreport}/README.txt (100%) rename {htmlreport => reports/htmlreport}/cppcheck-htmlreport (100%) rename {htmlreport => reports/htmlreport}/cppcheck_htmlreport/__init__.py (100%) rename {htmlreport => reports/htmlreport}/requirements.txt (100%) rename {htmlreport => reports/htmlreport}/setup.py (95%) 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 d01915c6ea6..d239ee0406c 100644 --- a/.github/workflows/scriptcheck.yml +++ b/.github/workflows/scriptcheck.yml @@ -107,7 +107,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/htmlreport/**/*.py test/**/*.py tools/**/*.py - name: check .json files if: matrix.python-latest @@ -123,8 +123,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/htmlreport/**/*.py python -m py_compile test/**/*.py python -m py_compile tools/**/*.py @@ -165,7 +165,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 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..244c0bd8446 100644 --- a/man/manual.md +++ b/man/manual.md @@ -1341,11 +1341,11 @@ 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. +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 reports/htmlreport that contains a script that transforms a Cppcheck XML file into HTML output. This command generates the help screen: - htmlreport/cppcheck-htmlreport -h + reports/htmlreport/cppcheck-htmlreport -h The output screen says: @@ -1394,6 +1394,53 @@ 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. +# Cppcheck Explorer report + +The script `reports/explorer/report.py` in the Cppcheck source tree converts Cppcheck XML output into a Cppcheck Explorer report, which you view in a browser. The report has a dashboard with graphs, and a results view where you can filter the warnings and see the related source code. It 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 a 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. No web server is needed. 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. + +To see all options, run: + + python3 reports/explorer/report.py -h + # Check level ## Reduced @@ -1550,16 +1597,31 @@ 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: +To view the metrics, it is recommended that you generate a [Cppcheck Explorer report](#cppcheck-explorer-report): + + python3 reports/explorer/report.py res.xml -o cppcheck-report + +Open `cppcheck-report/index.html` in a browser. 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 + +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..9323d05aea9 --- /dev/null +++ b/reports/explorer/report.py @@ -0,0 +1,2991 @@ +#!/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 + + +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']) + return 'k:%s|%s|%s' % (r['id'], r['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)): + 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%% + + + + +
+
+ +
+
+
+
+
+ +
+ + +
+
+ +
+
+
+ + +
+
+ + +
+
+
+ +
+
+
+
+
+
+
+
+
+
+ + + + + +''' + +CSS = r''' +:root { + --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + --mono: ui-monospace, "SF Mono", "Cascadia Code", "JetBrains Mono", Menlo, Consolas, monospace; + --radius: 10px; + --radius-sm: 6px; + --bg: #f6f7f9; + --surface: #ffffff; + --surface-2: #f1f3f6; + --surface-hover: #f3f5f8; + --border: #e3e6eb; + --border-strong: #cdd2da; + --text: #191b1f; + --text-2: #5f6670; + --text-3: #8b929c; + --accent: #2563eb; + --accent-soft: rgba(37, 99, 235, .10); + --accent-text: #ffffff; + --shadow: 0 1px 2px rgba(16, 24, 40, .05), 0 1px 3px rgba(16, 24, 40, .06); + --topbar-bg: rgba(255, 255, 255, .85); + --sev-error: #dc3c3d; + --sev-warning: #f2a600; + --sev-style: #257de0; + --sev-portability: #00b894; + --sev-performance: #6a4ce2; + --sev-information: #8a94a6; + --sev-other: #a0a0a0; + --new: #0a8f3c; + --new-soft: rgba(10, 143, 60, .12); + --old: #9aa1ab; + --hl-line: rgba(37, 99, 235, .08); + --hl-primary: rgba(242, 166, 0, .16); + --code-bg: #ffffff; + --code-gutter: #9aa1ab; + --tok-kw: #a626a4; + --tok-type: #0b7285; + --tok-str: #2f7d32; + --tok-num: #b35900; + --tok-com: #8b929c; + --tok-pp: #c2410c; + --tok-fn: #1d4ed8; + color-scheme: light; +} + +[data-theme="apple"] { + --font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", system-ui, sans-serif; + --radius: 14px; + --radius-sm: 8px; + --bg: #f5f5f7; + --surface: #ffffff; + --surface-2: #f2f2f4; + --surface-hover: #f5f5f7; + --border: #e5e5ea; + --border-strong: #d1d1d6; + --text: #1d1d1f; + --text-2: #6e6e73; + --text-3: #8e8e93; + --accent: #0071e3; + --accent-soft: rgba(0, 113, 227, .10); + --shadow: 0 2px 12px rgba(0, 0, 0, .05); + --topbar-bg: rgba(251, 251, 253, .72); + --hl-line: rgba(0, 113, 227, .07); + --tok-kw: #ad3da4; + --tok-type: #3e8087; + --tok-str: #d12f1b; + --tok-num: #272ad8; + --tok-com: #8a99a6; + --tok-pp: #78492a; + --tok-fn: #326d74; +} + +[data-theme="microsoft"] { + --font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, sans-serif; + --mono: "Cascadia Code", "Cascadia Mono", Consolas, ui-monospace, monospace; + --radius: 8px; + --radius-sm: 4px; + --bg: #f3f3f3; + --surface: #ffffff; + --surface-2: #f5f5f5; + --surface-hover: #f5f5f5; + --border: #e0e0e0; + --border-strong: #d1d1d1; + --text: #242424; + --text-2: #616161; + --text-3: #8a8a8a; + --accent: #0f6cbd; + --accent-soft: rgba(15, 108, 189, .10); + --shadow: 0 2px 4px rgba(0, 0, 0, .10), 0 0 2px rgba(0, 0, 0, .08); + --topbar-bg: rgba(255, 255, 255, .92); + --hl-line: rgba(15, 108, 189, .07); + --tok-kw: #0000ff; + --tok-type: #2b91af; + --tok-str: #a31515; + --tok-num: #098658; + --tok-com: #008000; + --tok-pp: #808080; + --tok-fn: #74531f; +} + +[data-theme="dark"], [data-theme="midnight"] { + color-scheme: dark; + --bg: #121212; + --surface: #1c1c1e; + --surface-2: #262628; + --surface-hover: #242426; + --border: #2e2e31; + --border-strong: #3d3d41; + --text: #ececee; + --text-2: #a1a1a6; + --text-3: #76767c; + --accent: #4c8dff; + --accent-soft: rgba(76, 141, 255, .16); + --shadow: 0 1px 2px rgba(0, 0, 0, .4); + --topbar-bg: rgba(28, 28, 30, .85); + --sev-error: #e0464a; + --sev-warning: #d28e05; + --sev-style: #338ced; + --sev-portability: #00a888; + --sev-performance: #9887ef; + --sev-information: #8a94a6; + --new: #3fcf73; + --new-soft: rgba(63, 207, 115, .14); + --old: #6b7079; + --hl-line: rgba(76, 141, 255, .10); + --hl-primary: rgba(210, 142, 5, .20); + --code-bg: #1a1a1c; + --code-gutter: #5d5d63; + --tok-kw: #c792ea; + --tok-type: #4ec9b0; + --tok-str: #c3e88d; + --tok-num: #f78c6c; + --tok-com: #6a737d; + --tok-pp: #ff9e64; + --tok-fn: #82aaff; +} + +[data-theme="midnight"] { + --bg: #0b1020; + --surface: #121a2e; + --surface-2: #19233b; + --surface-hover: #172038; + --border: #222d48; + --border-strong: #2f3c5e; + --text: #e6eaf5; + --text-2: #9aa5c0; + --text-3: #6c7895; + --accent: #7aa2ff; + --accent-soft: rgba(122, 162, 255, .16); + --topbar-bg: rgba(18, 26, 46, .85); + --code-bg: #0f1628; + --code-gutter: #4a5677; +} + +[data-theme="solarized"] { + --bg: #eee8d5; + --surface: #fdf6e3; + --surface-2: #f5efdc; + --surface-hover: #f7f0dd; + --border: #e2dac3; + --border-strong: #d3c9ad; + --text: #073642; + --text-2: #586e75; + --text-3: #839496; + --accent: #268bd2; + --accent-soft: rgba(38, 139, 210, .12); + --shadow: 0 1px 2px rgba(88, 110, 117, .12); + --topbar-bg: rgba(253, 246, 227, .9); + --code-bg: #fdf6e3; + --code-gutter: #93a1a1; + --hl-line: rgba(38, 139, 210, .08); + --tok-kw: #859900; + --tok-type: #b58900; + --tok-str: #2aa198; + --tok-num: #d33682; + --tok-com: #93a1a1; + --tok-pp: #cb4b16; + --tok-fn: #268bd2; +} + +* { box-sizing: border-box; } +html, body { height: 100%; } +body { + margin: 0; + font-family: var(--font); + font-size: 14px; + line-height: 1.45; + color: var(--text); + background: var(--bg); + -webkit-font-smoothing: antialiased; + display: flex; + flex-direction: column; +} +button, input, select { font: inherit; color: inherit; } +svg { flex: none; } + +/* ---------- top bar ---------- */ +.topbar { + position: sticky; top: 0; z-index: 20; + display: flex; align-items: center; gap: 24px; + padding: 10px 20px; + background: var(--topbar-bg); + backdrop-filter: saturate(180%) blur(16px); + -webkit-backdrop-filter: saturate(180%) blur(16px); + border-bottom: 1px solid var(--border); +} +.brand { display: flex; align-items: center; gap: 10px; min-width: 0; } +.logo { width: 30px; height: 30px; } +.logo rect { fill: var(--accent); } +.logo path { fill: none; stroke: var(--accent-text); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; } +.brand-text { min-width: 0; } +.brand-title { font-weight: 650; font-size: 15px; letter-spacing: -.01em; white-space: nowrap; } +.brand-sub { color: var(--text-2); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.views { display: flex; gap: 4px; padding: 3px; background: var(--surface-2); border-radius: calc(var(--radius-sm) + 3px); margin: 0 auto; } +.view-btn { + display: flex; align-items: center; gap: 7px; + border: 0; background: transparent; cursor: pointer; + padding: 6px 14px; border-radius: var(--radius-sm); + color: var(--text-2); font-weight: 550; +} +.view-btn svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; } +.view-btn:hover { color: var(--text); } +.view-btn.active { background: var(--surface); color: var(--text); box-shadow: var(--shadow); } +.count-pill { font-size: 11px; padding: 1px 7px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); font-variant-numeric: tabular-nums; } +.theme-picker { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 12px; } +select { + background: var(--surface); border: 1px solid var(--border-strong); border-radius: var(--radius-sm); + padding: 5px 8px; cursor: pointer; +} +select:focus-visible, input:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } + +main { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.view { display: none; } +.view.active { display: block; } + +/* ---------- dashboard ---------- */ +#view-dashboard { padding: 24px; max-width: 1400px; width: 100%; margin: 0 auto; } +.dash-head { display: flex; align-items: baseline; justify-content: space-between; margin-bottom: 18px; gap: 16px; flex-wrap: wrap; } +.dash-head h1 { font-size: 24px; letter-spacing: -.02em; margin: 0; font-weight: 700; } +.dash-head .meta { color: var(--text-2); font-size: 13px; } +.kpis { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 14px; margin-bottom: 18px; } +.card { + background: var(--surface); border: 1px solid var(--border); + border-radius: var(--radius); box-shadow: var(--shadow); +} +.kpi { padding: 16px 18px; cursor: pointer; transition: border-color .15s, transform .15s; } +.kpi:hover { border-color: var(--border-strong); transform: translateY(-1px); } +.kpi-label { color: var(--text-2); font-size: 12.5px; font-weight: 550; display: flex; align-items: center; gap: 7px; } +.kpi-value { font-size: 30px; font-weight: 700; letter-spacing: -.02em; margin-top: 4px; } +.kpi-foot { color: var(--text-3); font-size: 12px; margin-top: 2px; } +.kpi-foot .up { color: var(--new); font-weight: 600; } +.grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 14px; } +.panel { padding: 18px 20px 20px; min-width: 0; } +.panel h2 { font-size: 14px; margin: 0 0 2px; font-weight: 650; } +.panel .sub { color: var(--text-2); font-size: 12.5px; margin-bottom: 14px; } +.panel code { font-family: var(--mono); font-size: 12px; } +.span-6 { grid-column: span 6; } .span-12 { grid-column: span 12; } +@media (max-width: 1100px) { .span-6 { grid-column: span 12; } } + +.donut-wrap { display: flex; align-items: center; gap: 24px; flex-wrap: wrap; } +.donut { width: 180px; height: 180px; } +.donut .seg { transition: opacity .15s; cursor: pointer; } +.donut:hover .seg { opacity: .55; } +.donut .seg:hover { opacity: 1; } +.donut-total { font-size: 28px; font-weight: 700; fill: var(--text); } +.donut-cap { font-size: 11px; fill: var(--text-2); } +.legend { list-style: none; margin: 0; padding: 0; flex: 1; min-width: 180px; } +.legend li { + display: grid; grid-template-columns: 12px 1fr auto auto; align-items: center; gap: 10px; + padding: 6px 8px; border-radius: var(--radius-sm); cursor: pointer; +} +.legend li:hover { background: var(--surface-hover); } +.legend .sw { width: 10px; height: 10px; border-radius: 3px; } +.legend .v { font-weight: 600; font-variant-numeric: tabular-nums; } +.legend .p { color: var(--text-3); font-size: 12px; width: 44px; text-align: right; font-variant-numeric: tabular-nums; } + +.bars { display: flex; flex-direction: column; gap: 6px; } +.bar-row { + display: grid; grid-template-columns: minmax(90px, 36%) 1fr 56px; align-items: center; gap: 12px; + padding: 3px 6px; border-radius: var(--radius-sm); cursor: pointer; +} +.bar-row:hover { background: var(--surface-hover); } +.bar-label { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 13px; text-transform: none; } +.bar-label.cap::first-letter { text-transform: uppercase; } +.bar-label.mono { font-family: var(--mono); font-size: 12.5px; } +.bar-label.path { direction: rtl; text-align: left; } +.bar-track { height: 14px; position: relative; } +.bar-fill { display: flex; gap: 2px; height: 100%; border-radius: 0 4px 4px 0; overflow: hidden; min-width: 3px; } +.bar-fill > div { height: 100%; min-width: 2px; } +.bar-value { text-align: right; font-weight: 600; font-variant-numeric: tabular-nums; font-size: 13px; } +.chart-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: -4px 0 12px; color: var(--text-2); font-size: 12px; } +.chart-legend span { display: inline-flex; align-items: center; gap: 6px; } +.chart-legend i { width: 10px; height: 10px; border-radius: 3px; display: inline-block; } +.empty { color: var(--text-3); padding: 24px 0; text-align: center; } + +.cmp { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 18px; } +.cmp-item { padding: 12px 14px; border-radius: var(--radius-sm); background: var(--surface-2); cursor: pointer; } +.cmp-item:hover { outline: 1px solid var(--border-strong); } +.cmp-item .n { font-size: 24px; font-weight: 700; } +.cmp-item .l { color: var(--text-2); font-size: 12.5px; display: flex; align-items: center; gap: 6px; } +.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; flex: none; } + +table.tbl { width: 100%; border-collapse: collapse; font-size: 13px; } +.tbl th { text-align: left; color: var(--text-2); font-weight: 550; font-size: 12px; padding: 6px 8px; border-bottom: 1px solid var(--border); } +.tbl td { padding: 7px 8px; border-bottom: 1px solid var(--border); font-variant-numeric: tabular-nums; } +.tbl tr:last-child td { border-bottom: 0; } +.tbl td.num, .tbl th.num { text-align: right; } +.tbl tbody tr.click { cursor: pointer; } +.tbl tbody tr.click:hover td { background: var(--surface-hover); } +.tbl .mono { font-family: var(--mono); font-size: 12px; } + +/* ---------- badges ---------- */ +.sev { display: inline-flex; align-items: center; gap: 5px; font-size: 11.5px; font-weight: 600; white-space: nowrap; } +.sev.cap { text-transform: capitalize; } +.sev .dot { width: 8px; height: 8px; } +.pill { font-size: 10.5px; font-weight: 700; letter-spacing: .03em; text-transform: uppercase; padding: 1px 6px; border-radius: 99px; white-space: nowrap; } +.pill.new { color: var(--new); background: var(--new-soft); } +.pill.inc { color: var(--text-2); background: var(--surface-2); border: 1px solid var(--border); } +.guide { font-family: var(--mono); font-size: 11.5px; font-weight: 600; padding: 0 6px; border-radius: 4px; background: var(--surface-2); border: 1px solid var(--border); white-space: nowrap; } + +/* ---------- results ---------- */ +#view-results.active { display: grid; grid-template-columns: 250px minmax(340px, 1fr) minmax(400px, 1.25fr); height: calc(100vh - var(--topbar-h, 57px)); } +.filters { border-right: 1px solid var(--border); overflow-y: auto; padding: 16px 14px; background: var(--surface); } +.filter-group { margin-bottom: 20px; } +.filter-title { display: flex; justify-content: space-between; align-items: center; font-size: 11.5px; font-weight: 650; text-transform: uppercase; letter-spacing: .05em; color: var(--text-3); margin-bottom: 8px; } +.filter-title .links button { border: 0; background: none; color: var(--accent); cursor: pointer; font-size: 11.5px; text-transform: none; letter-spacing: 0; padding: 0 0 0 8px; font-weight: 550; } +.toggle { + display: flex; align-items: center; gap: 9px; width: 100%; + padding: 6px 8px; border-radius: var(--radius-sm); cursor: pointer; border: 0; background: none; text-align: left; + user-select: none; +} +.toggle:hover { background: var(--surface-hover); } +.toggle .box { + width: 16px; height: 16px; border-radius: 4px; border: 1.5px solid var(--border-strong); + display: grid; place-items: center; flex: none; transition: background .12s, border-color .12s; +} +.toggle .box svg { width: 10px; height: 10px; fill: none; stroke: #fff; stroke-width: 2.5; stroke-linecap: round; stroke-linejoin: round; opacity: 0; } +.toggle.on .box { background: var(--c, var(--accent)); border-color: var(--c, var(--accent)); } +.toggle.on .box svg { opacity: 1; } +.toggle .name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.toggle .name.cap { text-transform: capitalize; } +.toggle .name.mono { font-family: var(--mono); font-size: 12px; } +.toggle .cnt { color: var(--text-3); font-size: 12px; font-variant-numeric: tabular-nums; } +.toggle:not(.on) .name { color: var(--text-2); } +.toggle .only { display: none; color: var(--accent); font-size: 11px; font-weight: 600; } +.toggle:hover .only { display: inline; } +.toggle:hover .cnt.hide-on-hover { display: none; } +.segmented { display: flex; background: var(--surface-2); padding: 3px; border-radius: calc(var(--radius-sm) + 3px); gap: 2px; } +.segmented button { flex: 1; border: 0; background: none; padding: 5px 6px; border-radius: var(--radius-sm); cursor: pointer; color: var(--text-2); font-size: 12.5px; font-weight: 550; white-space: nowrap; } +.segmented button.active { background: var(--surface); color: var(--text); box-shadow: var(--shadow); } +.id-search { width: 100%; padding: 6px 9px; border: 1px solid var(--border-strong); border-radius: var(--radius-sm); background: var(--surface); margin-bottom: 6px; font-size: 12.5px; } +.id-list { max-height: 46vh; overflow-y: auto; margin: 0 -4px; padding: 0 4px; } + +.list-pane { display: flex; flex-direction: column; min-width: 0; min-height: 0; border-right: 1px solid var(--border); } +.list-toolbar { display: flex; gap: 8px; padding: 12px 14px 8px; } +.search { flex: 1; position: relative; } +.search svg { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 15px; height: 15px; fill: none; stroke: var(--text-3); stroke-width: 1.8; stroke-linecap: round; } +.search input { width: 100%; padding: 7px 10px 7px 32px; border: 1px solid var(--border-strong); border-radius: var(--radius-sm); background: var(--surface); } +.active-filters { display: flex; flex-wrap: wrap; gap: 6px; padding: 0 14px; } +.active-filters:not(:empty) { padding-bottom: 6px; } +.chip { display: inline-flex; align-items: center; gap: 6px; padding: 3px 4px 3px 10px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); font-size: 12px; font-weight: 550; max-width: 100%; } +.chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chip button { border: 0; background: none; color: inherit; cursor: pointer; padding: 0 5px; font-size: 14px; line-height: 1; } +.list-summary { padding: 2px 16px 8px; color: var(--text-3); font-size: 12px; } +.result-list { flex: 1; overflow-y: auto; outline: none; position: relative; contain: strict; } +.vspacer { position: relative; } +.item { + position: absolute; left: 8px; right: 8px; height: 72px; + display: block; text-align: left; border: 0; background: none; cursor: pointer; + padding: 8px 12px 8px 14px; border-radius: var(--radius-sm); overflow: hidden; +} +.item::before { content: ""; position: absolute; left: 4px; top: 10px; bottom: 10px; width: 3px; border-radius: 3px; background: var(--c); } +.item:hover { background: var(--surface-hover); } +.item.selected { background: var(--accent-soft); } +.item .row1 { display: flex; align-items: center; gap: 8px; min-width: 0; height: 18px; } +.item .id { font-family: var(--mono); font-size: 12px; color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.item .msg { margin: 2px 0 1px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.item .where { font-family: var(--mono); font-size: 11.5px; color: var(--text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; } +.item.is-old .msg { color: var(--text-2); } + +/* classification mode: filter bar, classification and guideline columns */ +#view-results.cls.active { grid-template-columns: 230px minmax(460px, 1.15fr) minmax(400px, 1.15fr); grid-template-rows: auto minmax(0, 1fr); } +.cls-bar { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 8px 14px; border-bottom: 1px solid var(--border); background: var(--surface); } +.cls-bar[hidden], .list-head[hidden] { display: none; } +.cls-bar .filter-title { margin: 0 8px 0 0; } +.cls-bar .sep { width: 1px; height: 18px; background: var(--border-strong); margin: 0 6px; } +.cls-bar .toggle { width: auto; } +.cls-bar .toggle:disabled { opacity: .45; cursor: default; background: none; } +.cls-bar .only { visibility: hidden; display: inline; } +.cls-bar .toggle:not(:disabled):hover .only { visibility: visible; } +.list-head, .cls .item { display: grid; grid-template-columns: 100px 120px minmax(0, 1fr); column-gap: 10px; } +.list-head { padding: 0 22px 6px; margin: 0; border-bottom: 1px solid var(--border); } +.list-head button { border: 0; background: none; padding: 0; text-align: left; cursor: pointer; font-size: 11.5px; font-weight: 650; color: var(--text-3); } +.list-head button.active { color: var(--accent); } +.cls .item { align-items: start; } +.cls .item .gcol { font-family: var(--mono); font-size: 12px; font-weight: 600; line-height: 18px; overflow: hidden; overflow-wrap: anywhere; max-height: 54px; } +.cls .item .sev { line-height: 18px; overflow: hidden; } +.cls .item .mcol { min-width: 0; } +mark { background: rgba(242, 166, 0, .35); color: inherit; border-radius: 2px; } + +.code-pane { display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--code-bg); } +.tabs { display: flex; overflow-x: auto; background: var(--surface-2); border-bottom: 1px solid var(--border); min-height: 38px; scrollbar-width: thin; flex: none; } +.tab { + display: flex; align-items: center; gap: 8px; padding: 0 6px 0 14px; height: 38px; border: 0; border-right: 1px solid var(--border); + background: none; cursor: pointer; color: var(--text-2); white-space: nowrap; font-size: 12.5px; max-width: 260px; position: relative; flex: none; +} +.tab .tname { overflow: hidden; text-overflow: ellipsis; } +.tab:hover { color: var(--text); } +.tab.active { background: var(--code-bg); color: var(--text); } +.tab.active::after { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 2px; background: var(--accent); } +.tab .x { border-radius: 4px; width: 20px; height: 20px; display: grid; place-items: center; opacity: .55; font-size: 15px; } +.tab .x:hover { background: var(--border); opacity: 1; } +.tabs-empty { padding: 10px 14px; color: var(--text-3); font-size: 12.5px; } +.detail { border-bottom: 1px solid var(--border); padding: 14px 18px; background: var(--surface); max-height: 40%; overflow-y: auto; flex: none; } +.detail:empty { display: none; } +.detail .row1 { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.detail .id { font-family: var(--mono); font-size: 12.5px; color: var(--text-2); } +.detail h3 { margin: 6px 0 4px; font-size: 15px; font-weight: 600; overflow-wrap: anywhere; } +.detail p { margin: 0 0 8px; color: var(--text-2); overflow-wrap: anywhere; white-space: pre-line; } +.detail .meta { display: flex; gap: 14px; flex-wrap: wrap; font-size: 12px; color: var(--text-3); } +.detail .meta a { color: var(--accent); text-decoration: none; } +.detail .meta a:hover { text-decoration: underline; } +.locs { list-style: none; padding: 0; margin: 8px 0 0; font-size: 12.5px; } +.locs li { display: flex; gap: 10px; padding: 4px 8px; border-radius: var(--radius-sm); cursor: pointer; align-items: baseline; } +.locs li:hover { background: var(--surface-hover); } +.locs .n { width: 18px; height: 18px; border-radius: 50%; background: var(--surface-2); border: 1px solid var(--border); font-size: 10.5px; display: grid; place-items: center; flex: none; font-weight: 600; } +.locs .p { font-family: var(--mono); font-size: 11.5px; color: var(--text-2); white-space: nowrap; } +.locs .i { color: var(--text); overflow-wrap: anywhere; } + +.code { flex: 1; overflow: auto; font-family: var(--mono); font-size: 12.5px; position: relative; } +.code-inner { min-width: max-content; padding: 8px 0 40vh; } +.ln { display: flex; white-space: pre; height: 20px; line-height: 20px; } +.ln:hover { background: var(--surface-hover); } +.ln .g { width: 64px; text-align: right; padding-right: 8px; color: var(--code-gutter); user-select: none; flex: none; font-variant-numeric: tabular-nums; } +.ln .m { width: 16px; flex: none; display: flex; align-items: center; justify-content: center; } +.ln .m i { width: 8px; height: 8px; border-radius: 50%; background: var(--c); cursor: pointer; display: block; } +.ln .s { padding-right: 24px; tab-size: 4; } +.ln.hl { background: var(--hl-line); } +.ln.primary { background: var(--hl-primary); } +.ln.primary .g { color: var(--text); font-weight: 600; } +.anno { + margin: 2px 24px 4px 80px; padding: 5px 10px; border-radius: var(--radius-sm); + font-family: var(--font); font-size: 12.5px; line-height: 1.4; white-space: normal; + background: var(--surface); border: 1px solid var(--border); border-left: 3px solid var(--c); + box-shadow: var(--shadow); width: max-content; max-width: min(720px, calc(var(--code-w, 600px) - 110px)); display: flex; gap: 8px; + position: sticky; left: 80px; +} +.anno .n { font-weight: 700; color: var(--text-2); } +.placeholder { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: var(--text-3); gap: 10px; padding: 24px; text-align: center; font-family: var(--font); } +.placeholder svg { width: 48px; height: 48px; fill: none; stroke: var(--border-strong); stroke-width: 1.4; } +.placeholder code { font-family: var(--mono); font-size: 12px; color: var(--text-2); } +.t-kw { color: var(--tok-kw); } +.t-ty { color: var(--tok-type); } +.t-st { color: var(--tok-str); } +.t-nu { color: var(--tok-num); } +.t-co { color: var(--tok-com); font-style: italic; } +.t-pp { color: var(--tok-pp); } +.t-fn { color: var(--tok-fn); } + +@media (max-width: 1000px) { + #view-results.active, #view-results.cls.active { grid-template-columns: 1fr; grid-template-rows: none; height: auto; } + .filters, .list-pane { border-right: 0; border-bottom: 1px solid var(--border); } + .result-list { height: 60vh; flex: none; } + .code-pane { height: 80vh; } + .theme-picker label { display: none; } +} + +/* ---------- tooltip ---------- */ +.tooltip { + position: fixed; z-index: 100; pointer-events: none; opacity: 0; transition: opacity .08s; + background: var(--surface); color: var(--text); border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); box-shadow: 0 6px 20px rgba(0,0,0,.15); + padding: 7px 10px; font-size: 12.5px; max-width: 360px; +} +.tooltip.show { opacity: 1; } +.tooltip .tt-title { font-weight: 600; margin-bottom: 3px; overflow-wrap: anywhere; } +.tooltip .tt-row { display: flex; align-items: center; gap: 7px; color: var(--text-2); } +.tooltip .tt-row b { color: var(--text); margin-left: auto; padding-left: 12px; font-variant-numeric: tabular-nums; } + +/* ---------- status colours (reserved for good/bad states) ---------- */ +:root { --ok: #1a7f37; --ok-soft: rgba(26, 127, 55, .11); --bad: #cf222e; --bad-soft: rgba(207, 34, 46, .10); } +[data-theme="dark"], [data-theme="midnight"] { --ok: #3fb950; --ok-soft: rgba(63, 185, 80, .15); --bad: #f85149; --bad-soft: rgba(248, 81, 73, .15); } + +/* ---------- dashboard additions ---------- */ +.dash-tools { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.dash-tools .segmented { min-width: 240px; } +.pstrip { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 16px; } +.pstrip button { + display: inline-flex; align-items: center; gap: 8px; border: 1px solid var(--border); background: var(--surface); + border-radius: 99px; padding: 5px 12px; cursor: pointer; font-size: 12.5px; font-weight: 550; color: var(--text-2); +} +.pstrip button:hover { border-color: var(--border-strong); color: var(--text); } +.pstrip button.active { background: var(--accent); border-color: var(--accent); color: var(--accent-text); } +.pstrip button .n { font-variant-numeric: tabular-nums; opacity: .75; font-weight: 500; } +.summary { padding: 18px 20px; margin-bottom: 14px; display: flex; gap: 24px; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; } +.summary h2 { font-size: 14px; margin: 0 0 6px; font-weight: 650; } +.summary p { margin: 0; color: var(--text-2); max-width: 80ch; line-height: 1.6; } +.summary p b { color: var(--text); font-weight: 600; } +.badges { display: flex; flex-direction: column; gap: 8px; min-width: 260px; } +.badge { + display: flex; align-items: center; gap: 10px; padding: 8px 12px; border-radius: var(--radius-sm); + font-weight: 600; font-size: 13px; cursor: pointer; border: 1px solid transparent; background: var(--surface-2); color: var(--text-2); +} +.badge svg { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; } +.badge.ok { background: var(--ok-soft); color: var(--ok); } +.badge.bad { background: var(--bad-soft); color: var(--bad); } +.badge:hover { border-color: currentColor; } +.badge.static { cursor: default; } +.badge.static:hover { border-color: transparent; } +.badge .bt { display: flex; flex-direction: column; line-height: 1.25; } +.badge .bt small { font-weight: 500; font-size: 11.5px; opacity: .85; } +.kpis.five { grid-template-columns: repeat(5, minmax(0, 1fr)); } +@media (max-width: 1100px) { .kpis.five { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.kpi-foot .delta { font-weight: 600; } +.kpi-foot .delta.worse { color: var(--bad); } +.kpi-foot .delta.better { color: var(--ok); } +.span-8 { grid-column: span 8; } .span-4 { grid-column: span 4; } +@media (max-width: 1100px) { .span-8, .span-4 { grid-column: span 12; } } +.chart { width: 100%; height: auto; display: block; overflow: visible; } +.chart .gl { stroke: var(--border); stroke-width: 1; } +.chart .ax { fill: var(--text-3); font-size: 11px; font-variant-numeric: tabular-nums; } +.chart .ln2 { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; } +.chart .mk { stroke: var(--surface); stroke-width: 2; } +.chart .hov rect { fill: transparent; } +.chart .hov line { stroke: var(--border-strong); stroke-width: 1; opacity: 0; } +.chart .hov:hover line { opacity: 1; } +.chart .vb { transition: opacity .12s; } +.mstats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; } +@media (max-width: 800px) { .mstats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.mstat { padding: 10px 12px; border-radius: var(--radius-sm); background: var(--surface-2); cursor: pointer; } +.mstat:hover { outline: 1px solid var(--border-strong); } +.mstat .l { color: var(--text-2); font-size: 12px; } +.mstat .n { font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums; } +.mstat .n small { font-size: 12px; font-weight: 500; color: var(--text-3); margin-left: 4px; } +.loading { color: var(--text-3); padding: 24px 0; text-align: center; } + +/* ---------- metrics view ---------- */ +#view-metrics.active { display: flex; flex-direction: column; height: calc(100vh - var(--topbar-h, 57px)); } +.m-toolbar { display: flex; align-items: center; gap: 10px; padding: 12px 16px; border-bottom: 1px solid var(--border); background: var(--surface); flex-wrap: wrap; } +.m-toolbar .segmented { width: 210px; } +.m-toolbar .search { flex: 0 1 300px; } +.m-toolbar .toggle { width: auto; } +.m-toolbar .sum { margin-left: auto; color: var(--text-3); font-size: 12px; } +.btn { border: 1px solid var(--border-strong); background: var(--surface); border-radius: var(--radius-sm); padding: 6px 12px; cursor: pointer; font-weight: 550; font-size: 12.5px; display: inline-flex; align-items: center; gap: 6px; } +.btn:hover { background: var(--surface-hover); } +.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); } +.btn svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; } +.m-thr { border-bottom: 1px solid var(--border); background: var(--surface-2); padding: 14px 16px; } +.m-thr .thr-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 6px 24px; margin-bottom: 12px; } +.m-thr .thr-row { display: grid; grid-template-columns: 1fr 74px 74px; gap: 8px; align-items: center; font-size: 12.5px; } +.m-thr .thr-head { color: var(--text-3); font-size: 11.5px; font-weight: 650; text-transform: uppercase; letter-spacing: .05em; } +.m-thr input { width: 100%; padding: 4px 6px; border: 1px solid var(--border-strong); border-radius: var(--radius-sm); background: var(--surface); text-align: right; font-variant-numeric: tabular-nums; } +.m-thr .acts { display: flex; gap: 8px; align-items: center; } +.m-thr .note { color: var(--text-3); font-size: 12px; margin-left: 8px; } +.m-chips { display: flex; gap: 6px; padding: 8px 16px 0; flex-wrap: wrap; } +.m-chips:empty { display: none; } +.m-table { flex: 1; overflow: auto; position: relative; contain: strict; } +.m-inner { position: relative; } +.m-row, .m-head { display: grid; align-items: center; font-size: 12.5px; } +.m-head { position: sticky; top: 0; z-index: 2; background: var(--surface); border-bottom: 1px solid var(--border); height: 36px; } +.m-head > div { padding: 0 10px; color: var(--text-2); font-weight: 600; font-size: 12px; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; user-select: none; } +.m-head > div:hover { color: var(--text); } +.m-head > div.sorted { color: var(--accent); } +.m-head > div.num { text-align: right; } +.m-row { position: absolute; left: 0; right: 0; height: 32px; border-bottom: 1px solid var(--border); cursor: pointer; } +.m-row:hover { background: var(--surface-hover); } +.m-row > div { padding: 0 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; } +.m-row .fn { font-family: var(--mono); font-size: 12px; font-weight: 550; } +.m-row .path { font-family: var(--mono); font-size: 11.5px; color: var(--text-2); direction: rtl; text-align: left; } +.m-row .num { text-align: right; } +.m-row .num.bad { color: var(--bad); font-weight: 700; background: var(--bad-soft); height: 100%; line-height: 32px; } +.m-row .na { color: var(--text-3); } +.m-row .viol { display: inline-block; min-width: 22px; padding: 0 6px; border-radius: 99px; text-align: center; font-weight: 700; font-size: 11.5px; } +.m-row .viol.bad { background: var(--bad-soft); color: var(--bad); } +.m-row .viol.ok { color: var(--text-3); } + +::-webkit-scrollbar { width: 10px; height: 10px; } +::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 10px; border: 2px solid transparent; background-clip: padding-box; } +::-webkit-scrollbar-track { background: transparent; } +''' + +JS = r''' +(function () { +'use strict'; + +const RAW = window.CPPCHECK_REPORT; +if (!RAW) { + document.body.innerHTML = '

Failed to load data/results.js. Keep the report files together in one folder.

'; + return; +} + +// ---------------------------------------------------------------- data +const RESULTS = RAW.results.map((x, i) => { + const locations = (x.locations || []).map(l => ({ file: l[0] || '', line: l[1] || 0, column: l[2] || 0, info: l[3] || '' })); + const r = { + idx: i, id: x.id || '', severity: x.severity || 'none', msg: x.msg || '', verbose: x.verbose || x.msg || '', + cwe: x.cwe || 0, hash: x.hash || '', inconclusive: !!x.inconclusive, file0: x.file0 || '', remark: x.remark || '', + classification: x.classification || '', guideline: x.guideline || '', symbols: x.symbols || [], isNew: !!x.isNew, + locations, + }; + r.loc = locations[0] || { file: '', line: 0, column: 0, info: '' }; + r.hay = [r.msg, r.id, r.guideline, r.classification, r.cwe ? 'cwe-' + r.cwe : '', r.symbols.join(' '), + ...locations.map(l => l.file + ':' + l.line)].join('\n').toLowerCase(); + return r; +}); +const HAS_CMP = !!RAW.comparison; +const CLS_MODE = RESULTS.some(r => r.classification); + +// "category" is the severity, or the classification in classification mode +const SEV_ORDER = ['error', 'warning', 'style', 'portability', 'performance', 'information', 'debug', 'internal', 'none']; +const CLS_ORDER = ['Mandatory', 'Required', 'Advisory', 'Document', 'Disapplied', 'L1', 'L2', 'L3', 'None']; +const CAT_ORDER = CLS_MODE ? CLS_ORDER : SEV_ORDER; +const CAT_COLOR = { + error: 'error', warning: 'warning', style: 'style', portability: 'portability', performance: 'performance', information: 'information', + Mandatory: 'error', Required: 'warning', Advisory: 'style', Document: 'portability', Disapplied: 'performance', None: 'information', + L1: 'error', L2: 'warning', L3: 'style', +}; +const CAT_NAME = CLS_MODE ? 'Classification' : 'Severity'; +const catOf = r => CLS_MODE ? (r.classification || 'None') : r.severity; +const catRank = c => { const i = CAT_ORDER.indexOf(c); return i < 0 ? CAT_ORDER.length : i; }; +const catColor = c => CAT_COLOR[c] ? `var(--sev-${CAT_COLOR[c]})` : 'var(--sev-other)'; +const sevColor = s => SEV_ORDER.includes(s) && CAT_COLOR[s] ? `var(--sev-${CAT_COLOR[s]})` : 'var(--sev-other)'; +const catCmp = (a, b) => catRank(a) - catRank(b) || a.localeCompare(b); +RESULTS.forEach(r => { r.cat = catOf(r); r.catRank = catRank(r.cat); }); + +const $ = (sel, el) => (el || document).querySelector(sel); +const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +const fmt = n => (n || 0).toLocaleString(); +const pct = (n, t) => t ? (100 * n / t).toFixed(n / t < 0.1 ? 1 : 0) + '%' : '0%'; +const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : s; +const basename = p => p.split(/[\\/]/).pop(); +const countBy = (arr, f) => { const m = new Map(); for (const x of arr) { const k = f(x); m.set(k, (m.get(k) || 0) + 1); } return m; }; +const catBadge = c => `${esc(c)}`; +const sevBadge = s => `${esc(s)}`; +const checkSvg = ''; + +const ALL_CATS = [...new Set(RESULTS.map(r => r.cat))].sort(catCmp); +// the "id" filter uses the guideline in classification mode +const keyOf = r => CLS_MODE ? (r.guideline || r.id) : r.id; +RESULTS.forEach(r => { r.key = keyOf(r); }); +const KEY_NAME = CLS_MODE ? 'Guidelines' : 'Warning ids'; +const ALL_IDS = [...countBy(RESULTS, r => r.key).entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0], undefined, { numeric: true })); +const ID_NAMES = ALL_IDS.map(x => x[0]); + +// products, risk domains, undefined behavior and MISRA/CERT (safety) warnings +const PRODUCT_OF = RAW.products || {}; +const DOMAINS = RAW.domains || []; +const NOT_UB = /leak|^syntaxError|^internal|^cppcheckError|^preprocessorErrorDirective|^unknownMacro|^missingInclude|^checkersReport|^premium-/i; +const SAFETY_ID = /^(premium-)?(misra|cert|autosar)/i; +RESULTS.forEach(r => { + r.product = PRODUCT_OF[r.loc.file] || ''; + r.domain = DOMAINS[RAW.results[r.idx].d] || ''; + r.ub = r.severity === 'error' && !NOT_UB.test(r.id); + r.safety = !!r.classification || SAFETY_ID.test(r.id); +}); +const PRODUCTS = (() => { + const n = countBy(RESULTS, r => r.product); + return [...new Set(Object.values(PRODUCT_OF))].sort((a, b) => (n.get(b) || 0) - (n.get(a) || 0) || a.localeCompare(b)); +})(); +// no product filter if all source files are in the same folder +const FOLDERS = new Set(Object.keys(PRODUCT_OF).map(f => f.replace(/\\/g, '/').replace(/[^/]*$/, ''))); +const HAS_PRODUCTS = PRODUCTS.length > 1 && FOLDERS.size > 1; +const SAFETY_CHECKED = !!RAW.safetyChecked || RESULTS.some(r => r.safety); + +// trend data: one snapshot per report, the current report is the last one +const SNAPSHOTS = RAW.snapshots || []; +const HAS_TREND = SNAPSHOTS.length > 1; +const PREV = HAS_TREND ? SNAPSHOTS[SNAPSHOTS.length - 2] : null; +function snapCats(s, product, field) { + const out = {}; + for (const [p, cats] of Object.entries(s[field || 'cats'] || {})) { + if (product && p !== product) continue; + for (const [c, n] of Object.entries(cats)) out[c] = (out[c] || 0) + n; + } + return out; +} +function snapNum(s, field, product) { + const o = s && s[field]; + if (!o) return null; + if (product) return o[product] || 0; + let t = 0; + for (const v of Object.values(o)) t += v; + return t; +} +// warnings in the baseline that are not in this report +const fixedCount = product => product ? RAW.comparison.fixedByProduct[product] || 0 : RAW.comparison.fixed; +const sumValues = o => { let t = 0; for (const v of Object.values(o)) t += v; return t; }; + +// the KPI groups: errors / warnings / style+performance+portability (or mandatory / required / advisory) +const GROUPS = (() => { + if (!CLS_MODE) return [ + { label: 'Errors', cats: ['error'] }, + { label: 'Warnings', cats: ['warning'] }, + { label: 'Style, performance & portability', cats: ['style', 'performance', 'portability'] }]; + const g1 = ['Mandatory', 'L1'], g2 = ['Required', 'L2']; + const name = (cats, dflt) => cats.filter(c => ALL_CATS.includes(c)).join(' / ') || dflt; + return [ + { label: name(g1, 'Mandatory'), cats: g1 }, + { label: name(g2, 'Required'), cats: g2 }, + { label: 'Advisory & other', cats: CLS_ORDER.filter(c => !g1.includes(c) && !g2.includes(c)) }]; +})(); +GROUPS.forEach(g => { g.color = catColor(g.cats[0]); }); +const groupCount = (cats, g) => g.cats.reduce((a, c) => a + (cats[c] || 0), 0); + +// ---------------------------------------------------------------- state +const state = { + view: 'dashboard', + cats: new Set(ALL_CATS), + hiddenIds: new Set(), + status: 'all', // all | new | old + inconclusive: true, + search: '', + file: '', + product: '', // shared by dashboard, results and metrics + domain: '', + only: '', // '' | ub | safety + scope: 'all', // dashboard graphs: all | new + sort: 'category', + selected: -1, + idSearch: '', +}; + +// ---------------------------------------------------------------- theme & header +const themeSelect = $('#theme-select'); +function setTheme(t) { + document.documentElement.dataset.theme = t; + themeSelect.value = t; + try { localStorage.setItem('cppcheck-report-theme', t); } catch (e) { /* ignore */ } +} +let savedTheme = null; +try { savedTheme = localStorage.getItem('cppcheck-report-theme'); } catch (e) { /* ignore */ } +setTheme(savedTheme || RAW.theme || 'light'); +themeSelect.addEventListener('change', () => setTheme(themeSelect.value)); + +$('#title').textContent = RAW.title; +document.title = RAW.title; +{ + const parts = []; + if (RAW.cppcheckVersion) parts.push('Cppcheck ' + RAW.cppcheckVersion); + parts.push(RAW.reportFile); + if (HAS_CMP) parts.push('baseline ' + RAW.comparison.oldFile); + parts.push(RAW.generated); + $('#subtitle').textContent = parts.join(' · '); +} + +$('#sort').innerHTML = [['category', 'Sort: ' + CAT_NAME.toLowerCase()], ['file', 'Sort: file'], ['id', CLS_MODE ? 'Sort: guideline' : 'Sort: id']] + .concat(HAS_CMP ? [['new', 'Sort: new first']] : []).map(([v, l]) => ``).join(''); + +document.querySelectorAll('.view-btn').forEach(b => b.addEventListener('click', () => showView(b.dataset.view))); +function showView(v) { + if (v === 'metrics' && !RAW.metrics) v = 'dashboard'; + state.view = v; + document.querySelectorAll('.view-btn').forEach(b => b.classList.toggle('active', b.dataset.view === v)); + document.querySelectorAll('.view').forEach(s => s.classList.toggle('active', s.id === 'view-' + v)); + if (history.replaceState) history.replaceState(null, '', v === 'dashboard' ? '#' : '#' + v); + if (v === 'results') renderResults(); + else if (v === 'metrics') renderMetrics(); + else if (dashKey !== dashStateKey()) renderDashboard(); +} + +// ---------------------------------------------------------------- tooltip +const tip = $('#tooltip'); +document.addEventListener('mouseover', e => { + const el = e.target.closest('[data-tip]'); + if (!el) { tip.classList.remove('show'); return; } + tip.innerHTML = el.dataset.tip; + tip.classList.add('show'); +}); +document.addEventListener('mousemove', e => { + if (!tip.classList.contains('show')) return; + const w = tip.offsetWidth, h = tip.offsetHeight; + let x = e.clientX + 14, y = e.clientY + 14; + if (x + w > window.innerWidth - 8) x = e.clientX - w - 14; + if (y + h > window.innerHeight - 8) y = e.clientY - h - 14; + tip.style.left = x + 'px'; tip.style.top = y + 'px'; +}); +const tipHtml = (title, rows) => esc('
' + esc(title) + '
' + + rows.map(([c, l, v]) => `
${c ? `` : ''}${esc(l)}${esc(v)}
`).join('')); + +// ---------------------------------------------------------------- charts +function donut(segments, total, caption) { + const R = 70, C = 2 * Math.PI * R, GAP = segments.filter(s => s.value).length > 1 ? 2.5 : 0; + let off = 0, out = ''; + for (const s of segments) { + if (!s.value) continue; + const len = C * s.value / total; + const dash = Math.max(len - GAP, 0.5); + out += ``; + off += len; + } + if (!total) out = ``; + return `${out} + ${fmt(total)} + ${esc(caption)}`; +} + +// rows: [{label, key, segments:[{label,value,color}]}] +function hbars(rows, opts) { + if (!rows.length) return '
No data
'; + const max = Math.max(...rows.map(r => r.segments.reduce((a, s) => a + s.value, 0))); + return '
' + rows.map(r => { + const tot = r.segments.reduce((a, s) => a + s.value, 0); + const segs = r.segments.filter(s => s.value).map(s => `
`).join(''); + const tipRows = r.segments.filter(s => s.value).map(s => [s.color, s.label, fmt(s.value)]); + if (tipRows.length > 1) tipRows.push([null, 'Total', fmt(tot)]); + return `
+
${esc(r.label)}
+
${segs}
+
${fmt(tot)}
`; + }).join('') + '
'; +} + +function chartLegend(items) { + return '
' + items.map(([c, l]) => `${esc(l)}`).join('') + '
'; +} + +// ---- axis helpers for the svg charts +function niceStep(max, n) { + const raw = Math.max(max, 1) / n; + const p = Math.pow(10, Math.floor(Math.log10(raw))); + const m = raw / p; + return Math.max(1, (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p); +} +function yAxis(maxV) { + const step = niceStep(maxV, 4); + const top = Math.max(step, Math.ceil(maxV / step) * step); + const ticks = []; + for (let v = 0; v <= top + 1e-9; v += step) ticks.push(v); + return { top, ticks }; +} +const fmtShort = n => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n); +function xLabels(labels, x, H, plotW) { + // show as many labels as fit without overlapping (about 6.5px per character) + const n = labels.length; + const maxLen = labels.reduce((a, l) => Math.max(a, String(l).length), 1); + const fit = Math.max(2, Math.floor(plotW / (maxLen * 6.5 + 14))); + const every = Math.ceil(n / Math.min(fit, 8)); + let g = ''; + labels.forEach((l, i) => { + if (!(i === n - 1 || (i % every === 0 && n - 1 - i >= every))) return; + const anchor = n > 1 && i === 0 ? 'start' : n > 1 && i === n - 1 ? 'end' : 'middle'; + g += `${esc(l)}`; + }); + return g; +} + +// line chart. series: [{label, color, values}] +function lineChart(labels, series, caption) { + const W = 680, H = 230, L = 44, R = 14, T = 10, B = 26; + let maxV = 1; + for (const s of series) for (const v of s.values) if (v > maxV) maxV = v; + const { top, ticks } = yAxis(maxV); + const n = labels.length; + const x = i => n === 1 ? (L + W - R) / 2 : L + i * (W - L - R) / (n - 1); + const y = v => T + (H - T - B) * (1 - v / top); + let g = ''; + for (const t of ticks) g += `${fmtShort(t)}`; + g += xLabels(labels, x, H, W - L - R); + for (const s of series) { + g += ``; + if (n <= 40) g += s.values.map((v, i) => ``).join(''); + } + for (let i = 0; i < n; i++) { + const x0 = i === 0 ? L - 6 : (x(i - 1) + x(i)) / 2, x1 = i === n - 1 ? W - R + 6 : (x(i) + x(i + 1)) / 2; + const tipRows = series.map(s => [s.color, s.label, fmt(s.values[i])]); + g += ``; + } + return `${g}`; +} + +// grouped column chart. series: [{label, color, values}] +function columnChart(labels, series, caption) { + const W = 340, H = 230, L = 40, R = 6, T = 10, B = 26; + let maxV = 1; + for (const s of series) for (const v of s.values) if (v > maxV) maxV = v; + const { top, ticks } = yAxis(maxV); + const n = labels.length, k = series.length; + const band = (W - L - R) / Math.max(n, 1); + const bw = Math.max(2, Math.min(16, (band * 0.72 - (k - 1) * 2) / k)); + const x = i => L + band * (i + 0.5); + const y = v => T + (H - T - B) * (1 - v / top); + let g = ''; + for (const t of ticks) g += `${fmtShort(t)}`; + g += xLabels(labels, x, H, W - L - R); + for (let i = 0; i < n; i++) { + const gw = k * bw + (k - 1) * 2; + series.forEach((s, j) => { + const v = s.values[i] || 0; + if (!v) return; + const x0 = x(i) - gw / 2 + j * (bw + 2), y0 = y(0), yv = y(v), r = Math.min(3, bw / 2, y0 - yv); + g += ``; + }); + g += ``; + } + return `${g}`; +} + +// ---------------------------------------------------------------- dashboard +const ICON_OK = ''; +const ICON_BAD = ''; +const ICON_NA = ''; +const ICON_WARN = ''; + +let dashKey = null; +const dashStateKey = () => [state.product, state.scope, METRICS ? thrVersion : -1].join('|'); + +function renderDashboard() { + dashKey = dashStateKey(); + const prod = state.product; + const P = prod ? RESULTS.filter(r => r.product === prod) : RESULTS; // all warnings (of the product) + const NEWONLY = HAS_CMP && state.scope === 'new'; + const D = NEWONLY ? P.filter(r => r.isNew) : P; // warnings in the graphs + const total = D.length; + const byCat = countBy(D, r => r.cat); + const what = NEWONLY ? 'new warnings' : 'warnings'; + const files = new Set(P.map(r => r.loc.file).filter(Boolean)); + let h = ''; + + h += `

${prod ? esc(prod) : 'Overview'}

${fmt(P.length)} warnings in ${fmt(files.size)} files · ` + + (CLS_MODE ? `${fmt(new Set(P.map(r => r.key)).size)} guidelines` : `${fmt(new Set(P.map(r => r.id)).size)} different checks`) + + (HAS_TREND ? ` · ${SNAPSHOTS.length} reports in trend` : '') + '
'; + if (HAS_CMP) { + h += `
Graphs show
+ +
`; + } + h += '
'; + + 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) : ''}
+ ${chartLegend(series.map(s => [s.color, s.label]))}${lineChart(T.map(s => s.label), series, 'Warnings per report')}`]); + const nf = [{ label: 'New', color: 'var(--new)', values: S.map(s => snapNum(s, 'new', prod) || 0) }, + { label: 'Fixed', color: 'var(--old)', values: S.map(s => snapNum(s, 'fixed', prod) || 0) }]; + cards.push(['span-4', `

New and fixed per report

Compared with the report before
+ ${chartLegend(nf.map(s => [s.color, s.label]))}${columnChart(S.map(s => s.label), nf, 'New and fixed warnings per report')}`]); + } + + // category donut + const segs = ALL_CATS.map(c => ({ key: c, label: cap(c), value: byCat.get(c) || 0, color: catColor(c) })); + half(`

${cap(what)} by ${CAT_NAME.toLowerCase()}

Click a ${CAT_NAME.toLowerCase()} to see its warnings
+
${donut(segs, total, what)}
    ` + + segs.map(s => `
  • ${esc(s.label)}${fmt(s.value)}${pct(s.value, total)}
  • `).join('') + + '
'); + + if (HAS_CMP) { + const pc = countBy(P, r => r.cat); + const newByCat = countBy(P.filter(r => r.isNew), r => r.cat); + const nNew = P.filter(r => r.isNew).length; + const nFixed = fixedCount(prod); + const rows = ALL_CATS.filter(c => pc.get(c)).map(c => ({ label: cap(c), key: c, segments: [ + { label: 'New', value: newByCat.get(c) || 0, color: 'var(--new)' }, + { label: 'Old', value: (pc.get(c) || 0) - (newByCat.get(c) || 0), color: 'var(--old)' }] })); + half(`

New and old warnings

Baseline: ${esc(RAW.comparison.oldFile)}
+
+
New
${fmt(nNew)}
+
Old
${fmt(P.length - nNew)}
+
Fixed since baseline
${fmt(nFixed)}
+
${chartLegend([['var(--new)', 'New'], ['var(--old)', 'Old']])}${hbars(rows, { kind: 'cat' })}`); + } else { + const groups = new Map(); + for (const r of D) { + if (!groups.has(r.cat)) groups.set(r.cat, { n: 0, ids: new Set(), files: new Set() }); + const g = groups.get(r.cat); g.n++; g.ids.add(r.key); g.files.add(r.loc.file); + } + half(`

${CAT_NAME} summary

Run with --baseline to see new and old warnings
+ ` + + ALL_CATS.filter(c => groups.has(c)).map(c => { const g = groups.get(c); + return ``; + }).join('') + '
${CAT_NAME}Warnings${CLS_MODE ? 'Guidelines' : 'Checks'}FilesShare
${catBadge(c)}${fmt(g.n)}${fmt(g.ids.size)}${fmt(g.files.size)}${pct(g.n, total)}
'); + } + + // risk domains + { + const byDom = new Map(); + for (const r of D) { + if (!r.domain) continue; + if (!byDom.has(r.domain)) byDom.set(r.domain, new Map()); + const m = byDom.get(r.domain); m.set(r.cat, (m.get(r.cat) || 0) + 1); + } + const rows = [...byDom.entries()].map(([d, m]) => ({ d, m, n: sumValues(Object.fromEntries(m)) })) + .sort((a, b) => b.n - a.n).map(({ d, m }) => ({ label: d, key: d, segments: ALL_CATS.map(c => ({ label: cap(c), value: m.get(c) || 0, color: catColor(c) })) })); + const cats = ALL_CATS.filter(c => rows.some(r => r.segments.some(s => s.label === cap(c) && s.value))); + half(`

Risk domains

${cap(what)} grouped by CWE, ${CLS_MODE ? 'guideline chapter' : 'check'} and severity
+ ${chartLegend(cats.map(c => [catColor(c), cap(c)]))}${hbars(rows, { kind: 'domain' })}`); + } + + // products + if (HAS_PRODUCTS && !prod) { + const byProd = new Map(); + for (const r of D) { + if (!r.product) continue; + if (!byProd.has(r.product)) byProd.set(r.product, new Map()); + const m = byProd.get(r.product); m.set(r.cat, (m.get(r.cat) || 0) + 1); + } + const rows = PRODUCTS.filter(p => byProd.has(p)).map(p => ({ p, m: byProd.get(p), n: sumValues(Object.fromEntries(byProd.get(p))) })) + .sort((a, b) => b.n - a.n).slice(0, 14) + .map(({ p, m }) => ({ label: p, key: p, segments: ALL_CATS.map(c => ({ label: cap(c), value: m.get(c) || 0, color: catColor(c) })) })); + half(`

${cap(what)} by product

Click a product to focus the dashboard on it
+ ${chartLegend(ALL_CATS.map(c => [catColor(c), cap(c)]))}${hbars(rows, { kind: 'product' })}`); + } + + // most frequent checks / guidelines + { + const keyCat = new Map(); + D.forEach(r => { if (!keyCat.has(r.key)) keyCat.set(r.key, r.cat); }); + const counts = [...countBy(D, r => r.key).entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + const top = counts.slice(0, 12).map(([k, n]) => ({ label: k, key: k, segments: [{ label: cap(keyCat.get(k)), value: n, color: catColor(keyCat.get(k)) }] })); + const cats = [...new Set(top.map(r => keyCat.get(r.key)))].sort(catCmp); + half(`

${CLS_MODE ? 'Most violated guidelines' : 'Most frequent checks'}

Top ${top.length} of ${fmt(counts.length)} ${CLS_MODE ? 'guidelines' : 'warning ids'}
+ ${chartLegend(cats.map(c => [catColor(c), cap(c)]))}${hbars(top, { kind: CLS_MODE ? 'guideline' : 'id', labelClass: 'mono' })}`); + } + + // top files + { + const byFile = new Map(); + for (const r of D) { + if (!r.loc.file) continue; + if (!byFile.has(r.loc.file)) byFile.set(r.loc.file, new Map()); + const m = byFile.get(r.loc.file); m.set(r.cat, (m.get(r.cat) || 0) + 1); + } + const top = [...byFile.entries()].map(([f, m]) => ({ f, m, n: [...m.values()].reduce((a, b) => a + b, 0) })) + .sort((a, b) => b.n - a.n || a.f.localeCompare(b.f)).slice(0, 12) + .map(({ f, m }) => ({ label: f, key: f, segments: ALL_CATS.map(c => ({ label: cap(c), value: m.get(c) || 0, color: catColor(c) })) })); + half(`

Files with most ${what}

Top ${top.length} of ${fmt(byFile.size)} files
+ ${chartLegend(ALL_CATS.map(c => [catColor(c), cap(c)]))}${hbars(top, { kind: 'file', labelClass: 'mono path' })}`); + } + + // CWE + const cwes = [...countBy(D.filter(r => r.cwe), r => r.cwe).entries()].sort((a, b) => b[1] - a[1]).slice(0, 10); + if (cwes.length) { + half(`

Top CWE classifications

Common Weakness Enumeration
+ ${hbars(cwes.map(([c, n]) => ({ label: 'CWE-' + c, key: String(c), segments: [{ label: 'Warnings', value: n, color: 'var(--accent)' }] })), { kind: 'cwe' })}`); + } + + if (HAS_CMP && RAW.comparison.fixedList.length) { + const fl = RAW.comparison.fixedList.filter(r => !prod || r.product === prod); + if (fl.length) { + half(`

Fixed warnings

In ${esc(RAW.comparison.oldFile)} but not in this report${RAW.comparison.fixed > RAW.comparison.fixedList.length ? ` (showing ${fmt(fl.length)})` : ''}
+
` + + fl.map(r => `' + esc(r.msg) + '')}">`).join('') + + '
${CAT_NAME}${CLS_MODE ? 'Guideline' : 'Id'}Location
${catBadge(CLS_MODE ? (r.classification || 'None') : r.severity)}${esc(CLS_MODE ? (r.guideline || r.id) : r.id)}${esc(basename(r.file))}${r.line ? ':' + r.line : ''}
'); + } + } + + // 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) => `
${icon}${title}${small}
`; + const b = []; + b.push(ub.length ? badge('bad', ICON_BAD, 'Undefined behavior', `${fmt(ub.length)} ${plural(ub.length, 'warning', 'warnings')}`, 'ub') + : badge('ok', ICON_OK, 'No undefined behavior', 'No warnings indicate undefined behavior', '')); + const sf = P.filter(r => r.safety); + if (sf.length) b.push(badge('bad', ICON_BAD, 'Safety & security (MISRA / CERT)', `${fmt(sf.length)} ${plural(sf.length, 'violation', 'violations')}`, 'safety')); + else if (SAFETY_CHECKED) b.push(badge('ok', ICON_OK, 'Safety & security (MISRA / CERT)', 'No violations', '')); + else b.push(badge('', ICON_NA, 'Safety & security (MISRA / CERT)', 'Not checked in this analysis', '')); + if ((RAW.criticalErrors || []).length) b.push(badge('bad', ICON_WARN, 'Analysis incomplete', 'Critical errors: ' + esc(RAW.criticalErrors.join(', ')), '')); + return `

Executive summary

${s.join(' ')}

${b.join('')}
`; +} + +function kpiHtml(P) { + const prod = state.product; + const cur = {}; + for (const r of P) cur[r.cat] = (cur[r.cat] || 0) + 1; + const prevCats = PREV ? snapCats(PREV, prod) : null; + const nFiles = new Set(P.map(r => r.loc.file).filter(Boolean)).size; + const delta = (v, prev, foot) => { + if (prev === null || prev === undefined) return foot; + const d = v - prev; + if (!d) return `No change vs ${esc(PREV.label)}`; + return `${d > 0 ? '▲ +' : '▼ −'}${fmt(Math.abs(d))} vs ${esc(PREV.label)}`; + }; + let h = '
'; + GROUPS.forEach((g, i) => { + const v = groupCount(cur, g); + h += kpi(g.label, fmt(v), delta(v, prevCats ? groupCount(prevCats, g) : null, pct(v, P.length) + ' of all'), 'grp:' + i, g.color); + }); + h += kpi('Total warnings', fmt(P.length), delta(P.length, prevCats ? sumValues(prevCats) : null, HAS_CMP ? `${fmt(P.filter(r => r.isNew).length)} new` : `${fmt(ALL_IDS.length)} checks`), 'all', null); + h += kpi('Affected files', fmt(nFiles), delta(nFiles, PREV ? snapNum(PREV, 'files', prod) : null, 'with warnings'), 'all', null); + return h + '
'; +} + +function kpi(label, value, foot, go, color) { + return `
${color ? `` : ''}${esc(label)}
+
${value}
${foot}
`; +} + +function metricsCardHtml() { + let h = '

Metrics

'; + if (!METRICS) return h + `
${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.
+
+
Functions
${fmt(fs.length)}
+
Functions over thresholds
${fmt(bad)}${pct(bad, fs.length)}
+ ${ccj >= 0 ? `
Highest cyclomatic complexity
${fmt(maxcc)}limit ${esc(thrText('cyclomaticComplexity') || '–')}
` : ''} + ${lowCom !== null ? `
Files with low comment density
${fmt(lowCom)}of ${fmt(fl.length)}
` : ''} +
`; + const rows = []; + METRICS.fids.forEach((id, j) => { + let n = 0; + for (const f of fs) if (f.bad[j]) n++; + if (n) rows.push({ label: `${mName(id)} ${thrText(id)}`, key: id, segments: [{ label: 'Functions over threshold', value: n, color: 'var(--bad)' }] }); + }); + METRICS.lids.forEach((id, j) => { + let n = 0; + for (const f of fl) if (f.bad[j]) n++; + if (n) rows.push({ label: `${mName(id)} ${thrText(id)}`, key: id, segments: [{ label: 'Files over threshold', value: n, color: 'var(--bad)' }] }); + }); + const top = ccj < 0 ? [] : fs.slice().sort((a, b) => (b.v[ccj] || 0) - (a.v[ccj] || 0)).slice(0, 8); + h += `
Threshold violations per metric
${rows.length ? hbars(rows, { kind: 'metric' }) : '
All functions are within the thresholds
'}
`; + if (top.length) { + h += `
Most complex functions
` + + top.map(f => ``).join('') + + '
FunctionFilev(G)Over
${esc(f.name)}${esc(basename(f.file))}:${f.line}${fmt(f.v[ccj])}${fmt(f.viol)}
'; + } + return h + '
'; +} + +$('#view-dashboard').addEventListener('click', e => { + const sc = e.target.closest('[data-scope]'); + if (sc) { state.scope = sc.dataset.scope; renderDashboard(); return; } + const pr = e.target.closest('[data-product]') || e.target.closest('[data-kind="product"]'); + if (pr) { + state.product = pr.dataset.product !== undefined ? pr.dataset.product : pr.dataset.key; + renderDashboard(); + window.scrollTo({ top: 0 }); + return; + } + const fn = e.target.closest('[data-func]'); + if (fn) { const f = METRICS.funcs[+fn.dataset.func]; openInResults(f.file, f.line); return; } + const mg = e.target.closest('[data-mgo],[data-metric],[data-kind="metric"]'); + if (mg) { + mstate.onlyBad = mg.dataset.mgo === 'bad'; + mstate.metric = mg.dataset.metric || (mg.dataset.kind === 'metric' ? mg.dataset.key : ''); + mstate.mode = mstate.metric && METRICS && METRICS.lids.includes(mstate.metric) ? 'files' : 'functions'; + if (mstate.metric) { mstate.sort = mstate.metric; mstate.dir = mstate.metric === 'HISCOMF' ? 1 : -1; } + showView('metrics'); + return; + } + const t = e.target.closest('[data-cat],[data-go],[data-kind]'); + if (!t) return; + resetFilters(); + if (HAS_CMP && state.scope === 'new') state.status = 'new'; + const go = t.dataset.go || ''; + if (go === 'new' || go === 'old') state.status = go; + else if (go === 'all') { /* all warnings */ } + else if (go === 'ub' || go === 'safety') state.only = go; + else if (go.startsWith('grp:')) { const g = GROUPS[+go.slice(4)]; state.cats = new Set(ALL_CATS.filter(c => g.cats.includes(c))); } + else if (t.dataset.kind === 'id' || t.dataset.kind === 'guideline') state.hiddenIds = new Set(ID_NAMES.filter(id => id !== t.dataset.key)); + else if (t.dataset.kind === 'file') state.file = t.dataset.key; + else if (t.dataset.kind === 'cwe') state.search = 'cwe-' + t.dataset.key; + else if (t.dataset.kind === 'domain') state.domain = t.dataset.key; + else if (t.dataset.kind === 'cat') state.cats = new Set([t.dataset.key]); + else if (t.dataset.cat) state.cats = new Set([t.dataset.cat]); + $('#search').value = state.search; + state.selected = -1; + listScrollTop = 0; + showView('results'); +}); + +function resetFilters() { + // the product is a global filter, it is kept + state.cats = new Set(ALL_CATS); + state.hiddenIds = new Set(); + state.status = 'all'; + state.inconclusive = true; + state.search = ''; + state.file = ''; + state.domain = ''; + state.only = ''; +} + +// ---------------------------------------------------------------- filtering +function matches(r, ignore) { + if (ignore !== 'cat' && !state.cats.has(r.cat)) return false; + if (ignore !== 'id' && state.hiddenIds.has(r.key)) return false; + if (ignore !== 'status') { + if (state.status === 'new' && !r.isNew) return false; + if (state.status === 'old' && r.isNew) return false; + } + if (!state.inconclusive && r.inconclusive) return false; + if (state.file && r.loc.file !== state.file) return false; + if (ignore !== 'product' && state.product && r.product !== state.product) return false; + if (state.domain && r.domain !== state.domain) return false; + if (state.only === 'ub' && !r.ub) return false; + if (state.only === 'safety' && !r.safety) return false; + if (state.search && !r.hay.includes(state.search.toLowerCase())) return false; + return true; +} + +function sorted(list) { + const byLoc = (a, b) => (a.loc.file < b.loc.file ? -1 : a.loc.file > b.loc.file ? 1 : 0) || a.loc.line - b.loc.line || a.loc.column - b.loc.column; + const byCat = (a, b) => a.catRank - b.catRank || (a.cat < b.cat ? -1 : a.cat > b.cat ? 1 : 0); + const cmp = { + category: (a, b) => byCat(a, b) || byLoc(a, b), + file: (a, b) => byLoc(a, b) || byCat(a, b), + id: (a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }) || byLoc(a, b), + new: (a, b) => (b.isNew - a.isNew) || byCat(a, b) || byLoc(a, b), + }[state.sort]; + return list.sort(cmp); +} + +let visible = []; + +// ---------------------------------------------------------------- results view +function renderResults() { + renderFilters(); + renderList(); + renderTabs(); + if (!activeTab) showCode(null); +} + +function rerender() { + const idScroll = $('#id-list') ? $('#id-list').scrollTop : 0; + const fScroll = $('#filters').scrollTop; + renderFilters(); + $('#id-list').scrollTop = idScroll; + $('#filters').scrollTop = fScroll; + renderList(); + refreshMarks(); +} + +function renderFilters() { + const el = $('#filters'); + let h = ''; + + if (HAS_PRODUCTS) { + const pc = countBy(RESULTS.filter(r => matches(r, 'product')), r => r.product); + h += `
Product
'; + } + + if (HAS_CMP) { + let n = 0, o = 0; + for (const r of RESULTS) if (matches(r, 'status')) { if (r.isNew) n++; else o++; } + h += `
Status
+ + +
`; + } + + const catCounts = new Map(); + for (const r of RESULTS) if (matches(r, 'cat')) catCounts.set(r.cat, (catCounts.get(r.cat) || 0) + 1); + const links = ''; + const catToggle = c => ``; + if (CLS_MODE) { + const misra = ['Mandatory', 'Required', 'Advisory', 'Document', 'Disapplied'], cert = ['L1', 'L2', 'L3']; + const other = ALL_CATS.filter(c => !misra.includes(c) && !cert.includes(c)); + $('#cls-bar').innerHTML = `
${CAT_NAME}${links}
` + + [misra, cert, other].filter(x => x.length).map(x => x.map(catToggle).join('')).join(''); + } else { + h += `
${CAT_NAME}${links}
${ALL_CATS.map(catToggle).join('')}
`; + } + + if (RESULTS.some(r => r.inconclusive)) { + h += `
Options
+
`; + } + + h += `
${KEY_NAME}
+
`; + el.innerHTML = h; + + const idCounts = new Map(); + for (const r of RESULTS) if (matches(r, 'id')) idCounts.set(r.key, (idCounts.get(r.key) || 0) + 1); + renderIdList(idCounts); + const idSearch = $('#id-search'); + idSearch.oninput = () => { state.idSearch = idSearch.value; renderIdList(idCounts); }; +} + +function renderIdList(idCounts) { + const q = state.idSearch.toLowerCase(); + $('#id-list').innerHTML = ID_NAMES.filter(id => !q || id.toLowerCase().includes(q)).map(id => + ``).join('') + || `
No matching ${KEY_NAME.toLowerCase()}
`; +} + +function onFilterClick(e) { + const b = e.target.closest('button'); + if (!b) return; + const only = e.target.closest('.only'); + if (b.dataset.status) state.status = b.dataset.status; + else if (b.dataset.cat) { + const c = b.dataset.cat; + if (only) state.cats = new Set([c]); + else if (state.cats.has(c)) state.cats.delete(c); else state.cats.add(c); + } else if (b.dataset.id) { + const id = b.dataset.id; + if (only) state.hiddenIds = new Set(ID_NAMES.filter(x => x !== id)); + else if (state.hiddenIds.has(id)) state.hiddenIds.delete(id); else state.hiddenIds.add(id); + } else if (b.dataset.act === 'cat-all') state.cats = new Set(ALL_CATS); + else if (b.dataset.act === 'cat-none') state.cats = new Set(); + else if (b.dataset.act === 'id-all') state.hiddenIds = new Set(); + else if (b.dataset.act === 'id-none') state.hiddenIds = new Set(ID_NAMES); + else if (b.dataset.act === 'inconclusive') state.inconclusive = !state.inconclusive; + else return; + listScrollTop = 0; + rerender(); +} +$('#filters').addEventListener('click', onFilterClick); +$('#cls-bar').addEventListener('click', onFilterClick); +if (CLS_MODE) { + $('#view-results').classList.add('cls'); + $('#cls-bar').hidden = false; + $('#list-head').hidden = false; + $('#list-head').innerHTML = [['category', 'Classification'], ['id', 'Guideline'], ['file', 'Warning']].map(([k, l]) => ``).join(''); + $('#list-head').addEventListener('click', e => { + const b = e.target.closest('[data-sort]'); + if (!b) return; + state.sort = $('#sort').value = b.dataset.sort; + renderList(); + }); +} +$('#filters').addEventListener('change', e => { + if (e.target.id !== 'product-select') return; + state.product = e.target.value; + listScrollTop = 0; + rerender(); +}); + +function highlight(text) { + if (!state.search) return esc(text); + const q = state.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return String(text).split(new RegExp('(' + q + ')', 'gi')).map((part, i) => i % 2 ? `${esc(part)}` : esc(part)).join(''); +} + +// ---- virtual list: only the visible rows are in the DOM +const ITEM_H = 74; +const listEl = $('#result-list'); +const spacer = $('#vspacer'); +let listScrollTop = 0; +let renderedRange = ''; + +function renderList() { + visible = sorted(RESULTS.filter(r => matches(r))); + if (CLS_MODE) document.querySelectorAll('#list-head button').forEach(b => b.classList.toggle('active', b.dataset.sort === state.sort)); + const n = visible.length; + $('#nav-count').textContent = fmt(n); + + const chips = []; + if (state.product) chips.push(['product', 'Product: ' + state.product]); + if (state.only) chips.push(['only', state.only === 'ub' ? 'Undefined behavior' : 'MISRA / CERT']); + if (state.domain) chips.push(['domain', 'Risk domain: ' + state.domain]); + if (state.file) chips.push(['file', 'File: ' + state.file]); + if (state.cats.size !== ALL_CATS.length) chips.push(['cat', CAT_NAME + ': ' + ([...state.cats].sort(catCmp).join(', ') || 'none')]); + if (state.hiddenIds.size) { + const shown = ID_NAMES.length - state.hiddenIds.size; + chips.push(['id', shown === 1 ? (CLS_MODE ? 'Guideline: ' : 'Id: ') + ID_NAMES.find(x => !state.hiddenIds.has(x)) : `${KEY_NAME}: ${shown} of ${ID_NAMES.length}`]); + } + if (state.status !== 'all') chips.push(['status', state.status === 'new' ? 'New only' : 'Old only']); + if (!state.inconclusive) chips.push(['inconclusive', 'Inconclusive hidden']); + $('#active-filters').innerHTML = chips.map(([k, l]) => `${esc(l)}`).join('') + + (chips.length > 1 ? '' : ''); + + const nNew = HAS_CMP ? visible.filter(r => r.isNew).length : 0; + $('#list-summary').textContent = `${fmt(n)} of ${fmt(RESULTS.length)} warnings` + (HAS_CMP ? ` · ${fmt(nNew)} new` : ''); + + spacer.style.height = (n ? n * ITEM_H + 16 : 0) + 'px'; + listEl.scrollTop = listScrollTop; + renderedRange = ''; + if (!n) { + spacer.innerHTML = `
No warnings match the current filters
`; + spacer.style.height = 'auto'; + return; + } + renderVisible(); +} + +function renderVisible(force) { + const top = listEl.scrollTop, hgt = listEl.clientHeight || 800; + const start = Math.max(0, Math.floor(top / ITEM_H) - 10); + const end = Math.min(visible.length, Math.ceil((top + hgt) / ITEM_H) + 10); + const range = start + ':' + end; + if (!force && range === renderedRange) return; + renderedRange = range; + let h = ''; + for (let i = start; i < end; i++) h += itemHtml(visible[i], i); + spacer.innerHTML = h; +} + +listEl.addEventListener('scroll', () => { + listScrollTop = listEl.scrollTop; + requestAnimationFrame(() => renderVisible()); +}, { passive: true }); +window.addEventListener('resize', () => { if (state.view === 'results') renderVisible(true); }); + +function itemHtml(r, i) { + const where = r.loc.file ? `${r.loc.file}:${r.loc.line}${r.loc.column ? ':' + r.loc.column : ''}` : 'no location'; + const pills = (r.isNew ? 'New' : '') + (r.inconclusive ? 'Inconclusive' : ''); + const id = `${highlight(r.id)}`; + const text = `
${highlight(r.msg)}
${highlight(where)}
`; + return `'; +} + +$('#active-filters').addEventListener('click', e => { + const b = e.target.closest('[data-clear]'); + if (!b) return; + const k = b.dataset.clear; + if (k === 'file') state.file = ''; + if (k === 'product') state.product = ''; + if (k === 'only') state.only = ''; + if (k === 'domain') state.domain = ''; + if (k === 'cat') state.cats = new Set(ALL_CATS); + if (k === 'id') state.hiddenIds = new Set(); + if (k === 'status') state.status = 'all'; + if (k === 'inconclusive') state.inconclusive = true; + if (k === 'all') { resetFilters(); state.product = ''; $('#search').value = ''; } + rerender(); +}); + +listEl.addEventListener('click', e => { + const it = e.target.closest('.item'); + if (it) select(+it.dataset.idx); +}); + +listEl.addEventListener('keydown', e => { + const down = e.key === 'ArrowDown' || e.key === 'j', up = e.key === 'ArrowUp' || e.key === 'k'; + if (!down && !up) return; + e.preventDefault(); + if (!visible.length) return; + let i = visible.findIndex(r => r.idx === state.selected); + i = down ? Math.min(i + 1, visible.length - 1) : Math.max(i - 1, 0); + const y = 8 + i * ITEM_H; + if (y < listEl.scrollTop) listEl.scrollTop = y - 8; + else if (y + ITEM_H > listEl.scrollTop + listEl.clientHeight) listEl.scrollTop = y + ITEM_H - listEl.clientHeight + 8; + select(visible[i].idx); +}); + +let searchTimer = 0; +$('#search').addEventListener('input', e => { + clearTimeout(searchTimer); + searchTimer = setTimeout(() => { state.search = e.target.value.trim(); listScrollTop = 0; rerender(); }, 150); +}); +$('#sort').addEventListener('change', e => { state.sort = e.target.value; renderList(); }); + +// ---------------------------------------------------------------- source loading +const sourceText = new Map(); // file -> text +const sourceWaiters = new Map(); // index -> [callbacks] +window.CPPCHECK_SOURCE = function (n, text) { + const cbs = sourceWaiters.get(n) || []; + sourceWaiters.delete(n); + cbs.forEach(cb => cb(text)); +}; +function loadSource(file, cb) { + if (sourceText.has(file)) { cb(sourceText.get(file)); return; } + const n = RAW.sources[file]; + if (n === undefined) { cb(null); return; } + const first = !sourceWaiters.has(n); + if (first) sourceWaiters.set(n, []); + sourceWaiters.get(n).push(text => { sourceText.set(file, text); cb(text); }); + if (first) { + const s = document.createElement('script'); + s.src = 'data/src/' + n + '.js'; + s.onload = () => s.remove(); + s.onerror = () => { s.remove(); const cbs = sourceWaiters.get(n) || []; sourceWaiters.delete(n); cbs.forEach(f => f(null)); }; + document.head.appendChild(s); + } +} + +// ---------------------------------------------------------------- code tabs +const tabs = []; +let activeTab = null; +const views = new Map(); // file -> code view +const codeEl = $('#code'); + +function select(idx) { + state.selected = idx; + spacer.querySelectorAll('.item.selected').forEach(el => el.classList.remove('selected')); + const el = spacer.querySelector(`.item[data-idx="${idx}"]`); + if (el) el.classList.add('selected'); + const r = RESULTS[idx]; + renderDetail(r); + if (r.loc.file) openFile(r.loc.file, r.loc.line); + else { activeTab = null; renderTabs(); showCode(null); } +} + +function renderDetail(r) { + const d = $('#detail'); + if (!r) { d.innerHTML = ''; return; } + const meta = []; + if (CLS_MODE) meta.push('Severity: ' + esc(r.severity)); + if (r.cwe) meta.push(`CWE-${r.cwe}`); + if (r.file0 && r.file0 !== r.loc.file) meta.push('Analyzed: ' + esc(r.file0)); + if (r.hash) meta.push('Hash: ' + esc(r.hash)); + if (r.remark) meta.push('Remark: ' + esc(r.remark)); + let locs = ''; + if (r.locations.length > 1 || (r.locations.length && r.locations[0].info)) { + locs = '
    ' + r.locations.map((l, i) => + `
  • ${i + 1}${esc(basename(l.file))}:${l.line}${esc(l.info || (i === 0 ? r.msg : ''))}
  • `).join('') + '
'; + } + d.innerHTML = `
${catBadge(r.cat)}${r.guideline ? `${esc(r.guideline)}` : ''}${r.isNew ? 'New' : ''}${r.inconclusive ? 'Inconclusive' : ''}${esc(r.id)}
+

${esc(r.msg)}

${r.verbose && r.verbose !== r.msg ? `

${esc(r.verbose.replace(/\\012/g, '\n'))}

` : ''} +
${meta.map(m => `${m}`).join('')}
${locs}`; + d.querySelectorAll('.locs li').forEach(li => li.addEventListener('click', () => { if (li.dataset.file) openFile(li.dataset.file, +li.dataset.line); })); +} + +function openFile(file, line) { + if (!tabs.includes(file)) tabs.push(file); + const same = activeTab === file && views.has(file) && codeEl.firstChild === views.get(file).root; + activeTab = file; + renderTabs(); + if (same) { annotate(views.get(file)); if (line) scrollToLine(views.get(file), line, true); return; } + showCode(file, line); +} + +function renderTabs() { + const t = $('#tabs'); + if (!tabs.length) { t.innerHTML = '
Select a warning to view its code
'; return; } + t.innerHTML = tabs.map(f => ``).join(''); + const act = t.querySelector('.tab.active'); + if (act) act.scrollIntoView({ block: 'nearest', inline: 'nearest' }); +} + +$('#tabs').addEventListener('click', e => { + const b = e.target.closest('.tab'); + if (!b) return; + const f = b.dataset.file; + if (e.target.closest('[data-close]')) { + const i = tabs.indexOf(f); + tabs.splice(i, 1); + views.delete(f); + if (activeTab === f) { activeTab = tabs[Math.min(i, tabs.length - 1)] || null; showCode(activeTab); } + renderTabs(); + return; + } + if (f === activeTab) return; + activeTab = f; + renderTabs(); + showCode(f); +}); +$('#tabs').addEventListener('auxclick', e => { + const b = e.target.closest('.tab'); + if (b && e.button === 1) b.querySelector('[data-close]').click(); +}); + +function placeholder(icon, html) { + codeEl.innerHTML = `
${html}
`; +} + +function showCode(file, line) { + codeEl.textContent = ''; + if (!file) { + placeholder('M17 14l-10 10 10 10M31 14l10 10-10 10M27 10l-6 28', '
Select a warning to view the related code
Tip: use ↑ / ↓ in the list to move between warnings
'); + return; + } + if (views.has(file)) { + const v = views.get(file); + codeEl.appendChild(v.root); + codeEl.scrollTop = v.scrollTop || 0; + refreshMarks(); + if (line) scrollToLine(v, line, false); + return; + } + placeholder('M24 8a16 16 0 1 0 16 16', '
Loading…
'); + loadSource(file, text => { + if (activeTab !== file) return; + if (text === null) { + placeholder('M12 6h17l9 9v27H12z M29 6v9h9 M19 27l10 8 M29 27l-10 8', + `
Source code is not available
${esc(file)}
Generate the report with --source-dir pointing at the source tree
`); + return; + } + const v = buildView(file, text); + views.set(file, v); + codeEl.textContent = ''; + codeEl.appendChild(v.root); + refreshMarks(); + scrollToLine(v, line || 1, false); + }); +} + +codeEl.addEventListener('scroll', () => { const v = activeTab && views.get(activeTab); if (v) v.scrollTop = codeEl.scrollTop; }, { passive: true }); + +// ---- code view: lines are rendered in chunks when they are scrolled into view +const LINE_H = 20, CHUNK = 250; +const chunkObserver = new IntersectionObserver(entries => { + for (const e of entries) if (e.isIntersecting) renderChunk(e.target._view, e.target._chunk); +}, { root: codeEl, rootMargin: '1200px 0px' }); + +function buildView(file, text) { + const lines = text.split('\n'); + if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop(); + const root = document.createElement('div'); + root.className = 'code-inner'; + const v = { file, lines, root, chunks: [], lineEls: new Array(lines.length), marks: new Map(), annos: [], hls: [], scrollTop: 0 }; + // block comment state at the start of each chunk + let block = false; + for (let c = 0; c * CHUNK < lines.length; c++) { + const start = c * CHUNK, end = Math.min(lines.length, start + CHUNK); + const el = document.createElement('div'); + el.style.height = ((end - start) * LINE_H) + 'px'; + el._view = v; el._chunk = c; + v.chunks.push({ start, end, el, block, rendered: false }); + root.appendChild(el); + chunkObserver.observe(el); + for (let i = start; i < end; i++) block = scanBlock(lines[i], block); + } + return v; +} + +function renderChunk(v, c) { + const ch = v.chunks[c]; + if (ch.rendered) return; + ch.rendered = true; + chunkObserver.unobserve(ch.el); + const st = { block: ch.block }; + let h = ''; + for (let i = ch.start; i < ch.end; i++) + h += `
${i + 1}${hl(v.lines[i], st) || ' '}
`; + ch.el.innerHTML = h; + ch.el.style.height = ''; + for (let i = ch.start, k = 0; i < ch.end; i++, k++) v.lineEls[i] = ch.el.children[k]; + for (let i = ch.start; i < ch.end; i++) if (v.marks.has(i + 1)) addMark(v, i + 1); +} + +function lineEl(v, n) { + if (n < 1 || n > v.lines.length) return null; + renderChunk(v, Math.floor((n - 1) / CHUNK)); + return v.lineEls[n - 1]; +} + +function scrollToLine(v, line, smooth) { + const el = lineEl(v, line); + if (!el) return; + annotate(v); + const top = el.offsetTop - codeEl.clientHeight / 3; + codeEl.scrollTo({ top: Math.max(0, top), behavior: smooth ? 'smooth' : 'auto' }); +} + +// gutter markers for visible warnings in the current file +function refreshMarks() { + const v = activeTab && views.get(activeTab); + if (!v) return; + v.root.querySelectorAll('.m i').forEach(i => i.remove()); + v.marks = new Map(); + for (const r of RESULTS) { + if (r.loc.file !== v.file || !matches(r)) continue; + const list = v.marks.get(r.loc.line); + if (list) list.push(r); else v.marks.set(r.loc.line, [r]); + } + for (const line of v.marks.keys()) if (v.lineEls[line - 1]) addMark(v, line); + annotate(v); +} + +function addMark(v, line) { + const rs = v.marks.get(line).slice().sort((a, b) => a.catRank - b.catRank); + const i = document.createElement('i'); + i.style.setProperty('--c', catColor(rs[0].cat)); + i.dataset.idx = rs[0].idx; + i.dataset.tip = tipHtml(`Line ${line}`, rs.slice(0, 8).map(r => [catColor(r.cat), CLS_MODE && r.guideline ? r.guideline : r.id, r.cat])); + v.lineEls[line - 1].querySelector('.m').appendChild(i); +} + +// highlight the lines of the selected warning and show its messages in the code +function annotate(v) { + v.annos.forEach(a => a.remove()); + v.hls.forEach(l => l.classList.remove('hl', 'primary')); + v.annos = []; v.hls = []; + const r = RESULTS[state.selected]; + if (!r) return; + const many = r.locations.length > 1; + r.locations.forEach((l, i) => { + if (l.file !== v.file) return; + const el = lineEl(v, l.line); + if (!el) return; + el.classList.add(i === 0 ? 'primary' : 'hl'); + v.hls.push(el); + const text = l.info || (i === 0 ? r.msg : ''); + if (!text) return; + const a = document.createElement('div'); + a.className = 'anno'; + a.style.setProperty('--c', catColor(r.cat)); + a.innerHTML = (many ? `${i + 1}` : '') + `${esc(text)}${l.column ? ` (col ${l.column})` : ''}`; + el.after(a); + v.annos.push(a); + }); +} + +codeEl.addEventListener('click', e => { + const i = e.target.closest('.m i'); + if (i) select(+i.dataset.idx); +}); + +// ---------------------------------------------------------------- syntax highlighting (C/C++) +const KW = new Set(('alignas alignof and asm auto break case catch class co_await co_return co_yield concept const consteval constexpr constinit const_cast continue ' + + 'decltype default delete do dynamic_cast else enum explicit export extern false final for friend goto if inline mutable namespace new noexcept not nullptr ' + + 'operator or override private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this ' + + 'thread_local throw true try typedef typeid typename union using virtual volatile while NULL').split(' ')); +const TY = new Set(('bool char char8_t char16_t char32_t double float int long short signed unsigned void wchar_t size_t ssize_t ptrdiff_t ' + + 'int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t intptr_t uintptr_t std string vector map set list FILE').split(' ')); +const TOK = /(\/\/.*$)|(\/\*)|("(?:\\.|[^"\\])*"?)|('(?:\\.|[^'\\])*'?)|(\b\d[\w.']*|\.\d[\w']*)|([A-Za-z_]\w*)(\s*\()?|([^\w\s"'\/]+|\/|\s+)/y; + +// returns true if the line ends inside a block comment +function scanBlock(line, block) { + let i = 0; + const n = line.length; + while (i < n) { + if (block) { + const e = line.indexOf('*/', i); + if (e < 0) return true; + block = false; i = e + 2; + continue; + } + const c = line.charCodeAt(i); + if (c === 47 /* / */) { + const d = line.charCodeAt(i + 1); + if (d === 47) return false; + if (d === 42) { block = true; i += 2; continue; } + } else if (c === 34 || c === 39) { + i++; + while (i < n && line.charCodeAt(i) !== c) i += line.charCodeAt(i) === 92 ? 2 : 1; + } + i++; + } + return block; +} + +function hl(line, st) { + if (line.length > 3000) return esc(line); + let out = '', pos = 0; + if (st.block) { + const e = line.indexOf('*/'); + if (e < 0) return `${esc(line)}`; + out += `${esc(line.slice(0, e + 2))}`; + pos = e + 2; st.block = false; + } + if (pos === 0 && /^\s*#/.test(line)) { + const m = /^(\s*#\s*\w*)(.*)$/.exec(line); + out += `${esc(m[1])}`; + const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(m[2]); + if (inc) return out + esc(inc[1]) + `${esc(inc[2])}` + hlRest(inc[3], st); + return out + hlRest(m[2], st); + } + return out + hlRest(line.slice(pos), st); +} + +function hlRest(s, st) { + let out = ''; + TOK.lastIndex = 0; + while (TOK.lastIndex < s.length) { + const start = TOK.lastIndex; + const m = TOK.exec(s); + if (!m) { out += esc(s.slice(start)); break; } + if (m[1]) out += `${esc(m[1])}`; + else if (m[2]) { + const e = s.indexOf('*/', TOK.lastIndex); + if (e < 0) { out += `${esc(s.slice(start))}`; st.block = true; break; } + out += `${esc(s.slice(start, e + 2))}`; + TOK.lastIndex = e + 2; + } else if (m[3] || m[4]) out += `${esc(m[3] || m[4])}`; + else if (m[5]) out += `${esc(m[5])}`; + else if (m[6]) { + const w = m[6]; + if (KW.has(w)) out += `${w}`; + else if (TY.has(w)) out += `${w}`; + else if (m[7]) out += `${w}`; + else out += w; + if (m[7]) out += esc(m[7]); + } else out += esc(m[8]); + } + return out; +} + +// ---------------------------------------------------------------- metrics +const METRIC_INFO = { + cyclomaticComplexity: ['v(G)', 'Cyclomatic complexity'], + HISStmt: ['STMT', 'Statements'], + HISPath: ['PATH', 'Execution paths'], + HISLevel: ['LEVEL', 'Nesting depth'], + HISCall: ['CALLS', 'Called functions'], + HISCalling: ['CALLING', 'Calling functions'], + HISParam: ['PARAM', 'Parameters'], + HISReturn: ['RETURN', 'Return points'], + HISGoto: ['GOTO', 'Goto statements'], + HISVOCF: ['VOCF', 'Language scope'], + HISStmtFile: ['STMT', 'Statements in file'], + HISComment: ['COMMENTS', 'Comments'], + HISCOMF: ['COMF %', 'Comment density'], +}; +const mShort = id => (METRIC_INFO[id] || [id])[0]; +const mName = id => (METRIC_INFO[id] || [id, id])[1]; + +// thresholds: defaults from the report, can be changed in the report (saved in localStorage) +const THR_KEY = 'cppcheck-report-thresholds'; +const THR_BASE = JSON.stringify(RAW.thresholds || {}); +let THRESH = JSON.parse(THR_BASE); +try { + const saved = JSON.parse(localStorage.getItem(THR_KEY) || 'null'); + if (saved && saved.base === THR_BASE && saved.t) THRESH = saved.t; +} catch (e) { /* ignore */ } +let thrVersion = 0; +const isBad = (id, v) => { + const t = THRESH[id]; + if (!t || v === null || v === undefined) return false; + return (t.max !== undefined && t.max !== null && v > t.max) || (t.min !== undefined && t.min !== null && v < t.min); +}; +const thrText = id => { + const t = THRESH[id]; + if (!t) return ''; + const p = []; + if (t.min !== undefined && t.min !== null) p.push('≥ ' + t.min); + if (t.max !== undefined && t.max !== null) p.push('≤ ' + t.max); + return p.join(', '); +}; + +let METRICS = null, metricsError = false; +window.CPPCHECK_METRICS = function (m) { + const files = m.files || []; + METRICS = { + fids: m.functionIds || [], + lids: m.fileIds || [], + funcs: (m.functions || []).map((row, i) => ({ idx: i, file: files[row[0]], name: row[1], line: row[2], v: row.slice(3), product: PRODUCT_OF[files[row[0]]] || '' })), + fileRows: m.fileRows || [], + files, + }; + computeViolations(); + if (state.view === 'metrics') renderMetrics(); + else if (state.view === 'dashboard') renderDashboard(); +}; +function loadMetrics() { + if (!RAW.metrics) return; + const s = document.createElement('script'); + s.src = 'data/metrics.js'; + s.onload = () => s.remove(); + s.onerror = () => { s.remove(); metricsError = true; if (state.view === 'dashboard') renderDashboard(); else if (state.view === 'metrics') renderMetrics(); }; + document.head.appendChild(s); +} + +function computeViolations() { + const { fids, lids } = METRICS; + const ccj = fids.indexOf('cyclomaticComplexity'); + const byFile = new Map(); + const fileEntry = f => { + if (!byFile.has(f)) byFile.set(f, { file: f, product: PRODUCT_OF[f] || '', n: 0, nviol: 0, maxcc: null, v: lids.map(() => null) }); + return byFile.get(f); + }; + for (const f of METRICS.funcs) { + f.bad = fids.map((id, j) => isBad(id, f.v[j])); + f.viol = f.bad.reduce((a, b) => a + b, 0); + const e = fileEntry(f.file); + e.n++; + if (f.viol) e.nviol++; + if (ccj >= 0 && f.v[ccj] !== null && (e.maxcc === null || f.v[ccj] > e.maxcc)) e.maxcc = f.v[ccj]; + } + for (const row of METRICS.fileRows) fileEntry(METRICS.files[row[0]]).v = row.slice(1); + METRICS.fileList = [...byFile.values()].sort((a, b) => a.file.localeCompare(b.file)); + for (const e of METRICS.fileList) { + e.bad = lids.map((id, j) => isBad(id, e.v[j])); + e.viol = e.bad.reduce((a, b) => a + b, 0); + } + thrVersion++; +} +const metricFuncs = () => state.product ? METRICS.funcs.filter(f => f.product === state.product) : METRICS.funcs; +const metricFiles = () => state.product ? METRICS.fileList.filter(f => f.product === state.product) : METRICS.fileList; + +const mstate = { mode: 'functions', sort: 'viol', dir: -1, search: '', onlyBad: false, metric: '', showThr: false, scrollTop: 0 }; +const M_ROW_H = 32, M_HEAD_H = 36; +let mRows = [], mCols = [], mRange = ''; + +function openInResults(file, line) { + state.selected = -1; + showView('results'); + renderDetail(null); + openFile(file, line); +} + +function buildMetricsView() { + const el = $('#view-metrics'); + el.innerHTML = `
+
+ + + ${HAS_PRODUCTS ? '' : ''} + +
+
+ +
+
`; + el.dataset.built = '1'; + $('#m-mode').addEventListener('click', e => { + const b = e.target.closest('[data-mode]'); + if (!b || b.dataset.mode === mstate.mode) return; + mstate.mode = b.dataset.mode; + mstate.sort = mstate.mode === 'files' ? 'nviol' : 'viol'; mstate.dir = -1; mstate.scrollTop = 0; + if (mstate.metric && !(mstate.mode === 'files' ? METRICS.lids : METRICS.fids).includes(mstate.metric)) mstate.metric = ''; + renderMetrics(); + }); + let timer = 0; + $('#m-search').addEventListener('input', e => { + clearTimeout(timer); + timer = setTimeout(() => { mstate.search = e.target.value.trim().toLowerCase(); mstate.scrollTop = 0; renderMetrics(); }, 120); + }); + $('#m-onlybad').addEventListener('click', () => { mstate.onlyBad = !mstate.onlyBad; mstate.scrollTop = 0; renderMetrics(); }); + if (HAS_PRODUCTS) $('#m-product').addEventListener('change', e => { state.product = e.target.value; mstate.scrollTop = 0; renderMetrics(); }); + $('#m-thr-btn').addEventListener('click', () => { mstate.showThr = !mstate.showThr; renderThresholds(); }); + $('#m-chips').addEventListener('click', e => { + const b = e.target.closest('[data-clear]'); + if (!b) return; + if (b.dataset.clear === 'metric') mstate.metric = ''; + if (b.dataset.clear === 'product') state.product = ''; + renderMetrics(); + }); + $('#m-head').addEventListener('click', e => { + const c = e.target.closest('[data-sort]'); + if (!c) return; + const k = c.dataset.sort; + if (mstate.sort === k) mstate.dir = -mstate.dir; + else { mstate.sort = k; mstate.dir = c.classList.contains('num') ? -1 : 1; } + renderMTable(); + }); + const table = $('#m-table'); + table.addEventListener('scroll', () => { mstate.scrollTop = table.scrollTop; requestAnimationFrame(() => renderMRows()); }, { passive: true }); + $('#m-rows').addEventListener('click', e => { + const row = e.target.closest('.m-row'); + if (!row) return; + const r = mRows[+row.dataset.i]; + openInResults(r.file, r.line || 1); + }); + $('#m-thr').addEventListener('click', e => { + const b = e.target.closest('[data-thr]'); + if (!b) return; + if (b.dataset.thr === 'apply') { + const t = {}; + $('#m-thr').querySelectorAll('.thr-row[data-id]').forEach(row => { + const v = {}; + for (const k of ['min', 'max']) { + const s = row.querySelector(`[data-b="${k}"]`).value.trim(); + if (s !== '' && !isNaN(+s)) v[k] = +s; + } + if (Object.keys(v).length) t[row.dataset.id] = v; + }); + THRESH = t; + try { localStorage.setItem(THR_KEY, JSON.stringify({ base: THR_BASE, t })); } catch (err) { /* ignore */ } + } else if (b.dataset.thr === 'reset') { + THRESH = JSON.parse(THR_BASE); + try { localStorage.removeItem(THR_KEY); } catch (err) { /* ignore */ } + } else return; + computeViolations(); + renderThresholds(); + renderMetrics(); + }); + window.addEventListener('resize', () => { if (state.view === 'metrics') renderMRows(true); }); +} + +function renderThresholds() { + const el = $('#m-thr'); + el.hidden = !mstate.showThr; + $('#m-thr-btn').classList.toggle('primary', mstate.showThr); + if (!mstate.showThr) return; + const ids = METRICS.fids.concat(METRICS.lids.filter(id => !METRICS.fids.includes(id))); + const val = (id, k) => THRESH[id] && THRESH[id][k] !== undefined && THRESH[id][k] !== null ? THRESH[id][k] : ''; + const head = '
MetricMinMax
'; + el.innerHTML = `
${head}${ids.length > 1 ? head : ''}` + + ids.map(id => `
${esc(mName(id))} (${esc(mShort(id))}) + +
`).join('') + + `
+ A value is over the threshold when it is below Min or above Max. Changes are saved in this browser.
`; +} + +function renderMetrics() { + const el = $('#view-metrics'); + if (!METRICS) { + el.dataset.built = ''; + el.innerHTML = `
${metricsError ? 'Failed to load data/metrics.js. Keep the report files together in one folder.' : 'Loading metrics…'}
`; + return; + } + if (!el.dataset.built) buildMetricsView(); + document.querySelectorAll('#m-mode button').forEach(b => b.classList.toggle('active', b.dataset.mode === mstate.mode)); + $('#m-onlybad').classList.toggle('on', mstate.onlyBad); + if ($('#m-search').value.trim().toLowerCase() !== mstate.search) $('#m-search').value = mstate.search; + if (HAS_PRODUCTS) { + $('#m-product').innerHTML = '' + PRODUCTS.map(p => ``).join(''); + } + const chips = []; + if (mstate.metric) chips.push(['metric', `Over threshold: ${mName(mstate.metric)} (${thrText(mstate.metric)})`]); + if (state.product && !HAS_PRODUCTS) chips.push(['product', 'Product: ' + state.product]); + $('#m-chips').innerHTML = chips.map(([k, l]) => `${esc(l)}`).join(''); + renderThresholds(); + renderMTable(); +} + +function renderMTable() { + const files = mstate.mode === 'files'; + const { fids, lids } = METRICS; + const num = (key, label, title, w) => ({ key, label, title, num: true, w: w || '82px' }); + if (files) { + mCols = [{ key: 'file', label: 'File', w: 'minmax(260px, 3fr)' }] + .concat(HAS_PRODUCTS ? [{ key: 'product', label: 'Product', w: 'minmax(110px, 1fr)' }] : []) + .concat([num('n', 'Functions', 'Number of functions', '90px'), num('nviol', 'Over', 'Functions over one or more thresholds', '70px'), + num('maxcc', 'Max v(G)', 'Highest cyclomatic complexity in the file', '90px')]) + .concat(lids.map((id, j) => num('m' + j, mShort(id), `${mName(id)} ${thrText(id)}`, '96px'))); + } else { + mCols = [{ key: 'name', label: 'Function', w: 'minmax(180px, 2fr)' }, { key: 'file', label: 'File', w: 'minmax(220px, 2fr)' }, + num('viol', 'Over', 'Number of metrics over the threshold', '64px')] + .concat(fids.map((id, j) => num('m' + j, mShort(id), `${mName(id)} ${thrText(id)}`))); + } + // filter + let list = files ? metricFiles() : metricFuncs(); + const mj = mstate.metric ? (files ? lids : fids).indexOf(mstate.metric) : -1; + const q = mstate.search; + list = list.filter(r => { + if (mstate.onlyBad && !(files ? r.nviol || r.viol : r.viol)) return false; + if (mj >= 0 && !r.bad[mj]) return false; + if (q && !(r.file.toLowerCase().includes(q) || (r.name && r.name.toLowerCase().includes(q)))) return false; + return true; + }); + // sort + const k = mstate.sort, dir = mstate.dir; + const get = k[0] === 'm' && /^m\d+$/.test(k) ? (r => r.v[+k.slice(1)]) : (r => r[k]); + const sortKnown = mCols.some(c => c.key === k) || /^m\d+$/.test(k); + if (!sortKnown && (fids.includes(k) || lids.includes(k))) { + // sort key given as metric id (from the dashboard) + mstate.sort = 'm' + (files ? lids : fids).indexOf(k); + return renderMTable(); + } + list = list.slice().sort((a, b) => { + let x = get(a), y = get(b); + if (x === null || x === undefined) return 1; + if (y === null || y === undefined) return -1; + let c = typeof x === 'string' ? x.localeCompare(y) : x - y; + if (!c && !files) c = (b.viol - a.viol) || a.file.localeCompare(b.file) || a.line - b.line; + return dir * c || a.file.localeCompare(b.file); + }); + mRows = list; + + const tmpl = mCols.map(c => c.w).join(' '); + const minW = mCols.reduce((a, c) => a + (parseInt(c.w.replace('minmax(', ''), 10) || 80), 0); + const inner = $('#m-inner'); + inner.style.minWidth = minW + 'px'; + inner.style.height = (M_HEAD_H + list.length * M_ROW_H) + 'px'; + inner.style.setProperty('--m-cols', tmpl); + const head = $('#m-head'); + head.style.gridTemplateColumns = tmpl; + head.innerHTML = mCols.map(c => `
${esc(c.label)}${mstate.sort === c.key ? (mstate.dir < 0 ? ' ↓' : ' ↑') : ''}
`).join(''); + const all = files ? metricFiles() : metricFuncs(); + const bad = all.filter(r => files ? r.nviol || r.viol : r.viol).length; + $('#m-sum').textContent = `${fmt(list.length)} of ${fmt(all.length)} ${files ? 'files' : 'functions'} · ${fmt(bad)} over thresholds`; + const table = $('#m-table'); + table.scrollTop = mstate.scrollTop; + mRange = ''; + if (!list.length) { + $('#m-rows').innerHTML = `
No ${files ? 'files' : 'functions'} match the filters
`; + return; + } + renderMRows(true); +} + +function renderMRows(force) { + const table = $('#m-table'); + if (!table || !mRows.length) return; + const top = Math.max(0, table.scrollTop - M_HEAD_H), hgt = table.clientHeight || 800; + const start = Math.max(0, Math.floor(top / M_ROW_H) - 10); + const end = Math.min(mRows.length, Math.ceil((top + hgt) / M_ROW_H) + 10); + const range = start + ':' + end; + if (!force && range === mRange) return; + mRange = range; + const files = mstate.mode === 'files'; + const tmpl = mCols.map(c => c.w).join(' '); + const cell = (r, j) => { + const v = r.v[j]; + if (v === null || v === undefined) return '
–
'; + return `
${fmt(v)}
`; + }; + let h = ''; + for (let i = start; i < end; i++) { + const r = mRows[i]; + let c = ''; + if (files) { + c += `
${esc(r.file)}
`; + if (HAS_PRODUCTS) c += `
${esc(r.product)}
`; + c += `
${fmt(r.n)}
${fmt(r.nviol)}
`; + c += `
${r.maxcc === null ? '–' : fmt(r.maxcc)}
`; + c += METRICS.lids.map((id, j) => cell(r, j)).join(''); + } else { + c += `
${esc(r.name)}
${esc(r.file)}:${r.line}
`; + c += `
${fmt(r.viol)}
`; + c += METRICS.fids.map((id, j) => cell(r, j)).join(''); + } + h += `
${c}
`; + } + $('#m-rows').innerHTML = h; +} + +// ---------------------------------------------------------------- init +const setTopbarH = () => document.documentElement.style.setProperty('--topbar-h', $('.topbar').offsetHeight + 'px'); +new ResizeObserver(() => codeEl.style.setProperty('--code-w', codeEl.clientWidth + 'px')).observe(codeEl); +window.addEventListener('resize', setTopbarH); +setTopbarH(); +if (RAW.metrics) $('#nav-metrics').hidden = false; +renderDashboard(); +loadMetrics(); +$('#nav-count').textContent = fmt(RESULTS.length); +if (location.hash === '#results' || location.hash === '#metrics') showView(location.hash.slice(1)); +})(); +''' + +if __name__ == '__main__': + main() diff --git a/htmlreport/README.txt b/reports/htmlreport/README.txt similarity index 100% rename from htmlreport/README.txt rename to reports/htmlreport/README.txt diff --git a/htmlreport/cppcheck-htmlreport b/reports/htmlreport/cppcheck-htmlreport similarity index 100% rename from htmlreport/cppcheck-htmlreport rename to reports/htmlreport/cppcheck-htmlreport diff --git a/htmlreport/cppcheck_htmlreport/__init__.py b/reports/htmlreport/cppcheck_htmlreport/__init__.py similarity index 100% rename from htmlreport/cppcheck_htmlreport/__init__.py rename to reports/htmlreport/cppcheck_htmlreport/__init__.py diff --git a/htmlreport/requirements.txt b/reports/htmlreport/requirements.txt similarity index 100% rename from htmlreport/requirements.txt rename to reports/htmlreport/requirements.txt diff --git a/htmlreport/setup.py b/reports/htmlreport/setup.py similarity index 95% rename from htmlreport/setup.py rename to reports/htmlreport/setup.py index 9f85000a090..39cabebde5a 100755 --- a/htmlreport/setup.py +++ b/reports/htmlreport/setup.py @@ -19,7 +19,7 @@ url="https://github.com/cppcheck-opensource/cppcheck", license="GPL", packages=find_packages(exclude=("tests", "docs")), - use_scm_version={"root": ".."}, + use_scm_version={"root": "../.."}, entry_points={ "console_scripts": [ "cppcheck-htmlreport = cppcheck_htmlreport:run.main", diff --git a/test/tools/htmlreport/check.sh b/test/tools/htmlreport/check.sh index d3945eea532..93a0c8ee895 100755 --- a/test/tools/htmlreport/check.sh +++ b/test/tools/htmlreport/check.sh @@ -28,7 +28,7 @@ GUI_TEST_XML="$REPORT_DIR/gui_test.xml" ERRORLIST_XML="$REPORT_DIR/errorlist.xml" UNMATCHEDSUPPR_XML="$REPORT_DIR/unmatchedSuppr.xml" -$PYTHON ${PROJECT_ROOT_DIR}/htmlreport/cppcheck-htmlreport --file ${PROJECT_ROOT_DIR}/gui/test/data/xmlfiles/xmlreport_v2.xml --title "xml2 test" --report-dir "$REPORT_DIR" --source-dir ${PROJECT_ROOT_DIR}/test/ +$PYTHON ${PROJECT_ROOT_DIR}/reports/htmlreport/cppcheck-htmlreport --file ${PROJECT_ROOT_DIR}/gui/test/data/xmlfiles/xmlreport_v2.xml --title "xml2 test" --report-dir "$REPORT_DIR" --source-dir ${PROJECT_ROOT_DIR}/test/ echo -e "\n" # Check HTML syntax validate_html "$INDEX_HTML" @@ -37,7 +37,7 @@ validate_html "$STATS_HTML" ${PROJECT_ROOT_DIR}/cppcheck ${PROJECT_ROOT_DIR}/samples --enable=all --inconclusive --xml-version=2 2> "$GUI_TEST_XML" xmllint --noout "$GUI_TEST_XML" -$PYTHON ${PROJECT_ROOT_DIR}/htmlreport/cppcheck-htmlreport --file "$GUI_TEST_XML" --title "xml2 + inconclusive test" --report-dir "$REPORT_DIR" +$PYTHON ${PROJECT_ROOT_DIR}/reports/htmlreport/cppcheck-htmlreport --file "$GUI_TEST_XML" --title "xml2 + inconclusive test" --report-dir "$REPORT_DIR" echo "" # Check HTML syntax validate_html "$INDEX_HTML" @@ -46,7 +46,7 @@ validate_html "$STATS_HTML" ${PROJECT_ROOT_DIR}/cppcheck ${PROJECT_ROOT_DIR}/samples --enable=all --inconclusive --verbose --xml-version=2 2> "$GUI_TEST_XML" xmllint --noout "$GUI_TEST_XML" -$PYTHON ${PROJECT_ROOT_DIR}/htmlreport/cppcheck-htmlreport --file "$GUI_TEST_XML" --title "xml2 + inconclusive + verbose test" --report-dir "$REPORT_DIR" +$PYTHON ${PROJECT_ROOT_DIR}/reports/htmlreport/cppcheck-htmlreport --file "$GUI_TEST_XML" --title "xml2 + inconclusive + verbose test" --report-dir "$REPORT_DIR" echo -e "\n" # Check HTML syntax validate_html "$INDEX_HTML" @@ -55,7 +55,7 @@ validate_html "$STATS_HTML" ${PROJECT_ROOT_DIR}/cppcheck --errorlist --inconclusive --xml-version=2 > "$ERRORLIST_XML" xmllint --noout "$ERRORLIST_XML" -$PYTHON ${PROJECT_ROOT_DIR}/htmlreport/cppcheck-htmlreport --file "$ERRORLIST_XML" --title "errorlist" --report-dir "$REPORT_DIR" +$PYTHON ${PROJECT_ROOT_DIR}/reports/htmlreport/cppcheck-htmlreport --file "$ERRORLIST_XML" --title "errorlist" --report-dir "$REPORT_DIR" # Check HTML syntax validate_html "$INDEX_HTML" validate_html "$STATS_HTML" @@ -63,7 +63,7 @@ validate_html "$STATS_HTML" ${PROJECT_ROOT_DIR}/cppcheck ${PROJECT_ROOT_DIR}/samples/memleak/good.c ${PROJECT_ROOT_DIR}/samples/resourceLeak/good.c --xml-version=2 --enable=information --suppressions-list="${ABSOLUTE_SCRIPT_DIR}/test_suppressions.txt" --xml 2> "$UNMATCHEDSUPPR_XML" xmllint --noout "$UNMATCHEDSUPPR_XML" -$PYTHON ${PROJECT_ROOT_DIR}/htmlreport/cppcheck-htmlreport --file "$UNMATCHEDSUPPR_XML" --title "unmatched Suppressions" --report-dir="$REPORT_DIR" +$PYTHON ${PROJECT_ROOT_DIR}/reports/htmlreport/cppcheck-htmlreport --file "$UNMATCHEDSUPPR_XML" --title "unmatched Suppressions" --report-dir="$REPORT_DIR" grep "unmatchedSuppression<.*>information<.*>Unmatched suppression: variableScope*<" "$INDEX_HTML" grep ">unmatchedSuppressioninformation<.*>Unmatched suppression: uninitstring<" "$INDEX_HTML" # Check HTML syntax diff --git a/test/tools/htmlreport/test_htmlreport.py b/test/tools/htmlreport/test_htmlreport.py index d5ac11aa16b..703508aceee 100755 --- a/test/tools/htmlreport/test_htmlreport.py +++ b/test/tools/htmlreport/test_htmlreport.py @@ -12,7 +12,7 @@ TEST_TOOLS_DIR = os.path.abspath(os.path.dirname(__file__)) ROOT_DIR = os.path.split(os.path.dirname(os.path.dirname(TEST_TOOLS_DIR)))[0] -HTMLREPORT_DIR = os.path.join(ROOT_DIR, 'htmlreport') +HTMLREPORT_DIR = os.path.join(ROOT_DIR, 'reports', 'htmlreport') CPPCHECK_BIN = os.path.join(ROOT_DIR, 'cppcheck') if os.getenv("PIP_PACKAGE_TEST") is not None: diff --git a/tools/dmake/dmake.cpp b/tools/dmake/dmake.cpp index 8bb4a72b212..b253297af7b 100644 --- a/tools/dmake/dmake.cpp +++ b/tools/dmake/dmake.cpp @@ -844,7 +844,7 @@ int main(int argc, char **argv) fout << "install: cppcheck\n"; fout << "\tinstall -d ${BIN}\n"; fout << "\tinstall cppcheck ${BIN}\n"; - fout << "\tinstall htmlreport/cppcheck-htmlreport ${BIN}\n"; + fout << "\tinstall reports/htmlreport/cppcheck-htmlreport ${BIN}\n"; fout << "ifdef FILESDIR\n"; fout << "\tinstall -d ${DESTDIR}${FILESDIR}\n"; fout << "\tinstall -d ${DESTDIR}${FILESDIR}/addons\n"; From 422f17c2fe21c421f7aa3317bd3d248322bd7f1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Tue, 1 Dec 2026 19:04:09 +0100 Subject: [PATCH 2/3] manual --- man/manual.md | 75 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 49 insertions(+), 26 deletions(-) diff --git a/man/manual.md b/man/manual.md index 244c0bd8446..0d2af0b7050 100644 --- a/man/manual.md +++ b/man/manual.md @@ -1341,7 +1341,18 @@ 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 reports/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: @@ -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,26 +1405,26 @@ 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. -# Cppcheck Explorer report +## Explorer report -The script `reports/explorer/report.py` in the Cppcheck source tree converts Cppcheck XML output into a Cppcheck Explorer report, which you view in a browser. The report has a dashboard with graphs, and a results view where you can filter the warnings and see the related source code. It is designed to be responsive also when there are thousands of warnings. +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 +### Generating a report -First analyze the code and save the results in a XML file, then generate the 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. No web server is needed. To share the report, copy the whole `cppcheck-report` folder. Note that the report contains the source code. +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 +### 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: @@ -1424,7 +1435,7 @@ If you provide the XML results from an earlier analysis as a baseline, then the cppcheck --enable=style --xml src 2> results.xml python3 reports/explorer/report.py results.xml --baseline=baseline.xml -o cppcheck-report -## Trend graphs +### 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: @@ -1437,6 +1448,34 @@ Save the XML results from each analysis in a folder and use `--history` to get t 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 @@ -1597,23 +1636,7 @@ Example: cppcheck --premium=metrics test.c --xml-version=3 2> res.xml -To view the metrics, it is recommended that you generate a [Cppcheck Explorer report](#cppcheck-explorer-report): - - python3 reports/explorer/report.py res.xml -o cppcheck-report - -Open `cppcheck-report/index.html` in a browser. 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 +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: From c7d9c0f3165df4f5aba5a5f699d5e3b71e9890fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Wed, 2 Dec 2026 10:46:52 +0100 Subject: [PATCH 3/3] explorer: fix gutter marker tooltip and add tests for the report javascript The gutter marker tooltip in the code view showed raw markup because tipHtml() output (escaped for a data-tip attribute) was assigned to el.dataset.tip. Add tipInner() for that case. Move the DOM-free javascript helpers into JS_LIB so they can be unit tested with node's built-in test runner, and add a pytest wrapper that runs the tests and syntax checks the generated report.js. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/scriptcheck.yml | 6 + reports/explorer/report.py | 242 +++++++++++++----------- test/tools/explorer/explorer_js_test.py | 64 +++++++ test/tools/explorer/lib.test.js | 158 ++++++++++++++++ 4 files changed, 361 insertions(+), 109 deletions(-) create mode 100644 test/tools/explorer/explorer_js_test.py create mode 100644 test/tools/explorer/lib.test.js diff --git a/.github/workflows/scriptcheck.yml b/.github/workflows/scriptcheck.yml index d239ee0406c..ea1e8e63ba2 100644 --- a/.github/workflows/scriptcheck.yml +++ b/.github/workflows/scriptcheck.yml @@ -191,6 +191,12 @@ jobs: env: PYTHONPATH: ./tools + # uses the node that is installed on the runner + - name: test explorer report javascript + run: | + node --version + python -m pytest -Werror --strict-markers -vv test/tools/explorer/explorer_js_test.py + - 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/reports/explorer/report.py b/reports/explorer/report.py index 9323d05aea9..5af9227da27 100755 --- a/reports/explorer/report.py +++ b/reports/explorer/report.py @@ -685,7 +685,7 @@ def generate(args): 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)): + 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) @@ -1403,10 +1403,140 @@ def main(): ::-webkit-scrollbar-track { background: transparent; } ''' +JS_LIB = r''' +// Helpers that do not use the DOM or the report data. They are tested with node, +// see test/tools/explorer/. +const CppcheckExplorer = (function () { +'use strict'; + +const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +const fmt = n => (n || 0).toLocaleString(); +const pct = (n, t) => t ? (100 * n / t).toFixed(n / t < 0.1 ? 1 : 0) + '%' : '0%'; +const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : s; +const basename = p => p.split(/[\\/]/).pop(); +const countBy = (arr, f) => { const m = new Map(); for (const x of arr) { const k = f(x); m.set(k, (m.get(k) || 0) + 1); } return m; }; + +// wrap the case-insensitive matches of search in +function highlightMatch(text, search) { + if (!search) return esc(text); + const q = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return String(text).split(new RegExp('(' + q + ')', 'gi')).map((part, i) => i % 2 ? `${esc(part)}` : esc(part)).join(''); +} + +// tooltip markup; tipHtml() escapes it again for use inside a data-tip="..." attribute in a template, +// tipInner() is for assigning to el.dataset.tip directly +const tipInner = (title, rows) => '
' + esc(title) + '
' + + rows.map(([c, l, v]) => `
${c ? `` : ''}${esc(l)}${esc(v)}
`).join(''); +const tipHtml = (title, rows) => esc(tipInner(title, rows)); + +// ---- axis helpers for the svg charts +function niceStep(max, n) { + const raw = Math.max(max, 1) / n; + const p = Math.pow(10, Math.floor(Math.log10(raw))); + const m = raw / p; + return Math.max(1, (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p); +} +function yAxis(maxV) { + const step = niceStep(maxV, 4); + const top = Math.max(step, Math.ceil(maxV / step) * step); + const ticks = []; + for (let v = 0; v <= top + 1e-9; v += step) ticks.push(v); + return { top, ticks }; +} +const fmtShort = n => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n); + +// ---------------------------------------------------------------- syntax highlighting (C/C++) +const KW = new Set(('alignas alignof and asm auto break case catch class co_await co_return co_yield concept const consteval constexpr constinit const_cast continue ' + + 'decltype default delete do dynamic_cast else enum explicit export extern false final for friend goto if inline mutable namespace new noexcept not nullptr ' + + 'operator or override private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this ' + + 'thread_local throw true try typedef typeid typename union using virtual volatile while NULL').split(' ')); +const TY = new Set(('bool char char8_t char16_t char32_t double float int long short signed unsigned void wchar_t size_t ssize_t ptrdiff_t ' + + 'int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t intptr_t uintptr_t std string vector map set list FILE').split(' ')); +const TOK = /(\/\/.*$)|(\/\*)|("(?:\\.|[^"\\])*"?)|('(?:\\.|[^'\\])*'?)|(\b\d[\w.']*|\.\d[\w']*)|([A-Za-z_]\w*)(\s*\()?|([^\w\s"'\/]+|\/|\s+)/y; + +// returns true if the line ends inside a block comment +function scanBlock(line, block) { + let i = 0; + const n = line.length; + while (i < n) { + if (block) { + const e = line.indexOf('*/', i); + if (e < 0) return true; + block = false; i = e + 2; + continue; + } + const c = line.charCodeAt(i); + if (c === 47 /* / */) { + const d = line.charCodeAt(i + 1); + if (d === 47) return false; + if (d === 42) { block = true; i += 2; continue; } + } else if (c === 34 || c === 39) { + i++; + while (i < n && line.charCodeAt(i) !== c) i += line.charCodeAt(i) === 92 ? 2 : 1; + } + i++; + } + return block; +} + +function hl(line, st) { + if (line.length > 3000) return esc(line); + let out = '', pos = 0; + if (st.block) { + const e = line.indexOf('*/'); + if (e < 0) return `${esc(line)}`; + out += `${esc(line.slice(0, e + 2))}`; + pos = e + 2; st.block = false; + } + if (pos === 0 && /^\s*#/.test(line)) { + const m = /^(\s*#\s*\w*)(.*)$/.exec(line); + out += `${esc(m[1])}`; + const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(m[2]); + if (inc) return out + esc(inc[1]) + `${esc(inc[2])}` + hlRest(inc[3], st); + return out + hlRest(m[2], st); + } + return out + hlRest(line.slice(pos), st); +} + +function hlRest(s, st) { + let out = ''; + TOK.lastIndex = 0; + while (TOK.lastIndex < s.length) { + const start = TOK.lastIndex; + const m = TOK.exec(s); + if (!m) { out += esc(s.slice(start)); break; } + if (m[1]) out += `${esc(m[1])}`; + else if (m[2]) { + const e = s.indexOf('*/', TOK.lastIndex); + if (e < 0) { out += `${esc(s.slice(start))}`; st.block = true; break; } + out += `${esc(s.slice(start, e + 2))}`; + TOK.lastIndex = e + 2; + } else if (m[3] || m[4]) out += `${esc(m[3] || m[4])}`; + else if (m[5]) out += `${esc(m[5])}`; + else if (m[6]) { + const w = m[6]; + if (KW.has(w)) out += `${w}`; + else if (TY.has(w)) out += `${w}`; + else if (m[7]) out += `${w}`; + else out += w; + if (m[7]) out += esc(m[7]); + } else out += esc(m[8]); + } + return out; +} + +return { esc, fmt, pct, cap, basename, countBy, highlightMatch, tipInner, tipHtml, niceStep, yAxis, fmtShort, scanBlock, hl }; +})(); + +if (typeof module !== 'undefined') module.exports = CppcheckExplorer; +''' + JS = r''' (function () { 'use strict'; +const { esc, fmt, pct, cap, basename, countBy, highlightMatch, tipInner, tipHtml, niceStep, yAxis, fmtShort, scanBlock, hl } = CppcheckExplorer; + const RAW = window.CPPCHECK_REPORT; if (!RAW) { document.body.innerHTML = '

Failed to load data/results.js. Keep the report files together in one folder.

'; @@ -1448,12 +1578,6 @@ def main(): RESULTS.forEach(r => { r.cat = catOf(r); r.catRank = catRank(r.cat); }); const $ = (sel, el) => (el || document).querySelector(sel); -const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); -const fmt = n => (n || 0).toLocaleString(); -const pct = (n, t) => t ? (100 * n / t).toFixed(n / t < 0.1 ? 1 : 0) + '%' : '0%'; -const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : s; -const basename = p => p.split(/[\\/]/).pop(); -const countBy = (arr, f) => { const m = new Map(); for (const x of arr) { const k = f(x); m.set(k, (m.get(k) || 0) + 1); } return m; }; const catBadge = c => `${esc(c)}`; const sevBadge = s => `${esc(s)}`; const checkSvg = ''; @@ -1598,9 +1722,6 @@ def main(): if (y + h > window.innerHeight - 8) y = e.clientY - h - 14; tip.style.left = x + 'px'; tip.style.top = y + 'px'; }); -const tipHtml = (title, rows) => esc('
' + esc(title) + '
' + - rows.map(([c, l, v]) => `
${c ? `` : ''}${esc(l)}${esc(v)}
`).join('')); - // ---------------------------------------------------------------- charts function donut(segments, total, caption) { const R = 70, C = 2 * Math.PI * R, GAP = segments.filter(s => s.value).length > 1 ? 2.5 : 0; @@ -1640,21 +1761,6 @@ def main(): return '
' + items.map(([c, l]) => `${esc(l)}`).join('') + '
'; } -// ---- axis helpers for the svg charts -function niceStep(max, n) { - const raw = Math.max(max, 1) / n; - const p = Math.pow(10, Math.floor(Math.log10(raw))); - const m = raw / p; - return Math.max(1, (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p); -} -function yAxis(maxV) { - const step = niceStep(maxV, 4); - const top = Math.max(step, Math.ceil(maxV / step) * step); - const ticks = []; - for (let v = 0; v <= top + 1e-9; v += step) ticks.push(v); - return { top, ticks }; -} -const fmtShort = n => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n); function xLabels(labels, x, H, plotW) { // show as many labels as fit without overlapping (about 6.5px per character) const n = labels.length; @@ -2208,9 +2314,7 @@ def main(): }); function highlight(text) { - if (!state.search) return esc(text); - const q = state.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - return String(text).split(new RegExp('(' + q + ')', 'gi')).map((part, i) => i % 2 ? `${esc(part)}` : esc(part)).join(''); + return highlightMatch(text, state.search); } // ---- virtual list: only the visible rows are in the DOM @@ -2538,7 +2642,7 @@ def main(): const i = document.createElement('i'); i.style.setProperty('--c', catColor(rs[0].cat)); i.dataset.idx = rs[0].idx; - i.dataset.tip = tipHtml(`Line ${line}`, rs.slice(0, 8).map(r => [catColor(r.cat), CLS_MODE && r.guideline ? r.guideline : r.id, r.cat])); + i.dataset.tip = tipInner(`Line ${line}`, rs.slice(0, 8).map(r => [catColor(r.cat), CLS_MODE && r.guideline ? r.guideline : r.id, r.cat])); v.lineEls[line - 1].querySelector('.m').appendChild(i); } @@ -2572,86 +2676,6 @@ def main(): if (i) select(+i.dataset.idx); }); -// ---------------------------------------------------------------- syntax highlighting (C/C++) -const KW = new Set(('alignas alignof and asm auto break case catch class co_await co_return co_yield concept const consteval constexpr constinit const_cast continue ' + - 'decltype default delete do dynamic_cast else enum explicit export extern false final for friend goto if inline mutable namespace new noexcept not nullptr ' + - 'operator or override private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this ' + - 'thread_local throw true try typedef typeid typename union using virtual volatile while NULL').split(' ')); -const TY = new Set(('bool char char8_t char16_t char32_t double float int long short signed unsigned void wchar_t size_t ssize_t ptrdiff_t ' + - 'int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t intptr_t uintptr_t std string vector map set list FILE').split(' ')); -const TOK = /(\/\/.*$)|(\/\*)|("(?:\\.|[^"\\])*"?)|('(?:\\.|[^'\\])*'?)|(\b\d[\w.']*|\.\d[\w']*)|([A-Za-z_]\w*)(\s*\()?|([^\w\s"'\/]+|\/|\s+)/y; - -// returns true if the line ends inside a block comment -function scanBlock(line, block) { - let i = 0; - const n = line.length; - while (i < n) { - if (block) { - const e = line.indexOf('*/', i); - if (e < 0) return true; - block = false; i = e + 2; - continue; - } - const c = line.charCodeAt(i); - if (c === 47 /* / */) { - const d = line.charCodeAt(i + 1); - if (d === 47) return false; - if (d === 42) { block = true; i += 2; continue; } - } else if (c === 34 || c === 39) { - i++; - while (i < n && line.charCodeAt(i) !== c) i += line.charCodeAt(i) === 92 ? 2 : 1; - } - i++; - } - return block; -} - -function hl(line, st) { - if (line.length > 3000) return esc(line); - let out = '', pos = 0; - if (st.block) { - const e = line.indexOf('*/'); - if (e < 0) return `${esc(line)}`; - out += `${esc(line.slice(0, e + 2))}`; - pos = e + 2; st.block = false; - } - if (pos === 0 && /^\s*#/.test(line)) { - const m = /^(\s*#\s*\w*)(.*)$/.exec(line); - out += `${esc(m[1])}`; - const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(m[2]); - if (inc) return out + esc(inc[1]) + `${esc(inc[2])}` + hlRest(inc[3], st); - return out + hlRest(m[2], st); - } - return out + hlRest(line.slice(pos), st); -} - -function hlRest(s, st) { - let out = ''; - TOK.lastIndex = 0; - while (TOK.lastIndex < s.length) { - const start = TOK.lastIndex; - const m = TOK.exec(s); - if (!m) { out += esc(s.slice(start)); break; } - if (m[1]) out += `${esc(m[1])}`; - else if (m[2]) { - const e = s.indexOf('*/', TOK.lastIndex); - if (e < 0) { out += `${esc(s.slice(start))}`; st.block = true; break; } - out += `${esc(s.slice(start, e + 2))}`; - TOK.lastIndex = e + 2; - } else if (m[3] || m[4]) out += `${esc(m[3] || m[4])}`; - else if (m[5]) out += `${esc(m[5])}`; - else if (m[6]) { - const w = m[6]; - if (KW.has(w)) out += `${w}`; - else if (TY.has(w)) out += `${w}`; - else if (m[7]) out += `${w}`; - else out += w; - if (m[7]) out += esc(m[7]); - } else out += esc(m[8]); - } - return out; -} - // ---------------------------------------------------------------- metrics const METRIC_INFO = { cyclomaticComplexity: ['v(G)', 'Cyclomatic complexity'], diff --git a/test/tools/explorer/explorer_js_test.py b/test/tools/explorer/explorer_js_test.py new file mode 100644 index 00000000000..93a6614c2c9 --- /dev/null +++ b/test/tools/explorer/explorer_js_test.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Test the JavaScript code of the Cppcheck Explorer report (reports/explorer/report.py) with node.""" + +import importlib.util +import os +import shutil +import subprocess +import sys + +import pytest + +TEST_DIR = os.path.dirname(os.path.abspath(__file__)) +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(TEST_DIR))) +REPORT_PY = os.path.join(ROOT_DIR, 'reports', 'explorer', 'report.py') + +NODE = shutil.which('node') +pytestmark = pytest.mark.skipif(NODE is None, reason='node is not installed') + +XML = ''' + + + + + + x + + + + y + + + +''' + + +def load_report(): + spec = importlib.util.spec_from_file_location('explorer_report', REPORT_PY) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def run_node(args, env=None): + p = subprocess.run([NODE] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + universal_newlines=True, env=env, check=False) + assert p.returncode == 0, p.stdout + return p.stdout + + +def test_lib(tmp_path): + lib = tmp_path / 'lib.js' + lib.write_text(load_report().JS_LIB, encoding='utf-8') + env = dict(os.environ, EXPLORER_LIB=str(lib)) + run_node(['--test', os.path.join(TEST_DIR, 'lib.test.js')], env=env) + + +def test_generated_report_js_syntax(tmp_path): + (tmp_path / 'a.cpp').write_text('int f() {\n int y;\n int x; return x;\n}\n', encoding='utf-8') + (tmp_path / 'results.xml').write_text(XML, encoding='utf-8') + out = tmp_path / 'report' + subprocess.run([sys.executable, REPORT_PY, str(tmp_path / 'results.xml'), '-o', str(out), + '--source-dir', str(tmp_path)], check=True, stdout=subprocess.PIPE) + for f in ('report.js', os.path.join('data', 'results.js')): + run_node(['--check', str(out / f)]) diff --git a/test/tools/explorer/lib.test.js b/test/tools/explorer/lib.test.js new file mode 100644 index 00000000000..9d2ea413f5c --- /dev/null +++ b/test/tools/explorer/lib.test.js @@ -0,0 +1,158 @@ +// Unit tests for the DOM-free helpers of the Cppcheck Explorer report (JS_LIB in reports/explorer/report.py). +// +// Run through pytest: python -m pytest test/tools/explorer/explorer_js_test.py +// or directly: EXPLORER_LIB=/path/to/lib.js node --test test/tools/explorer/lib.test.js +// where lib.js contains report.JS_LIB. + +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +if (!process.env.EXPLORER_LIB) + throw new Error('EXPLORER_LIB is not set, it should be the path of a file containing report.JS_LIB'); +const L = require(process.env.EXPLORER_LIB); + +// highlight a whole source file the way the code view does it +function hlLines(lines) { + const st = { block: false }; + return lines.map(l => L.hl(l, st)); +} + +test('esc', () => { + assert.equal(L.esc('\'&\''), '<a href="x">'&'</a>'); + assert.equal(L.esc(42), '42'); + assert.equal(L.esc(''), ''); +}); + +test('basename', () => { + assert.equal(L.basename('src/lib/a.cpp'), 'a.cpp'); + assert.equal(L.basename('C:\\src\\a.cpp'), 'a.cpp'); + assert.equal(L.basename('a.cpp'), 'a.cpp'); +}); + +test('cap', () => { + assert.equal(L.cap('error'), 'Error'); + assert.equal(L.cap(''), ''); +}); + +test('pct', () => { + assert.equal(L.pct(1, 3), '33%'); + assert.equal(L.pct(1, 20), '5.0%'); + assert.equal(L.pct(3, 3), '100%'); + assert.equal(L.pct(0, 0), '0%'); +}); + +test('fmtShort', () => { + assert.equal(L.fmtShort(0), '0'); + assert.equal(L.fmtShort(999), '999'); + assert.equal(L.fmtShort(1000), '1k'); + assert.equal(L.fmtShort(1500), '1.5k'); + assert.equal(L.fmtShort(12345), '12k'); +}); + +test('countBy', () => { + const m = L.countBy(['a', 'b', 'a'], x => x); + assert.deepEqual([...m.entries()], [['a', 2], ['b', 1]]); +}); + +test('yAxis', () => { + assert.deepEqual(L.yAxis(37), { top: 40, ticks: [0, 10, 20, 30, 40] }); + assert.deepEqual(L.yAxis(0), { top: 1, ticks: [0, 1] }); + assert.deepEqual(L.yAxis(4), { top: 4, ticks: [0, 1, 2, 3, 4] }); + for (const max of [1, 7, 99, 1234, 98765]) { + const { top, ticks } = L.yAxis(max); + assert.ok(top >= max, `top ${top} < max ${max}`); + assert.ok(ticks.length >= 2 && ticks.length <= 6, `${ticks.length} ticks for max ${max}`); + } +}); + +test('highlightMatch', () => { + assert.equal(L.highlightMatch('', ''), '<x>'); + // case-insensitive, the text keeps its case + assert.equal(L.highlightMatch('Null pointer null', 'null'), 'Null pointer null'); + // regex characters in the search are literal + assert.equal(L.highlightMatch('a.b axb', 'a.b'), 'a.b axb'); + assert.equal(L.highlightMatch('f(x) [y]', '(x)'), 'f(x) [y]'); + // matches and the text around them are escaped + assert.equal(L.highlightMatch('a ', ''), 'a<b> <b>'); +}); + +test('tipInner is markup for el.dataset.tip', () => { + assert.equal(L.tipInner('Line 1', [[null, 'uninitvar', 'error']]), + '
Line 1
uninitvarerror
'); + assert.equal(L.tipInner('t', [['red', 'a', 'b']]), + '
t
ab
'); + // text is escaped + assert.equal(L.tipInner('aa<b
x&y"z"
'); +}); + +test('tipHtml is tipInner escaped for a data-tip="..." attribute', () => { + const rows = [['var(--sev-error)', 'a"]/.test(attr), attr); + assert.equal(attr, L.esc(L.tipInner('T"', rows))); +}); + +test('scanBlock', () => { + assert.equal(L.scanBlock('int a;', false), false); + assert.equal(L.scanBlock('int a; /* x', false), true); + assert.equal(L.scanBlock('/* x */ int a;', false), false); + assert.equal(L.scanBlock('x */ y', true), false); + assert.equal(L.scanBlock('still in comment', true), true); + assert.equal(L.scanBlock('// /*', false), false); + assert.equal(L.scanBlock('s = "/*";', false), false); + assert.equal(L.scanBlock('c = \'"\'; /*', false), true); + assert.equal(L.scanBlock('s = "\\" /*";', false), false); +}); + +test('hl: tokens', () => { + assert.equal(L.hl('return x;', { block: false }), 'return x;'); + assert.equal(L.hl('int f(void)', { block: false }), + 'int f(void)'); + assert.equal(L.hl('x = 0x1F;', { block: false }), 'x = 0x1F;'); + assert.equal(L.hl("x = 1'000'000;", { block: false }), 'x = 1'000'000;'); + assert.equal(L.hl('s = "a\\"b";', { block: false }), 's = "a\\"b";'); + assert.equal(L.hl("c = '\\'';", { block: false }), 'c = '\\'';'); + assert.equal(L.hl('x; // a ', { block: false }), 'x; // a <b>'); +}); + +test('hl: code is escaped', () => { + assert.equal(L.hl('ad', { block: false }), 'a<b && c>d'); + assert.equal(L.hl('"