Skip to content

Commit c7d9c0f

Browse files
dmcppcheckclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 422f17c commit c7d9c0f

4 files changed

Lines changed: 361 additions & 109 deletions

File tree

‎.github/workflows/scriptcheck.yml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,12 @@ jobs:
191191
env:
192192
PYTHONPATH: ./tools
193193

194+
# uses the node that is installed on the runner
195+
- name: test explorer report javascript
196+
run: |
197+
node --version
198+
python -m pytest -Werror --strict-markers -vv test/tools/explorer/explorer_js_test.py
199+
194200
- name: Show all ignored files
195201
if: false # TODO: currently lists all the contents of ignored folders - we only need what actually matched
196202
run: |

‎reports/explorer/report.py‎

Lines changed: 133 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -685,7 +685,7 @@ def generate(args):
685685
write_js(os.path.join(data_dir, 'results.js'), 'window.CPPCHECK_REPORT=', data)
686686

687687
page = HTML_TEMPLATE.replace('%%TITLE%%', html.escape(args.title)).replace('%%THEME%%', html.escape(args.theme))
688-
for name, content in (('index.html', page), ('report.css', CSS), ('report.js', JS)):
688+
for name, content in (('index.html', page), ('report.css', CSS), ('report.js', JS_LIB + JS)):
689689
with open(os.path.join(out, name), 'wt', encoding='utf-8') as f:
690690
f.write(content)
691691

@@ -1403,10 +1403,140 @@ def main():
14031403
::-webkit-scrollbar-track { background: transparent; }
14041404
'''
14051405

1406+
JS_LIB = r'''
1407+
// Helpers that do not use the DOM or the report data. They are tested with node,
1408+
// see test/tools/explorer/.
1409+
const CppcheckExplorer = (function () {
1410+
'use strict';
1411+
1412+
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
1413+
const fmt = n => (n || 0).toLocaleString();
1414+
const pct = (n, t) => t ? (100 * n / t).toFixed(n / t < 0.1 ? 1 : 0) + '%' : '0%';
1415+
const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : s;
1416+
const basename = p => p.split(/[\\/]/).pop();
1417+
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; };
1418+
1419+
// wrap the case-insensitive matches of search in <mark>
1420+
function highlightMatch(text, search) {
1421+
if (!search) return esc(text);
1422+
const q = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1423+
return String(text).split(new RegExp('(' + q + ')', 'gi')).map((part, i) => i % 2 ? `<mark>${esc(part)}</mark>` : esc(part)).join('');
1424+
}
1425+
1426+
// tooltip markup; tipHtml() escapes it again for use inside a data-tip="..." attribute in a template,
1427+
// tipInner() is for assigning to el.dataset.tip directly
1428+
const tipInner = (title, rows) => '<div class="tt-title">' + esc(title) + '</div>' +
1429+
rows.map(([c, l, v]) => `<div class="tt-row">${c ? `<span class="dot" style="background:${c}"></span>` : ''}${esc(l)}<b>${esc(v)}</b></div>`).join('');
1430+
const tipHtml = (title, rows) => esc(tipInner(title, rows));
1431+
1432+
// ---- axis helpers for the svg charts
1433+
function niceStep(max, n) {
1434+
const raw = Math.max(max, 1) / n;
1435+
const p = Math.pow(10, Math.floor(Math.log10(raw)));
1436+
const m = raw / p;
1437+
return Math.max(1, (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p);
1438+
}
1439+
function yAxis(maxV) {
1440+
const step = niceStep(maxV, 4);
1441+
const top = Math.max(step, Math.ceil(maxV / step) * step);
1442+
const ticks = [];
1443+
for (let v = 0; v <= top + 1e-9; v += step) ticks.push(v);
1444+
return { top, ticks };
1445+
}
1446+
const fmtShort = n => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n);
1447+
1448+
// ---------------------------------------------------------------- syntax highlighting (C/C++)
1449+
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 ' +
1450+
'decltype default delete do dynamic_cast else enum explicit export extern false final for friend goto if inline mutable namespace new noexcept not nullptr ' +
1451+
'operator or override private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this ' +
1452+
'thread_local throw true try typedef typeid typename union using virtual volatile while NULL').split(' '));
1453+
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 ' +
1454+
'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(' '));
1455+
const TOK = /(\/\/.*$)|(\/\*)|("(?:\\.|[^"\\])*"?)|('(?:\\.|[^'\\])*'?)|(\b\d[\w.']*|\.\d[\w']*)|([A-Za-z_]\w*)(\s*\()?|([^\w\s"'\/]+|\/|\s+)/y;
1456+
1457+
// returns true if the line ends inside a block comment
1458+
function scanBlock(line, block) {
1459+
let i = 0;
1460+
const n = line.length;
1461+
while (i < n) {
1462+
if (block) {
1463+
const e = line.indexOf('*/', i);
1464+
if (e < 0) return true;
1465+
block = false; i = e + 2;
1466+
continue;
1467+
}
1468+
const c = line.charCodeAt(i);
1469+
if (c === 47 /* / */) {
1470+
const d = line.charCodeAt(i + 1);
1471+
if (d === 47) return false;
1472+
if (d === 42) { block = true; i += 2; continue; }
1473+
} else if (c === 34 || c === 39) {
1474+
i++;
1475+
while (i < n && line.charCodeAt(i) !== c) i += line.charCodeAt(i) === 92 ? 2 : 1;
1476+
}
1477+
i++;
1478+
}
1479+
return block;
1480+
}
1481+
1482+
function hl(line, st) {
1483+
if (line.length > 3000) return esc(line);
1484+
let out = '', pos = 0;
1485+
if (st.block) {
1486+
const e = line.indexOf('*/');
1487+
if (e < 0) return `<span class="t-co">${esc(line)}</span>`;
1488+
out += `<span class="t-co">${esc(line.slice(0, e + 2))}</span>`;
1489+
pos = e + 2; st.block = false;
1490+
}
1491+
if (pos === 0 && /^\s*#/.test(line)) {
1492+
const m = /^(\s*#\s*\w*)(.*)$/.exec(line);
1493+
out += `<span class="t-pp">${esc(m[1])}</span>`;
1494+
const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(m[2]);
1495+
if (inc) return out + esc(inc[1]) + `<span class="t-st">${esc(inc[2])}</span>` + hlRest(inc[3], st);
1496+
return out + hlRest(m[2], st);
1497+
}
1498+
return out + hlRest(line.slice(pos), st);
1499+
}
1500+
1501+
function hlRest(s, st) {
1502+
let out = '';
1503+
TOK.lastIndex = 0;
1504+
while (TOK.lastIndex < s.length) {
1505+
const start = TOK.lastIndex;
1506+
const m = TOK.exec(s);
1507+
if (!m) { out += esc(s.slice(start)); break; }
1508+
if (m[1]) out += `<span class="t-co">${esc(m[1])}</span>`;
1509+
else if (m[2]) {
1510+
const e = s.indexOf('*/', TOK.lastIndex);
1511+
if (e < 0) { out += `<span class="t-co">${esc(s.slice(start))}</span>`; st.block = true; break; }
1512+
out += `<span class="t-co">${esc(s.slice(start, e + 2))}</span>`;
1513+
TOK.lastIndex = e + 2;
1514+
} else if (m[3] || m[4]) out += `<span class="t-st">${esc(m[3] || m[4])}</span>`;
1515+
else if (m[5]) out += `<span class="t-nu">${esc(m[5])}</span>`;
1516+
else if (m[6]) {
1517+
const w = m[6];
1518+
if (KW.has(w)) out += `<span class="t-kw">${w}</span>`;
1519+
else if (TY.has(w)) out += `<span class="t-ty">${w}</span>`;
1520+
else if (m[7]) out += `<span class="t-fn">${w}</span>`;
1521+
else out += w;
1522+
if (m[7]) out += esc(m[7]);
1523+
} else out += esc(m[8]);
1524+
}
1525+
return out;
1526+
}
1527+
1528+
return { esc, fmt, pct, cap, basename, countBy, highlightMatch, tipInner, tipHtml, niceStep, yAxis, fmtShort, scanBlock, hl };
1529+
})();
1530+
1531+
if (typeof module !== 'undefined') module.exports = CppcheckExplorer;
1532+
'''
1533+
14061534
JS = r'''
14071535
(function () {
14081536
'use strict';
14091537
1538+
const { esc, fmt, pct, cap, basename, countBy, highlightMatch, tipInner, tipHtml, niceStep, yAxis, fmtShort, scanBlock, hl } = CppcheckExplorer;
1539+
14101540
const RAW = window.CPPCHECK_REPORT;
14111541
if (!RAW) {
14121542
document.body.innerHTML = '<p style="padding:24px;font-family:sans-serif">Failed to load <code>data/results.js</code>. Keep the report files together in one folder.</p>';
@@ -1448,12 +1578,6 @@ def main():
14481578
RESULTS.forEach(r => { r.cat = catOf(r); r.catRank = catRank(r.cat); });
14491579
14501580
const $ = (sel, el) => (el || document).querySelector(sel);
1451-
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
1452-
const fmt = n => (n || 0).toLocaleString();
1453-
const pct = (n, t) => t ? (100 * n / t).toFixed(n / t < 0.1 ? 1 : 0) + '%' : '0%';
1454-
const cap = s => s ? s.charAt(0).toUpperCase() + s.slice(1) : s;
1455-
const basename = p => p.split(/[\\/]/).pop();
1456-
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; };
14571581
const catBadge = c => `<span class="sev ${CLS_MODE ? '' : 'cap'}"><span class="dot" style="background:${catColor(c)}"></span>${esc(c)}</span>`;
14581582
const sevBadge = s => `<span class="sev cap"><span class="dot" style="background:${sevColor(s)}"></span>${esc(s)}</span>`;
14591583
const checkSvg = '<svg viewBox="0 0 10 10"><path d="M2 5.2l2 2L8 3"/></svg>';
@@ -1598,9 +1722,6 @@ def main():
15981722
if (y + h > window.innerHeight - 8) y = e.clientY - h - 14;
15991723
tip.style.left = x + 'px'; tip.style.top = y + 'px';
16001724
});
1601-
const tipHtml = (title, rows) => esc('<div class="tt-title">' + esc(title) + '</div>' +
1602-
rows.map(([c, l, v]) => `<div class="tt-row">${c ? `<span class="dot" style="background:${c}"></span>` : ''}${esc(l)}<b>${esc(v)}</b></div>`).join(''));
1603-
16041725
// ---------------------------------------------------------------- charts
16051726
function donut(segments, total, caption) {
16061727
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():
16401761
return '<div class="chart-legend">' + items.map(([c, l]) => `<span><i style="background:${c}"></i>${esc(l)}</span>`).join('') + '</div>';
16411762
}
16421763
1643-
// ---- axis helpers for the svg charts
1644-
function niceStep(max, n) {
1645-
const raw = Math.max(max, 1) / n;
1646-
const p = Math.pow(10, Math.floor(Math.log10(raw)));
1647-
const m = raw / p;
1648-
return Math.max(1, (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p);
1649-
}
1650-
function yAxis(maxV) {
1651-
const step = niceStep(maxV, 4);
1652-
const top = Math.max(step, Math.ceil(maxV / step) * step);
1653-
const ticks = [];
1654-
for (let v = 0; v <= top + 1e-9; v += step) ticks.push(v);
1655-
return { top, ticks };
1656-
}
1657-
const fmtShort = n => n >= 10000 ? (n / 1000).toFixed(0) + 'k' : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, '') + 'k' : String(n);
16581764
function xLabels(labels, x, H, plotW) {
16591765
// show as many labels as fit without overlapping (about 6.5px per character)
16601766
const n = labels.length;
@@ -2208,9 +2314,7 @@ def main():
22082314
});
22092315
22102316
function highlight(text) {
2211-
if (!state.search) return esc(text);
2212-
const q = state.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2213-
return String(text).split(new RegExp('(' + q + ')', 'gi')).map((part, i) => i % 2 ? `<mark>${esc(part)}</mark>` : esc(part)).join('');
2317+
return highlightMatch(text, state.search);
22142318
}
22152319
22162320
// ---- virtual list: only the visible rows are in the DOM
@@ -2538,7 +2642,7 @@ def main():
25382642
const i = document.createElement('i');
25392643
i.style.setProperty('--c', catColor(rs[0].cat));
25402644
i.dataset.idx = rs[0].idx;
2541-
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]));
2645+
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]));
25422646
v.lineEls[line - 1].querySelector('.m').appendChild(i);
25432647
}
25442648
@@ -2572,86 +2676,6 @@ def main():
25722676
if (i) select(+i.dataset.idx);
25732677
});
25742678
2575-
// ---------------------------------------------------------------- syntax highlighting (C/C++)
2576-
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 ' +
2577-
'decltype default delete do dynamic_cast else enum explicit export extern false final for friend goto if inline mutable namespace new noexcept not nullptr ' +
2578-
'operator or override private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this ' +
2579-
'thread_local throw true try typedef typeid typename union using virtual volatile while NULL').split(' '));
2580-
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 ' +
2581-
'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(' '));
2582-
const TOK = /(\/\/.*$)|(\/\*)|("(?:\\.|[^"\\])*"?)|('(?:\\.|[^'\\])*'?)|(\b\d[\w.']*|\.\d[\w']*)|([A-Za-z_]\w*)(\s*\()?|([^\w\s"'\/]+|\/|\s+)/y;
2583-
2584-
// returns true if the line ends inside a block comment
2585-
function scanBlock(line, block) {
2586-
let i = 0;
2587-
const n = line.length;
2588-
while (i < n) {
2589-
if (block) {
2590-
const e = line.indexOf('*/', i);
2591-
if (e < 0) return true;
2592-
block = false; i = e + 2;
2593-
continue;
2594-
}
2595-
const c = line.charCodeAt(i);
2596-
if (c === 47 /* / */) {
2597-
const d = line.charCodeAt(i + 1);
2598-
if (d === 47) return false;
2599-
if (d === 42) { block = true; i += 2; continue; }
2600-
} else if (c === 34 || c === 39) {
2601-
i++;
2602-
while (i < n && line.charCodeAt(i) !== c) i += line.charCodeAt(i) === 92 ? 2 : 1;
2603-
}
2604-
i++;
2605-
}
2606-
return block;
2607-
}
2608-
2609-
function hl(line, st) {
2610-
if (line.length > 3000) return esc(line);
2611-
let out = '', pos = 0;
2612-
if (st.block) {
2613-
const e = line.indexOf('*/');
2614-
if (e < 0) return `<span class="t-co">${esc(line)}</span>`;
2615-
out += `<span class="t-co">${esc(line.slice(0, e + 2))}</span>`;
2616-
pos = e + 2; st.block = false;
2617-
}
2618-
if (pos === 0 && /^\s*#/.test(line)) {
2619-
const m = /^(\s*#\s*\w*)(.*)$/.exec(line);
2620-
out += `<span class="t-pp">${esc(m[1])}</span>`;
2621-
const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(m[2]);
2622-
if (inc) return out + esc(inc[1]) + `<span class="t-st">${esc(inc[2])}</span>` + hlRest(inc[3], st);
2623-
return out + hlRest(m[2], st);
2624-
}
2625-
return out + hlRest(line.slice(pos), st);
2626-
}
2627-
2628-
function hlRest(s, st) {
2629-
let out = '';
2630-
TOK.lastIndex = 0;
2631-
while (TOK.lastIndex < s.length) {
2632-
const start = TOK.lastIndex;
2633-
const m = TOK.exec(s);
2634-
if (!m) { out += esc(s.slice(start)); break; }
2635-
if (m[1]) out += `<span class="t-co">${esc(m[1])}</span>`;
2636-
else if (m[2]) {
2637-
const e = s.indexOf('*/', TOK.lastIndex);
2638-
if (e < 0) { out += `<span class="t-co">${esc(s.slice(start))}</span>`; st.block = true; break; }
2639-
out += `<span class="t-co">${esc(s.slice(start, e + 2))}</span>`;
2640-
TOK.lastIndex = e + 2;
2641-
} else if (m[3] || m[4]) out += `<span class="t-st">${esc(m[3] || m[4])}</span>`;
2642-
else if (m[5]) out += `<span class="t-nu">${esc(m[5])}</span>`;
2643-
else if (m[6]) {
2644-
const w = m[6];
2645-
if (KW.has(w)) out += `<span class="t-kw">${w}</span>`;
2646-
else if (TY.has(w)) out += `<span class="t-ty">${w}</span>`;
2647-
else if (m[7]) out += `<span class="t-fn">${w}</span>`;
2648-
else out += w;
2649-
if (m[7]) out += esc(m[7]);
2650-
} else out += esc(m[8]);
2651-
}
2652-
return out;
2653-
}
2654-
26552679
// ---------------------------------------------------------------- metrics
26562680
const METRIC_INFO = {
26572681
cyclomaticComplexity: ['v(G)', 'Cyclomatic complexity'],
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#!/usr/bin/env python3
2+
"""Test the JavaScript code of the Cppcheck Explorer report (reports/explorer/report.py) with node."""
3+
4+
import importlib.util
5+
import os
6+
import shutil
7+
import subprocess
8+
import sys
9+
10+
import pytest
11+
12+
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
13+
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(TEST_DIR)))
14+
REPORT_PY = os.path.join(ROOT_DIR, 'reports', 'explorer', 'report.py')
15+
16+
NODE = shutil.which('node')
17+
pytestmark = pytest.mark.skipif(NODE is None, reason='node is not installed')
18+
19+
XML = '''<?xml version="1.0" encoding="UTF-8"?>
20+
<results version="2">
21+
<cppcheck version="2.19 dev"/>
22+
<errors>
23+
<error id="uninitvar" severity="error" msg="Uninitialized variable: x" verbose="Uninitialized variable: x" cwe="457">
24+
<location file="a.cpp" line="3" column="12" info="Uninitialized variable: x"/>
25+
<symbol>x</symbol>
26+
</error>
27+
<error id="unusedVariable" severity="style" msg="Unused variable: y" verbose="Unused variable: y" cwe="563">
28+
<location file="a.cpp" line="2" column="9"/>
29+
<symbol>y</symbol>
30+
</error>
31+
</errors>
32+
</results>
33+
'''
34+
35+
36+
def load_report():
37+
spec = importlib.util.spec_from_file_location('explorer_report', REPORT_PY)
38+
module = importlib.util.module_from_spec(spec)
39+
spec.loader.exec_module(module)
40+
return module
41+
42+
43+
def run_node(args, env=None):
44+
p = subprocess.run([NODE] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
45+
universal_newlines=True, env=env, check=False)
46+
assert p.returncode == 0, p.stdout
47+
return p.stdout
48+
49+
50+
def test_lib(tmp_path):
51+
lib = tmp_path / 'lib.js'
52+
lib.write_text(load_report().JS_LIB, encoding='utf-8')
53+
env = dict(os.environ, EXPLORER_LIB=str(lib))
54+
run_node(['--test', os.path.join(TEST_DIR, 'lib.test.js')], env=env)
55+
56+
57+
def test_generated_report_js_syntax(tmp_path):
58+
(tmp_path / 'a.cpp').write_text('int f() {\n int y;\n int x; return x;\n}\n', encoding='utf-8')
59+
(tmp_path / 'results.xml').write_text(XML, encoding='utf-8')
60+
out = tmp_path / 'report'
61+
subprocess.run([sys.executable, REPORT_PY, str(tmp_path / 'results.xml'), '-o', str(out),
62+
'--source-dir', str(tmp_path)], check=True, stdout=subprocess.PIPE)
63+
for f in ('report.js', os.path.join('data', 'results.js')):
64+
run_node(['--check', str(out / f)])

0 commit comments

Comments
 (0)