From 9170f8cb6627320b61b097fef96b75a373f5790b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:18:35 -0800 Subject: [PATCH 1/8] fix(cli): escape Markdown and HTML metacharacters in GFM table cells MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `escape_gfm_cell` escaped only `\`, `|` and newlines, so a path's other metacharacters reached the rendered table as markup: an `a.py` became an element under a non-sanitising GFM renderer, `a&b.py` displayed as `a&b.py`, and `__init__.py` rendered as bold `init.py`. The helper is the one GFM escaper for the report, `check`'s `--summary-file` digest and `exemptions`, so every table shares the widened set: `< & ` * _ ~ [ ]` each take a backslash, which GFM renders as the literal character. The buffer is pre-sized by the escape count, since `_` is in most identifiers and the plain `s.len()` guess reallocated on most cells. The two existing tests that spelled a symbol with `_` now expect the escaped form; a new unit test and a report-level test pin the rendered output for each metacharacter. --- big-code-analysis-cli/src/check_format.rs | 72 ++++++++++++++----- big-code-analysis-cli/src/exemptions_tests.rs | 4 +- big-code-analysis-cli/src/markdown_report.rs | 21 ++++++ .../tests/check/check_stream_contract.rs | 4 +- 4 files changed, 80 insertions(+), 21 deletions(-) diff --git a/big-code-analysis-cli/src/check_format.rs b/big-code-analysis-cli/src/check_format.rs index fb80932ee..c62403e9a 100644 --- a/big-code-analysis-cli/src/check_format.rs +++ b/big-code-analysis-cli/src/check_format.rs @@ -559,28 +559,44 @@ fn write_top_offenders(out: &mut String, pairs: &[(Violation, Option)] } } -/// Escape `\`, `|`, and newlines in a GFM table cell. `|` is the -/// column separator; `\` must be escaped first so that escaping `|` -/// to `\|` doesn't accidentally interact with a literal backslash -/// already present in the cell (a path `a\|b` would otherwise -/// produce `a\\|b`, which GFM renders as `a\` followed by a column -/// break rather than the literal `a\|b`). Newlines and carriage -/// returns are collapsed to a single space — multi-line cells -/// would break the table layout entirely. +/// Escape a GFM table cell so its text renders verbatim. `|` is the +/// column separator, and a literal `\` is escaped too so that a path +/// `a\|b` renders as itself rather than as `a\` followed by a column +/// break — one backslash per metacharacter, never two, so a `\` already +/// in the cell can never pair with the one added for a following `|`. +/// Newlines and carriage returns are collapsed to a single space — +/// multi-line cells would break the table layout entirely. /// -/// `markdown_report::escape_cell` delegates here so the two GFM-table -/// emitters in this crate share one escaping policy (see issue #439). +/// The remaining escapes keep a path's *identity* intact in the rendered +/// output: `<` opens raw HTML (`a.py` became an +/// element under a non-sanitising renderer), `&` starts an entity +/// (`a&b.py` displayed as `a&b.py`), and `` ` `` / `*` / `_` / `~` / +/// `[` / `]` open code spans, emphasis, strikethrough and links +/// (`__init__.py` rendered as bold `init.py`). GFM honours a backslash +/// before any ASCII punctuation, so each renders as the literal character. +/// +/// `markdown_report::escape_cell`, `vcs_report` and `exemptions` all +/// route here so every GFM-table emitter in this crate shares one +/// escaping policy (see issue #439). pub(crate) fn escape_gfm_cell(s: &str) -> String { - let mut out = String::with_capacity(s.len()); + let needs_escape = |ch: char| { + matches!( + ch, + '\\' | '|' | '<' | '&' | '`' | '*' | '_' | '~' | '[' | ']' + ) + }; + // Size for every escape up front: `_` is in most identifiers and + // paths, so the plain `s.len()` guess reallocated on most cells. + let escapes = s.chars().filter(|&ch| needs_escape(ch)).count(); + let mut out = String::with_capacity(s.len() + escapes); for ch in s.chars() { - match ch { - // Escape `\` FIRST so the subsequent `|` → `\|` rule - // doesn't conflict with a literal backslash already in - // the cell. - '\\' => out.push_str("\\\\"), - '|' => out.push_str("\\|"), - '\n' | '\r' => out.push(' '), - _ => out.push(ch), + if needs_escape(ch) { + out.push('\\'); + out.push(ch); + } else if matches!(ch, '\n' | '\r') { + out.push(' '); + } else { + out.push(ch); } } out @@ -1363,4 +1379,22 @@ mod tests { assert_eq!(escape_gfm_cell("a\\b"), "a\\\\b"); assert_eq!(escape_gfm_cell("a\\|b"), "a\\\\\\|b"); } + + /// A path's Markdown and HTML metacharacters must render as the + /// literal path: unescaped, `` became an element under a + /// non-sanitising GFM renderer, `&` collapsed to `&`, and + /// `__init__.py` rendered as bold `init.py`. + #[test] + fn escape_gfm_cell_neutralises_markup_in_paths() { + assert_eq!( + escape_gfm_cell("a.py"), + "a\\.py" + ); + assert_eq!(escape_gfm_cell("a&b.py"), "a\\&b.py"); + assert_eq!(escape_gfm_cell("__init__.py"), "\\_\\_init\\_\\_.py"); + assert_eq!(escape_gfm_cell("x*y~z`w[v].rs"), "x\\*y\\~z\\`w\\[v\\].rs"); + // Ordinary paths are untouched: no escape is spent on a `.`, `/`, + // `-` or `#`, which GFM renders literally in a cell. + assert_eq!(escape_gfm_cell("src/a-b.c#1.rs"), "src/a-b.c#1.rs"); + } } diff --git a/big-code-analysis-cli/src/exemptions_tests.rs b/big-code-analysis-cli/src/exemptions_tests.rs index ab34aeca3..da83cf92d 100644 --- a/big-code-analysis-cli/src/exemptions_tests.rs +++ b/big-code-analysis-cli/src/exemptions_tests.rs @@ -260,8 +260,10 @@ fn a_lineless_baseline_entry_drops_the_line_in_every_format() { let md = report .render(OutputFormat::Markdown, "") .expect("markdown render"); + // The symbol's underscores are escaped so GFM renders them rather + // than reading `_one` as an emphasis opener. assert!( - md.contains("| src/lonely.rs | - | only_one | cognitive | 21 |"), + md.contains("| src/lonely.rs | - | only\\_one | cognitive | 21 |"), "got: {md}" ); diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index 4e455bc7f..2d45e889d 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -1936,6 +1936,27 @@ mod tests { ); } + /// A path cell neutralises Markdown and raw-HTML metacharacters so the + /// rendered table shows the path itself. Unescaped, `` became an + /// element under a non-sanitising GFM renderer, `&` collapsed to + /// `&`, and `__init__.py` rendered as bold `init.py`. + #[test] + fn cell_escaping_markup_in_paths() { + let path = "pkg/__init__&*.py"; + let mut f = make_summary("run", path, SpaceKind::Function, LANG::Python); + f.cyclomatic = 5.0; + let unit = make_summary(path, path, SpaceKind::Unit, LANG::Python); + let report = generate_report(&[unit, f], 20, SuppressionPolicy::Honor); + assert!( + report.contains("pkg/\\_\\_init\\_\\_\\\\&\\*.py"), + "path metacharacters not escaped:\n{report}" + ); + assert!( + !report.contains("| pkg/__init__ Date: Sat, 7 Nov 2026 10:20:31 -0800 Subject: [PATCH 2/8] fix(cli): align, sort and focus the HTML report's table headers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three defects in the inline CSS/JS every report page carries. Every `th` was `text-align:left` while `td.numeric` was right-aligned, so a numeric column's header sat flush-left over its numbers; numeric headers now take the same alignment, keyed on the `data-numeric` attribute the sorter already emits. The sort comparator mapped an empty cell to +Infinity, which placed it last ascending but first descending (and any other non-numeric text fell through to a comparator that returned 0 against every number — not a total preorder); a blank now parses to NaN and sorts last in both directions. And sorting was click-only on a non-focusable `th`: headers now carry `tabindex="0"`, sort on Enter / Space, show a focus ring, and both handlers ignore an event whose target is the header's documentation link, so Enter on the link (and the `click` a browser synthesizes to activate it) navigates instead of sorting. The sort decorates each row's key once rather than parsing per comparison. The script is tested by executing it: `tests/fixtures/ sort_script_harness.mjs` runs `INLINE_JS` under Node against a DOM stub whose collections carry the browser's method surface (`NodeList` has `forEach`, `HTMLCollection` neither), with a pre-ranked header and a child link, and the Rust test asserts the orders and event outcomes. It needs Node >= 22.7 (the `make plugin-test` floor), skips with a note locally and fails under `CI`. The book's claim that blanks sort "as positive infinity" is corrected and the on-page hint names the keyboard path. --- .pre-commit-config.yaml | 4 +- big-code-analysis-book/src/commands/report.md | 9 +- big-code-analysis-book/src/commands/vcs.md | 3 +- big-code-analysis-cli/src/html_report.rs | 165 +++++++++++++- .../src/html_report/sections.rs | 4 +- .../src/html_report/styling.rs | 37 ++- big-code-analysis-cli/src/markdown_report.rs | 3 +- ..._html_report__tests__html_report_rich.snap | 40 ++-- ...l_report__tests__html_report_two_lang.snap | 32 +-- ...s_report__tests__vcs_report_html_rich.snap | 8 +- ...port__tests__vcs_report_markdown_rich.snap | 6 +- .../tests/fixtures/sort_script_harness.mjs | 211 ++++++++++++++++++ 12 files changed, 458 insertions(+), 64 deletions(-) create mode 100644 big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5dd44f1a3..aae257e4e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -56,7 +56,9 @@ repos: - id: test name: test language: system - files: '\.rs$' + # The `.mjs` is the DOM-stub harness a Rust unit test drives, so an + # edit to it is an edit to that test. + files: '(\.rs|big-code-analysis-cli/tests/fixtures/.*\.mjs)$' entry: cargo test pass_filenames: false diff --git a/big-code-analysis-book/src/commands/report.md b/big-code-analysis-book/src/commands/report.md index 0219c40c7..a871ebebf 100644 --- a/big-code-analysis-book/src/commands/report.md +++ b/big-code-analysis-book/src/commands/report.md @@ -245,10 +245,11 @@ bca report --paths /path/to/project \ html --top 10 --output report.html ``` -Click any column header to sort that table ascending, click again to -toggle descending. Each table sorts independently. Empty cells (where a -metric was not measured) sort as if they were positive infinity, which -keeps "no data" rows out of the visible top of a hotspot. +Click any column header — or Tab to it and press Enter or Space — to +sort that table ascending, and again to toggle descending. Each table +sorts independently. Empty cells (where a metric was not measured) sort +last in both directions, so "no data" rows never surface at the top of +a hotspot. Hover (or keyboard-focus, where the browser supports it) any metric column header (`SLOC`, `MI`, `CC`, `ABC`, `WMC`, `NPA`, `NPM`, diff --git a/big-code-analysis-book/src/commands/vcs.md b/big-code-analysis-book/src/commands/vcs.md index da83b6703..9bd2c57d2 100644 --- a/big-code-analysis-book/src/commands/vcs.md +++ b/big-code-analysis-book/src/commands/vcs.md @@ -76,7 +76,8 @@ bca vcs --top 50 --format markdown --output vcs.md ``` `--format html` produces a self-contained, sortable page styled like -`bca report html` (click any column header to re-sort); `--format +`bca report html` (click any column header, or focus it and press +Enter, to re-sort); `--format markdown` produces the same ranked table as [GitHub-Flavored Markdown](https://github.github.com/gfm/). Both render every signal column, the same data the structured formats carry. The diff --git a/big-code-analysis-cli/src/html_report.rs b/big-code-analysis-cli/src/html_report.rs index 3f7d9c919..f3fb4082d 100644 --- a/big-code-analysis-cli/src/html_report.rs +++ b/big-code-analysis-cli/src/html_report.rs @@ -155,7 +155,10 @@ fn write_table_head<'t>( } else { "" }; - let _ = write!(out, "` can never take focus. + let _ = write!(out, " must carry a right-align rule" + ); + assert!(INLINE_CSS.contains("table.hotspot td.numeric{text-align:right")); + // The selector keys on the attribute the sorter already emits, so + // the real output carries it on exactly the numeric headers. + let out = generate_html_report(&rust_fixture(), 20, SuppressionPolicy::Honor); + assert!(out.contains("File"), + "identity headers stay text-aligned (no data-numeric):\n{out}" + ); + } + + /// Sorting is reachable from the keyboard: every header is in the tab + /// order and the handler fires on Enter / Space as well as click. + /// Before, a bare `` could never take focus, and the only + /// focusable thing in a metric header was its documentation link. + #[test] + fn headers_are_focusable_and_sort_on_keyboard() { + let out = generate_html_report(&rust_fixture(), 20, SuppressionPolicy::Honor); + // `` only — `` shares the prefix. + let total = out.matches("").count(); + assert!(total > 0); + assert_eq!( + out.matches(" must be focusable" + ); + assert!(INLINE_JS.contains("th.addEventListener('keydown'")); + assert!(INLINE_JS.contains("e.key==='Enter'||e.key===' '")); + // A metric header holds a documentation link; Enter on *that* + // must follow the link, not sort. The handler ignores a keydown + // that bubbled from a child, before it reads the key. + let guard = INLINE_JS + .find("if(e.target!==th)return;") + .expect("target guard"); + let key = INLINE_JS.find("e.key==='Enter'").expect("key test"); + assert!(guard < key, "the target guard must run before the key test"); + assert!( + INLINE_CSS.contains("table.hotspot th:focus-visible{outline:"), + "a focused header must be visibly focused" + ); + } + + /// An empty numeric cell (the overview's `Avg MI` when no file carries + /// code) sorts last in *both* directions. The previous comparator + /// mapped it to +Infinity, which sorted it last ascending and first + /// descending. + #[test] + fn js_sorts_blank_numeric_cells_last_in_both_directions() { + assert!( + INLINE_JS.contains("function num(s){return s===''?NaN:parseFloat("), + "a blank must parse to NaN, never a signed infinity" + ); + // The NaN arms return a fixed order that ignores `sign`, which is + // what makes the placement direction-independent. + assert!(INLINE_JS.contains("if(ae&&be)return 0;if(ae)return 1;if(be)return -1;")); + let signed_tail = "if(a.kb.k)return 1*sign;"; + let nan_arms = INLINE_JS.find("if(ae)return 1;").expect("NaN arm"); + let signed = INLINE_JS.find(signed_tail).expect("signed compare"); + assert!( + nan_arms < signed, + "the NaN arms must run before the signed compare" + ); + } + + /// Runs [`INLINE_JS`] under Node against a DOM stub + /// (`tests/fixtures/sort_script_harness.mjs`) and asserts what it + /// *does*: the substring tests above pin the spelling and would pass + /// a script that, say, guarded the wrong event target. The harness + /// needs nothing newer than Node 14; the floor is `make plugin-test`'s + /// 22.7 so one runtime serves every Node-driven test. Without it the + /// test skips locally with a note, and **fails** under `CI` — the + /// `plugin-test` posture, since under nextest a skipped test's stderr + /// is never shown and a skip would read as a pass. `ci.yml` installs + /// Node before every job that runs this crate's tests. + #[test] + fn inline_sort_script_behaves_under_a_dom_stub() { + let node_ok = std::process::Command::new("node") + .arg("-e") + .arg( + "const [a,b]=process.versions.node.split('.').map(Number);\ + process.exit(a>22||(a===22&&b>=7)?0:1)", + ) + .status() + .is_ok_and(|s| s.success()); + if !node_ok { + assert!( + std::env::var_os("CI").is_none(), + "Node >= 22.7 is required for inline_sort_script_behaves_under_a_dom_stub in CI" + ); + eprintln!( + "node >= 22.7 not found; skipping inline_sort_script_behaves_under_a_dom_stub" + ); + return; + } + let dir = tempfile::tempdir().expect("tempdir"); + let script = dir.path().join("sort.js"); + std::fs::write(&script, INLINE_JS).expect("write script"); + let harness = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/sort_script_harness.mjs"); + let out = std::process::Command::new("node") + .arg(&harness) + .arg(&script) + .output() + .expect("run node"); + assert!( + out.status.success(), + "harness failed:\n{}", + String::from_utf8_lossy(&out.stderr) + ); + let got: serde_json::Value = + serde_json::from_slice(&out.stdout).expect("harness emits JSON"); + let strs = |key: &str| -> Vec { + got[key] + .as_array() + .unwrap_or_else(|| panic!("{key} is an array: {got}")) + .iter() + .map(|v| v.as_str().expect("string cell").to_owned()) + .collect() + }; + // The pre-ranked column ships `aria-sort="descending"`, so its + // first activation is a reversal to ascending. + assert_eq!(strs("rankedFirstClick"), ["1.0", "3.0", "7.0", "9.0"]); + assert_eq!(got["rankedAriaAfterFirstClick"], "ascending"); + // Numeric sort parses through the thousands separator and keeps + // the blank last in both directions. + assert_eq!(strs("numericAscending"), ["5", "12", "1,000", ""]); + assert_eq!(got["ariaAfterFirstClick"], "ascending"); + assert_eq!(strs("numericDescending"), ["1,000", "12", "5", ""]); + assert_eq!(got["ariaAfterSecondClick"], "descending"); + // A text sort is lexical, and sorting one column clears the + // other's `aria-sort`. + assert_eq!(strs("textAscending"), ["a.rs", "b.rs", "c.rs", "d.rs"]); + assert!(got["numericAriaCleared"].is_null(), "{got}"); + assert!(got["rankedAriaCleared"].is_null(), "{got}"); + // Keyboard: Enter / Space on the header sort and swallow the key. + assert_eq!(strs("enterOnHeaderSorts"), ["d.rs", "c.rs", "b.rs", "a.rs"]); + assert_eq!(got["enterOnHeaderPrevented"], true); + assert_eq!(strs("spaceOnHeaderSorts"), ["5", "12", "1,000", ""]); + assert_eq!(got["spaceOnHeaderPrevented"], true); + // Enter on the header's documentation link neither sorts nor + // cancels the link's own navigation — including the `click` a + // browser synthesizes to activate the link, which bubbles to the + // header's click handler. A mouse click on the link is likewise + // the link's alone. + assert_eq!(got["enterOnLinkPrevented"], false, "{got}"); + assert_eq!(got["enterOnLinkMovedRows"], false, "{got}"); + assert_eq!(got["clickOnLinkMovedRows"], false, "{got}"); + assert_eq!(got["tabPrevented"], false); + } + #[test] fn js_numeric_sort_strips_thousands_separators() { // Regression: numeric cells use `thousands()` to insert commas diff --git a/big-code-analysis-cli/src/html_report/sections.rs b/big-code-analysis-cli/src/html_report/sections.rs index 5ce46bae2..212cd4a9d 100644 --- a/big-code-analysis-cli/src/html_report/sections.rs +++ b/big-code-analysis-cli/src/html_report/sections.rs @@ -244,7 +244,9 @@ pub(crate) fn write_overview_table( // One discoverability hint near the first table: the columns are // sortable, which is otherwise invisible until a reader happens to // click a header (issue #622). - let _ = out.write_str("

Click a column header to sort any table.

\n"); + let _ = out.write_str( + "

Click a column header \u{2014} or Tab to it and press Enter \u{2014} to sort any table.

\n", + ); let mut rows: Vec> = Vec::with_capacity(by_lang.len()); for (&lang_name, lang_summaries) in by_lang { rows.push(lang_overview_row(lang_name, lang_summaries)); diff --git a/big-code-analysis-cli/src/html_report/styling.rs b/big-code-analysis-cli/src/html_report/styling.rs index cabde2fd3..e9312c6a1 100644 --- a/big-code-analysis-cli/src/html_report/styling.rs +++ b/big-code-analysis-cli/src/html_report/styling.rs @@ -185,6 +185,8 @@ table.hotspot th:hover{background:#e5e5e5}\ table.hotspot th[aria-sort=ascending]::after{content:\" \\2191\"}\ table.hotspot th[aria-sort=descending]::after{content:\" \\2193\"}\ table.hotspot tr:nth-child(even) td{background:#fafafa}\ +table.hotspot th[data-numeric=\"1\"]{text-align:right}\ +table.hotspot th:focus-visible{outline:2px solid #3d82cc;outline-offset:-2px}\ table.hotspot td.numeric{text-align:right;font-variant-numeric:tabular-nums}\ table.hotspot td.risk-heat-0,table.hotspot td.risk-heat-1,\ table.hotspot td.risk-heat-2,table.hotspot td.risk-heat-3,\ @@ -277,35 +279,46 @@ pub(crate) fn language_palette_slug(lang_name: &str) -> &'static str { pub(crate) const INLINE_JS: &str = "\ (function(){\ -function num(s){return s===''?Number.POSITIVE_INFINITY:parseFloat(s.replace(/,/g,''));}\ +function num(s){return s===''?NaN:parseFloat(s.replace(/,/g,''));}\ document.querySelectorAll('table.hotspot').forEach(function(table){\ var headers=table.querySelectorAll('thead th');\ headers.forEach(function(th,idx){\ -th.addEventListener('click',function(){sort(table,idx,th);});\ +th.addEventListener('click',function(e){\ +if(e.target!==th)return;\ +sort(table,idx,th);\ +});\ +th.addEventListener('keydown',function(e){\ +if(e.target!==th)return;\ +if(e.key==='Enter'||e.key===' '){e.preventDefault();sort(table,idx,th);}\ +});\ });\ });\ function sort(tbl,idx,th){\ var tbody=tbl.tBodies[0];\ if(!tbody)return;\ -var rows=Array.prototype.slice.call(tbody.rows);\ var numeric=th.dataset.numeric==='1';\ var dir=th.getAttribute('aria-sort')==='ascending'?'descending':'ascending';\ tbl.querySelectorAll('thead th').forEach(function(h){h.removeAttribute('aria-sort');});\ th.setAttribute('aria-sort',dir);\ var sign=dir==='ascending'?1:-1;\ -rows.sort(function(a,b){\ -var av=a.cells[idx].textContent;\ -var bv=b.cells[idx].textContent;\ +var keyed=Array.prototype.map.call(tbody.rows,function(r){\ +var t=r.cells[idx].textContent;\ +return {r:r,k:numeric?num(t):t};\ +});\ +keyed.sort(function(a,b){\ if(numeric){\ -var an=num(av);\ -var bn=num(bv);\ -if(anbn)return 1*sign;\ +var ae=isNaN(a.k);\ +var be=isNaN(b.k);\ +if(ae&&be)return 0;\ +if(ae)return 1;\ +if(be)return -1;\ +if(a.kb.k)return 1*sign;\ return 0;\ }\ -return av.localeCompare(bv)*sign;\ +return a.k.localeCompare(b.k)*sign;\ });\ -rows.forEach(function(r){tbody.appendChild(r);});\ +keyed.forEach(function(e){tbody.appendChild(e.r);});\ }\ })();\ "; diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index 2d45e889d..fdf8cb72e 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -1063,7 +1063,8 @@ pub(crate) fn lang_overview_row( thousands(func_count), // An empty cell, not `n/a`, when no file had code to measure: the // HTML table sorter reads an empty cell as "no value" and sorts it - // last, where any other text would parse as NaN. + // last in either direction; any other text would parse as NaN and + // sort the same way, but read as a value in the cell. avg_mi.map_or_else(String::new, |mi| format!("{mi:.1}")), format!("{avg_cc:.1}"), format!("{avg_cog:.1}"), diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap index 413cbffa0..3c91a8f0c 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap @@ -8,7 +8,7 @@ expression: out Code Quality Metrics Summary — big-code-analysis - +

Code Quality Metrics Summary

@@ -65,10 +65,10 @@ expression: out

Per-language overview

-

Click a column header to sort any table.

+

Click a column header — or Tab to it and press Enter — to sort any table.

- + @@ -88,7 +88,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
Python1120228.08.59.0
Rust2280821.423.422.6
- + @@ -98,7 +98,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
FileMISLOCTokens
src/main.py28.0120800
- + @@ -109,7 +109,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
FunctionFileLineCCCognitiveSLOCTokens
mainsrc/main.py10101260300
load_datasrc/main.py407635180
- + @@ -119,7 +119,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
FunctionFileLineCognitiveCCSLOCTokens
mainsrc/main.py10121060300
load_datasrc/main.py406735180
- + @@ -129,7 +129,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
FunctionFileLineEffortVolumeEst. BugsSLOCTokens
mainsrc/main.py102,0001,0000.3360300
load_datasrc/main.py401,2006000.2335180
- + @@ -139,7 +139,7 @@ expression: out

Many parameters hotspots (top 5 by Args)

FunctionFileLineSLOCTokensCCCognitive
FunctionFileLineSLOCTokensCCCognitive
mainsrc/main.py10603001012
load_datasrc/main.py403518076
- + @@ -148,7 +148,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineArgsSLOCTokens
FunctionFileLineArgsSLOCTokens
load_datasrc/main.py40435180
- + @@ -173,7 +173,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

FunctionFileLineABCSLOCTokens
FunctionFileLineABCSLOCTokens
mainsrc/main.py109.060300
load_datasrc/main.py407.035180
- + @@ -184,7 +184,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
FileMISLOCTokens
src/lib.rs12.02001,500
src/util.rs45.080600
- + @@ -198,7 +198,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
FunctionFileLineCCCognitiveSLOCTokens
process_requestsrc/lib.rs102530150900
validate_inputsrc/lib.rs402024120700
- + @@ -211,7 +211,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
FunctionFileLineCognitiveCCSLOCTokens
secret_internalsrc/lib.rs22080993002,000
process_requestsrc/lib.rs103025150900
- + @@ -224,7 +224,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
FunctionFileLineEffortVolumeEst. BugsSLOCTokens
secret_internalsrc/lib.rs22020,00010,0003.303002,000
process_requestsrc/lib.rs109,0004,5000.83150900
- + @@ -237,7 +237,7 @@ expression: out

Many parameters hotspots (top 5 by Args)

FunctionFileLineSLOCTokensCCCognitive
FunctionFileLineSLOCTokensCCCognitive
secret_internalsrc/lib.rs2203002,0009980
process_requestsrc/lib.rs101509002530
- + @@ -249,7 +249,7 @@ expression: out

Type hotspots (top 5 by WMC)

FunctionFileLineArgsSLOCTokens
FunctionFileLineArgsSLOCTokens
secret_internalsrc/lib.rs22083002,000
process_requestsrc/lib.rs106150900
- + @@ -258,7 +258,7 @@ expression: out

Exit points hotspots (top 5 by Exits)

TypeFileLineWMCMethodsNPANPMSLOCTokens
TypeFileLineWMCMethodsNPANPMSLOCTokens
Widgetsrc/lib.rs250408261801,100
- + @@ -270,7 +270,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineExitsCCSLOCTokens
FunctionFileLineExitsCCSLOCTokens
secret_internalsrc/lib.rs22010993002,000
handle_eventsrc/lib.rs10061270400
- + @@ -304,6 +304,6 @@ expression: out
Comment ratio
Comment ratio: comment lines as a percentage of source lines (CLOC / SLOC).
- + diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap index 92a3bca0d..107fc66f3 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap @@ -8,7 +8,7 @@ expression: out Code Quality Metrics Summary — big-code-analysis - +

Code Quality Metrics Summary

@@ -55,10 +55,10 @@ expression: out

No major quality concerns detected.

Per-language overview

-

Click a column header to sort any table.

+

Click a column header — or Tab to it and press Enter — to sort any table.

FunctionFileLineABCSLOCTokens
FunctionFileLineABCSLOCTokens
secret_internalsrc/lib.rs22050.03002,000
process_requestsrc/lib.rs1022.0150900
- + @@ -76,7 +76,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
Python120150.03.02.0
Rust120250.03.02.0
- + @@ -86,7 +86,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
FileMISLOCTokens
src/main.py50.02030
- + @@ -96,7 +96,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
FunctionFileLineCCCognitiveSLOCTokens
greetsrc/main.py1322030
- + @@ -105,7 +105,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
FunctionFileLineCognitiveCCSLOCTokens
greetsrc/main.py1232030
- + @@ -114,7 +114,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
FunctionFileLineEffortVolumeEst. BugsSLOCTokens
greetsrc/main.py15001000.102030
- + @@ -123,7 +123,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineSLOCTokensCCCognitive
FunctionFileLineSLOCTokensCCCognitive
greetsrc/main.py1203032
- + @@ -141,7 +141,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

FunctionFileLineABCSLOCTokens
FunctionFileLineABCSLOCTokens
greetsrc/main.py15.02030
- + @@ -151,7 +151,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
FileMISLOCTokens
src/lib.rs50.02030
- + @@ -162,7 +162,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
FunctionFileLineCCCognitiveSLOCTokens
computesrc/lib.rs1322030
do_stuffsrc/lib.rs1322030
- + @@ -172,7 +172,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
FunctionFileLineCognitiveCCSLOCTokens
computesrc/lib.rs1232030
do_stuffsrc/lib.rs1232030
- + @@ -182,7 +182,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
FunctionFileLineEffortVolumeEst. BugsSLOCTokens
computesrc/lib.rs15001000.102030
do_stuffsrc/lib.rs15001000.102030
- + @@ -192,7 +192,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineSLOCTokensCCCognitive
FunctionFileLineSLOCTokensCCCognitive
computesrc/lib.rs1203032
do_stuffsrc/lib.rs1203032
- + @@ -223,6 +223,6 @@ expression: out
Comment ratio
Comment ratio: comment lines as a percentage of source lines (CLOC / SLOC).
- + diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap index e18ffae4b..5cf8d9406 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap @@ -8,7 +8,7 @@ expression: html Change-history risk — big-code-analysis - +

Change-history risk

@@ -18,7 +18,7 @@ expression: html
FunctionFileLineABCSLOCTokens
FunctionFileLineABCSLOCTokens
computesrc/lib.rs15.02030
do_stuffsrc/lib.rs15.02030
- + @@ -32,7 +32,7 @@ expression: html

Repository: 2 (over 3 files, coverage threshold 0.50).

RankFileRiskCommits (recent)Commits (long)Churn (recent)Churn (long)Authors (recent)Authors (long)OwnershipBurstBug fixesSec fixesRevertsAge (d)Last mod (d)Change entropy (recent)Change entropy (long)Co-change entropy (recent)Co-change entropy (long)Hotspot
RankFileRiskCommits (recent)Commits (long)Churn (recent)Churn (long)Authors (recent)Authors (long)OwnershipBurstBug fixesSec fixesRevertsAge (d)Last mod (d)Change entropy (recent)Change entropy (long)Co-change entropy (recent)Co-change entropy (long)Hotspot
1src/hot.rs9.450602,0005,000230.750.5041020051.502.500.801.20123.0
2src/warm.rs6.120308002,000230.750.5041020051.502.500.801.20
- + @@ -67,6 +67,6 @@ expression: html - + diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap index 228322e0d..6057ce13c 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap @@ -28,9 +28,9 @@ _Bus factor: the number of authors whose departure would orphan more than half t ## Legend - **Risk** — Composite change-history risk score: recent churn and commit frequency dominate, raised by author dilution, bug-/security-fix history, and newness. Ordinal: only relative ranks carry meaning, not the absolute value. -- **Commits (recent)** — Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: commits_recent. -- **Churn (recent)** — Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: churn_recent. -- **Authors (recent)** — Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: authors_recent. +- **Commits (recent)** — Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: commits\_recent. +- **Churn (recent)** — Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: churn\_recent. +- **Authors (recent)** — Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: authors\_recent. - **Ownership** — Top-author edit share (0–1): fraction of edits by the single most active author; lower means more diluted ownership. - **Bug fixes** — Commits classified as bug fixes (by message) within the long window. - **Hotspot** — Complexity × recent churn: high-complexity files that also change often. Shown only when AST metrics are joined (e.g. report --vcs); omitted by plain bca vcs. diff --git a/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs b/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs new file mode 100644 index 000000000..552a92fed --- /dev/null +++ b/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs @@ -0,0 +1,211 @@ +// Executes the report's inline sort script against a minimal DOM stub and +// prints what it did, so a Rust test can assert on behaviour rather than +// on the script's spelling. Driven by `html_report::tests:: +// inline_sort_script_behaves_under_a_dom_stub`; not a `node --test` file. +// +// Usage: node sort_script_harness.mjs +// +// The stub implements only what the script touches: `document +// .querySelectorAll('table.hotspot')`, `thead th` lookup, `tBodies`, +// `rows`, `cells`, `textContent`, `dataset`, the `aria-sort` attribute, +// `addEventListener` and `appendChild`. Collections are array-likes with +// the browser's method surface — `NodeList` has `forEach` but no `map`, +// `HTMLCollection` has neither — so a script that reaches for an Array +// method fails here as it would in a browser. `textContent` is a plain +// per-node string, not the concatenation of descendants a browser +// computes: a `
DirectoryBus factorFiles
DirectoryBus factorFiles
docs11
src22
` with a child `` reads `""`, which is fine while +// the script never reads a header's text. One table carries a numeric +// column whose cells are `5`, `12`, `` (blank) and `1,000` and a text +// column; its first header holds a child link, as the metric headers +// in the real page do, and its third ships `aria-sort="descending"`, +// as the pre-ranked column of every hotspot table does. + +import { readFileSync } from "node:fs" + +const script = readFileSync(process.argv[2], "utf8") + +// An array-like: indices and `length`, plus `forEach` where the browser +// collection has it. No `map`, `filter`, `slice` or `sort`. +function collection(items, { forEach = false } = {}) { + const c = Object.create(null) + items.forEach((n, i) => { + c[i] = n + }) + c.length = items.length + if (forEach) c.forEach = (fn) => items.forEach(fn) + return c +} + +class Node { + // Private so no reader gets a real Array; `children` below is the + // browser's `HTMLCollection` shape. + #children + constructor(tag, text = "") { + this.tag = tag + this.textContent = text + this.#children = [] + this.attrs = new Map() + this.listeners = new Map() + this.parent = null + } + get children() { + return collection(this.#children) + } + // `dataset.foo` reads the `data-foo` attribute, as in a browser. + get dataset() { + const attrs = this.attrs + return new Proxy( + {}, + { + get: (_, key) => (typeof key === "string" ? (attrs.get(`data-${key}`) ?? undefined) : undefined), + }, + ) + } + appendChild(child) { + if (child.parent) child.parent.#children.splice(child.parent.#children.indexOf(child), 1) + child.parent = this + this.#children.push(child) + return child + } + getAttribute(name) { + return this.attrs.has(name) ? this.attrs.get(name) : null + } + setAttribute(name, value) { + this.attrs.set(name, String(value)) + } + removeAttribute(name) { + this.attrs.delete(name) + } + addEventListener(type, fn) { + if (!this.listeners.has(type)) this.listeners.set(type, []) + this.listeners.get(type).push(fn) + } + // Bubbling dispatch: the event's `target` is the node dispatched on, + // listeners run from the target up through its ancestors. + dispatch(type, event) { + event.target = this + event.defaultPrevented = false + event.preventDefault = () => { + event.defaultPrevented = true + } + for (let node = this; node; node = node.parent) { + for (const fn of node.listeners.get(type) ?? []) fn(event) + } + return event + } + querySelectorAll(selector) { + const out = [] + const walk = (node) => { + for (const child of node.#children) { + if (matches(child, selector)) out.push(child) + walk(child) + } + } + walk(this) + return collection(out, { forEach: true }) + } + // Each getter exists only on the element the DOM defines it for, so + // a script reading `tbl.rows` or `tbody.children` fails here by name + // rather than as an empty readback that reads like a sort bug. + get tBodies() { + this.only("table", "tBodies") + return collection(this.#children.filter((c) => c.tag === "tbody")) + } + get rows() { + this.only(["tbody", "thead", "table"], "rows") + return collection(this.#children.filter((c) => c.tag === "tr")) + } + get cells() { + this.only("tr", "cells") + return collection(this.#children.filter((c) => c.tag === "td" || c.tag === "th")) + } + only(tags, prop) { + if (![tags].flat().includes(this.tag)) throw new Error(`stub does not model <${this.tag}>.${prop}`) + } +} + +function matches(node, selector) { + switch (selector) { + case "table.hotspot": + return node.tag === "table" && node.attrs.get("class") === "hotspot" + case "thead th": + return node.tag === "th" && node.parent?.parent?.tag === "thead" + default: + throw new Error(`stub does not model selector ${selector}`) + } +} + +const document = new Node("document") +const table = document.appendChild(new Node("table")) +table.setAttribute("class", "hotspot") +const thead = table.appendChild(new Node("thead")) +const headRow = thead.appendChild(new Node("tr")) +const numericTh = headRow.appendChild(new Node("th")) +numericTh.setAttribute("data-numeric", "1") +const link = numericTh.appendChild(new Node("a", "SLOC")) +const textTh = headRow.appendChild(new Node("th", "File")) +const rankedTh = headRow.appendChild(new Node("th", "Risk")) +rankedTh.setAttribute("data-numeric", "1") +rankedTh.setAttribute("aria-sort", "descending") +const tbody = table.appendChild(new Node("tbody")) +for (const [num, text, risk] of [ + ["5", "b.rs", "9.0"], + ["12", "a.rs", "7.0"], + ["", "d.rs", "3.0"], + ["1,000", "c.rs", "1.0"], +]) { + const tr = tbody.appendChild(new Node("tr")) + tr.appendChild(new Node("td", num)) + tr.appendChild(new Node("td", text)) + tr.appendChild(new Node("td", risk)) +} + +// The script reads `document` as a free global. +new Function("document", script)(document) + +const column = (idx) => Array.from(tbody.rows, (r) => r.cells[idx].textContent) +const out = {} + +// The pre-ranked column announces `descending` at render time, so its +// first activation must reverse to `ascending`, and clear nothing else +// since no other header is sorted yet. +rankedTh.dispatch("click", {}) +out.rankedFirstClick = column(2) +out.rankedAriaAfterFirstClick = rankedTh.getAttribute("aria-sort") + +numericTh.dispatch("click", {}) +out.numericAscending = column(0) +out.ariaAfterFirstClick = numericTh.getAttribute("aria-sort") +numericTh.dispatch("click", {}) +out.numericDescending = column(0) +out.ariaAfterSecondClick = numericTh.getAttribute("aria-sort") + +textTh.dispatch("click", {}) +out.textAscending = column(1) +out.numericAriaCleared = numericTh.getAttribute("aria-sort") +out.rankedAriaCleared = rankedTh.getAttribute("aria-sort") + +// Keyboard on the header itself sorts and swallows the key's default. +const enterOnHeader = textTh.dispatch("keydown", { key: "Enter" }) +out.enterOnHeaderSorts = column(1) +out.enterOnHeaderPrevented = enterOnHeader.defaultPrevented +const spaceOnHeader = numericTh.dispatch("keydown", { key: " " }) +out.spaceOnHeaderSorts = column(0) +out.spaceOnHeaderPrevented = spaceOnHeader.defaultPrevented +// Enter on the child link bubbles to the header; the link must keep its +// default (navigation) and the order must not move. A browser activates +// an anchor whose Enter was not cancelled by synthesizing a `click` on +// it, which bubbles to the header too, so model that second event. +const before = column(0) +const enterOnLink = link.dispatch("keydown", { key: "Enter" }) +out.enterOnLinkPrevented = enterOnLink.defaultPrevented +if (!enterOnLink.defaultPrevented) link.dispatch("click", {}) +out.enterOnLinkMovedRows = column(0).join() !== before.join() +// A mouse click on the link is the link's too. +link.dispatch("click", {}) +out.clickOnLinkMovedRows = column(0).join() !== before.join() +// An unrelated key does nothing. +const tab = numericTh.dispatch("keydown", { key: "Tab" }) +out.tabPrevented = tab.defaultPrevented + +process.stdout.write(JSON.stringify(out)) From a12aa933b38be626dc533f594dd0b88a959eb688 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:20:38 -0800 Subject: [PATCH 3/8] ci: install Node before every job that runs the CLI crate's tests The inline-sort-script test fails under `CI` when Node >= 22.7 is absent rather than skipping, since under nextest a skipped test's stderr is never shown and a skip would read as a pass. `test` ran nextest before its `setup-node` step, and the `coverage` and the two `(cli)` `feature-matrix` legs had none, so each would have passed or failed on whatever Node the runner image happened to ship. Node is now provisioned ahead of the test run in all three jobs. --- .github/workflows/ci.yml | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 396003ae1..d02dd757b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -277,6 +277,16 @@ jobs: - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: tool: cargo-nextest + # Node is installed before the Rust tests, not only for the agent + # hook tests below: `html_report::tests::inline_sort_script_behaves_ + # under_a_dom_stub` runs the report's inline sort script under Node + # and, with `CI` set, fails rather than skips when Node is absent — + # so the pinned runtime, not whatever the image ships, is what it + # sees. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + check-latest: true # nextest runs the lib / bins / integration tests and writes the JUnit # report to target/nextest/ci/junit.xml (see .config/nextest.toml). It # does not run doctests — those are covered by the next step. @@ -287,10 +297,6 @@ jobs: # exercising the workspace's documentation examples. - name: cargo test --doc run: cargo test --doc --all-features --workspace --locked - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: "24" - check-latest: true - name: Build analyzer for plugin integration tests run: cargo build -p big-code-analysis-cli --all-features --locked - name: Agent hook tests with the checkout analyzer @@ -408,6 +414,13 @@ jobs: - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: tool: cargo-nextest@0.9.146,cargo-llvm-cov@0.9.1 + # The instrumented run below is the same test set as the `test` job, + # including the Node-driven inline-sort-script test, which fails + # under `CI` when Node is missing rather than skipping. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + check-latest: true - name: Record coverage provenance run: | { @@ -622,6 +635,14 @@ jobs: - uses: taiki-e/install-action@86f7a0ffb25f40114606501a311ebcfaf882ea32 # v2.88.0 with: tool: cargo-nextest + # The two `(cli)` legs run the CLI crate's lib tests, one of which + # drives the report's inline sort script under Node and fails under + # `CI` when Node is absent — on every leg, so the verdict never + # depends on what the runner image happens to ship. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + check-latest: true # The one thing a partial feature set breaks that the clippy run # above cannot see (#1472): a test gated on the union of its rows # must be *absent* when none of those features is enabled, not From 56499a23336469af7357cb1c45299c1972e691c2 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:21:29 -0800 Subject: [PATCH 4/8] fix(cli): render shared Markdown notes as HTML instead of showing backticks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Notes written once as Markdown prose and emitted by both renderers reached the HTML page HTML-escaped but otherwise verbatim, so the advisory provenance read "sourced from the `bca.toml` `[thresholds]` table" with literal backticks. `note_html` escapes, then turns each paired backtick span into ``; an odd count leaves the note untouched. It is the one policy for every crate-authored note and legend definition — the provenance line, `MI_NOTE`, the actionable and fully-suppressed captions, the VCS shallow-clone note and every legend `
` — so a backtick added to a tooltip tomorrow renders the same way. The Markdown legend writer now emits definitions as-is rather than through the table-cell escaper, which the widened escape set would have turned `commits_recent` into `commits\_recent`; the VCS wire keys are spelled as code spans instead, so both renderers show them literally. --- big-code-analysis-cli/src/html_report.rs | 30 +++++++++++++++++++ .../src/html_report/sections.rs | 15 ++++++---- .../src/html_report/styling.rs | 26 ++++++++++++++++ big-code-analysis-cli/src/markdown_report.rs | 12 +++++--- .../src/markdown_report/advisory.rs | 5 +++- ..._html_report__tests__html_report_rich.snap | 6 ++-- ...l_report__tests__html_report_two_lang.snap | 6 ++-- ...s_report__tests__vcs_report_html_rich.snap | 22 +++++++------- ...port__tests__vcs_report_markdown_rich.snap | 6 ++-- big-code-analysis-cli/src/vcs_report.rs | 24 +++++++-------- 10 files changed, 109 insertions(+), 43 deletions(-) diff --git a/big-code-analysis-cli/src/html_report.rs b/big-code-analysis-cli/src/html_report.rs index f3fb4082d..a057d94db 100644 --- a/big-code-analysis-cli/src/html_report.rs +++ b/big-code-analysis-cli/src/html_report.rs @@ -489,6 +489,36 @@ mod tests { assert_eq!(escaped, "a&b<c>d"e'f"); } + /// A note shared with the Markdown report renders its backtick spans + /// as `` instead of showing the literal backticks, and is still + /// HTML-escaped inside them. + #[test] + fn note_html_turns_backtick_spans_into_code() { + assert_eq!( + note_html("sourced from the `bca.toml` `[thresholds]` table."), + "sourced from the bca.toml [thresholds] table." + ); + assert_eq!(note_html("x `` z"), "x <y> z"); + // An odd count of backticks leaves one unpaired, with no span to + // close, so the note is left untouched rather than half-converted. + assert_eq!(note_html("odd ` tick"), "odd ` tick"); + assert_eq!(note_html("a `b` `c"), "a `b` `c"); + assert_eq!(note_html("plain"), "plain"); + // The advisory provenance line is what motivated this: the HTML + // report showed "the `bca.toml` `[thresholds]` table" verbatim. + let out = generate_html_report(&rust_fixture(), 20, SuppressionPolicy::Honor); + assert!( + !out.contains("`bca"), + "no literal backtick from a shared note may reach the page:\n{out}" + ); + // The fixture renders under the built-in defaults, so the line is + // the `Default` provenance wording. + assert!( + out.contains("(distinct from bca check's gate)"), + "provenance line must render its code span:\n{out}" + ); + } + #[test] fn empty_summaries_emit_no_tables() { let out = generate_html_report(&[], 20, SuppressionPolicy::Honor); diff --git a/big-code-analysis-cli/src/html_report/sections.rs b/big-code-analysis-cli/src/html_report/sections.rs index 212cd4a9d..6ab926a4d 100644 --- a/big-code-analysis-cli/src/html_report/sections.rs +++ b/big-code-analysis-cli/src/html_report/sections.rs @@ -299,7 +299,7 @@ pub(crate) fn write_global_actionable_summary( let _ = writeln!( out, "

{}

", - escape_html(advisory.provenance_line()) + note_html(advisory.provenance_line()) ); if counts.all_clear() { let _ = out.write_str("

No major quality concerns detected.

\n"); @@ -333,7 +333,10 @@ pub(crate) fn write_legend_html(out: &mut String, entries: &[(&str, &str)]) { ), None => escape_html(header).into_owned(), }; - let _ = writeln!(out, "
{term}
{}
", escape_html(tip)); + // Definitions are crate-authored Markdown prose, like the notes: + // one policy for every such string, so a backtick added to a + // tooltip tomorrow renders as `` here too. + let _ = writeln!(out, "
{term}
{}
", note_html(tip)); } let _ = out.write_str("\n\n"); } @@ -512,13 +515,13 @@ fn write_actionable_summary( let _ = writeln!( section.out, "

{}

", - escape_html(advisory.provenance_line()) + note_html(advisory.provenance_line()) ); let breakdown = hotspot::suppressed_metric_breakdown(funcs, policy, advisory); let _ = writeln!( section.out, "

{}

", - escape_html(&hotspot::actionable_summary_caption(&breakdown)) + note_html(&hotspot::actionable_summary_caption(&breakdown)) ); if counts.all_clear() { let _ = section @@ -559,7 +562,7 @@ fn emit_fully_suppressed_note_html( let _ = writeln!( section.out, "

{}

", - escape_html(&hotspot::fully_suppressed_caption(&title, count)) + note_html(&hotspot::fully_suppressed_caption(&title, count)) ); } @@ -609,7 +612,7 @@ pub(crate) fn write_language_section( let _ = writeln!( section.out, "

{}

", - escape_html(hotspot::MI_NOTE) + note_html(hotspot::MI_NOTE) ); } } diff --git a/big-code-analysis-cli/src/html_report/styling.rs b/big-code-analysis-cli/src/html_report/styling.rs index e9312c6a1..c688f4078 100644 --- a/big-code-analysis-cli/src/html_report/styling.rs +++ b/big-code-analysis-cli/src/html_report/styling.rs @@ -27,6 +27,32 @@ pub(crate) fn escape_html(s: &str) -> Cow<'_, str> { Cow::Owned(out) } +/// Render a note that is written once as Markdown prose and shared with +/// the HTML report: HTML-escape it, then turn each *paired* backtick code +/// span into `…`. Before this the HTML page showed the +/// literal backticks ("sourced from the \`bca.toml\` \`[thresholds]\` +/// table."). An unpaired backtick is left as-is, since there is no span +/// to close. +pub(crate) fn note_html(note: &str) -> Cow<'_, str> { + let escaped = escape_html(note); + let ticks = escaped.matches('`').count(); + if ticks == 0 || !ticks.is_multiple_of(2) { + return escaped; + } + let mut out = String::with_capacity(escaped.len() + 16); + for (i, segment) in escaped.split('`').enumerate() { + if i > 0 { + out.push_str(if i.is_multiple_of(2) { + "
" + } else { + "" + }); + } + out.push_str(segment); + } + Cow::Owned(out) +} + /// Slugify a heading basis into an HTML `id`/fragment-safe token: /// lowercase ASCII, every run of non-`[a-z0-9]` characters collapsed to a /// single `-`, with leading/trailing hyphens trimmed. Built from the raw diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index fdf8cb72e..64d9c9576 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -581,16 +581,20 @@ pub(crate) fn write_legend(out: &mut String, level: usize, entries: &[(&str, &st } let hashes = "#".repeat(level); let _ = writeln!(out, "\n{hashes} Legend\n"); + // Every definition is a `&'static str` this crate authors, written as + // Markdown prose (`mi_visual_studio`, `--recent-window`), so it is + // emitted as-is: the cell escaper is for untrusted text in a table + // cell, and here it would turn `commits_recent` into `commits\_recent`. for (header, definition) in entries { // Link the header to its hosted metric chapter when one exists, so a // one-line legend entry can hand the reader the full explanation // (issue #675). VCS / identity headers have no anchor and render bare. match hotspot::metric_doc_url(header) { Some(url) => { - let _ = writeln!(out, "- **[{header}]({url})** — {}", escape_cell(definition)); + let _ = writeln!(out, "- **[{header}]({url})** — {definition}"); } None => { - let _ = writeln!(out, "- **{header}** — {}", escape_cell(definition)); + let _ = writeln!(out, "- **{header}** — {definition}"); } } } @@ -1460,8 +1464,8 @@ mod tests { // Headers with a hosted-docs anchor link to it (issue #675); the // rest render bare. Either way the definition follows. let bullet = match hotspot::metric_doc_url(header) { - Some(url) => format!("- **[{header}]({url})** — {}", escape_cell(definition)), - None => format!("- **{header}** — {}", escape_cell(definition)), + Some(url) => format!("- **[{header}]({url})** — {definition}"), + None => format!("- **{header}** — {definition}"), }; assert!(out.contains(&bullet), "legend missing entry for {header:?}"); } diff --git a/big-code-analysis-cli/src/markdown_report/advisory.rs b/big-code-analysis-cli/src/markdown_report/advisory.rs index 8d2e5ddaa..ede01c3ba 100644 --- a/big-code-analysis-cli/src/markdown_report/advisory.rs +++ b/big-code-analysis-cli/src/markdown_report/advisory.rs @@ -153,7 +153,10 @@ impl AdvisoryThresholds { } /// The one-line provenance sentence printed in both formats so the - /// advisory numbers are always attributable (issue #630). + /// advisory numbers are always attributable (issue #630). Written as + /// Markdown: the Markdown renderer emits it as-is and the HTML + /// renderer passes it through `html_report::note_html`, which turns + /// each paired backtick span into ``. pub(crate) fn provenance_line(self) -> &'static str { match self.source { ThresholdSource::Manifest => { diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap index 3c91a8f0c..5404ad866 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap @@ -55,7 +55,7 @@ expression: out

Actionable summary (all languages)

-

Advisory thresholds: built-in defaults (distinct from `bca check`'s gate).

+

Advisory thresholds: built-in defaults (distinct from bca check's gate).

  • 5 functions with CC > 10
  • 4 functions with cognitive complexity > 15
  • @@ -80,7 +80,7 @@ expression: out

    Files: 1 | SLOC: 120 | PLOC: 25 | Comment ratio: 4.2%

    Average MI (SLOC-weighted): 28.0 (GOOD)

    Actionable Summary

    -

    Advisory thresholds: built-in defaults (distinct from `bca check`'s gate).

    +

    Advisory thresholds: built-in defaults (distinct from bca check's gate).

    Raw counts across all functions, ignoring suppression markers.

    • 1 functions with more than 3 parameters
    • @@ -161,7 +161,7 @@ expression: out

      Files: 2 | SLOC: 280 | PLOC: 265 | Comment ratio: 8.9%

      Average MI (SLOC-weighted): 21.4 (GOOD)

      Actionable Summary

      -

      Advisory thresholds: built-in defaults (distinct from `bca check`'s gate).

      +

      Advisory thresholds: built-in defaults (distinct from bca check's gate).

      Raw counts across all functions; the hotspot tables hide suppressed rows (cyclomatic: 1) — re-run with --no-suppress to list them.

      • 5 functions with CC > 10
      • diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap index 107fc66f3..c764f7e46 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap @@ -51,7 +51,7 @@ expression: out

        Actionable summary (all languages)

        -

        Advisory thresholds: built-in defaults (distinct from `bca check`'s gate).

        +

        Advisory thresholds: built-in defaults (distinct from bca check's gate).

        No major quality concerns detected.

        Per-language overview

        @@ -70,7 +70,7 @@ expression: out

        Files: 1 | SLOC: 20 | PLOC: 25 | Comment ratio: 25.0%

        Average MI (SLOC-weighted): 50.0 (GOOD)

        Actionable Summary

        -

        Advisory thresholds: built-in defaults (distinct from `bca check`'s gate).

        +

        Advisory thresholds: built-in defaults (distinct from bca check's gate).

        Raw counts across all functions, ignoring suppression markers.

        No major quality concerns detected.

        Maintainability Index hotspots (lowest 5 by MI)

        @@ -135,7 +135,7 @@ expression: out

        Files: 1 | SLOC: 20 | PLOC: 25 | Comment ratio: 25.0%

        Average MI (SLOC-weighted): 50.0 (GOOD)

        Actionable Summary

        -

        Advisory thresholds: built-in defaults (distinct from `bca check`'s gate).

        +

        Advisory thresholds: built-in defaults (distinct from bca check's gate).

        Raw counts across all functions, ignoring suppression markers.

        No major quality concerns detected.

        Maintainability Index hotspots (lowest 5 by MI)

        diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap index 5cf8d9406..67105f64a 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap @@ -18,7 +18,7 @@ expression: html
- + @@ -44,12 +44,12 @@ expression: html Legend
Risk
Composite change-history risk score: recent churn and commit frequency dominate, raised by author dilution, bug-/security-fix history, and newness. Ordinal: only relative ranks carry meaning, not the absolute value.
-
Commits (recent)
Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: commits_recent.
-
Commits (long)
Distinct commits that touched this file in the long window (default 365 days, set via --long-window) — not all history. Wire key: commits_long.
-
Churn (recent)
Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: churn_recent.
-
Churn (long)
Lines added + deleted to this file in the long window (default 365 days, set via --long-window) — not all history. Wire key: churn_long.
-
Authors (recent)
Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: authors_recent.
-
Authors (long)
Distinct authors who touched this file in the long window (default 365 days, set via --long-window) — not all history. Wire key: authors_long.
+
Commits (recent)
Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: commits_recent.
+
Commits (long)
Distinct commits that touched this file in the long window (default 365 days, set via --long-window) — not all history. Wire key: commits_long.
+
Churn (recent)
Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: churn_recent.
+
Churn (long)
Lines added + deleted to this file in the long window (default 365 days, set via --long-window) — not all history. Wire key: churn_long.
+
Authors (recent)
Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: authors_recent.
+
Authors (long)
Distinct authors who touched this file in the long window (default 365 days, set via --long-window) — not all history. Wire key: authors_long.
Ownership
Top-author edit share (0–1): fraction of edits by the single most active author; lower means more diluted ownership.
Burst
Recency of change (0–1): recent commits as a share of long-window commits.
Bug fixes
Commits classified as bug fixes (by message) within the long window.
@@ -57,10 +57,10 @@ expression: html
Reverts
Revert commits touching this file within the long window.
Age (d)
Days since the first in-window commit touching this file (capped at the long window).
Last mod (d)
Days since the most recent in-window commit touching this file.
-
Change entropy (recent)
Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the recent window (default 90 days, --recent-window). Higher means more diffuse, fault-prone change. Wire key: change_entropy_recent.
-
Change entropy (long)
Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the long window (default 365 days, --long-window). Higher means more diffuse, fault-prone change. Wire key: change_entropy_long.
-
Co-change entropy (recent)
Co-change entropy (bits): how widely changes to this file ripple to other files, over the recent window (default 90 days, --recent-window). Higher means coupling to many different partners. Wire key: cochange_entropy_recent.
-
Co-change entropy (long)
Co-change entropy (bits): how widely changes to this file ripple to other files, over the long window (default 365 days, --long-window). Higher means coupling to many different partners. Wire key: cochange_entropy_long.
+
Change entropy (recent)
Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the recent window (default 90 days, --recent-window). Higher means more diffuse, fault-prone change. Wire key: change_entropy_recent.
+
Change entropy (long)
Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the long window (default 365 days, --long-window). Higher means more diffuse, fault-prone change. Wire key: change_entropy_long.
+
Co-change entropy (recent)
Co-change entropy (bits): how widely changes to this file ripple to other files, over the recent window (default 90 days, --recent-window). Higher means coupling to many different partners. Wire key: cochange_entropy_recent.
+
Co-change entropy (long)
Co-change entropy (bits): how widely changes to this file ripple to other files, over the long window (default 365 days, --long-window). Higher means coupling to many different partners. Wire key: cochange_entropy_long.
Hotspot
Complexity × recent churn: high-complexity files that also change often. Shown only when AST metrics are joined (e.g. report --vcs); omitted by plain bca vcs.
Bus factor
Number of authors whose departure would orphan more than half the files (by Avelino Degree-of-Authorship); lower is riskier.
Files
Files in this directory contributing to its bus factor.
diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap index 6057ce13c..cce97ac19 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap @@ -28,9 +28,9 @@ _Bus factor: the number of authors whose departure would orphan more than half t ## Legend - **Risk** — Composite change-history risk score: recent churn and commit frequency dominate, raised by author dilution, bug-/security-fix history, and newness. Ordinal: only relative ranks carry meaning, not the absolute value. -- **Commits (recent)** — Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: commits\_recent. -- **Churn (recent)** — Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: churn\_recent. -- **Authors (recent)** — Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: authors\_recent. +- **Commits (recent)** — Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: `commits_recent`. +- **Churn (recent)** — Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: `churn_recent`. +- **Authors (recent)** — Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: `authors_recent`. - **Ownership** — Top-author edit share (0–1): fraction of edits by the single most active author; lower means more diluted ownership. - **Bug fixes** — Commits classified as bug fixes (by message) within the long window. - **Hotspot** — Complexity × recent churn: high-complexity files that also change often. Shown only when AST metrics are joined (e.g. report --vcs); omitted by plain bca vcs. diff --git a/big-code-analysis-cli/src/vcs_report.rs b/big-code-analysis-cli/src/vcs_report.rs index 582b1ba70..9baedb9d7 100644 --- a/big-code-analysis-cli/src/vcs_report.rs +++ b/big-code-analysis-cli/src/vcs_report.rs @@ -18,7 +18,7 @@ use std::fmt::Write as _; use crate::html_report::{ - Headings, RankedColumn, write_html_head, write_html_tail, write_legend_html, + Headings, RankedColumn, note_html, write_html_head, write_html_tail, write_legend_html, write_table_classed_with_tooltips as write_html_table_classed, write_table_with_tooltips, }; use crate::markdown_report::hotspot::{self, Cell}; @@ -61,12 +61,12 @@ struct VcsColumn { // (issue #592). Moved here from `html_report::VCS_HEADER_TOOLTIPS` (issue // #611) to make `VCS_SPECS` the single source of truth. const RISK_TOOLTIP: &str = "Composite change-history risk score: recent churn and commit frequency dominate, raised by author dilution, bug-/security-fix history, and newness. Ordinal: only relative ranks carry meaning, not the absolute value."; -const COMMITS_RECENT_TOOLTIP: &str = "Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: commits_recent."; -const COMMITS_LONG_TOOLTIP: &str = "Distinct commits that touched this file in the long window (default 365 days, set via --long-window) \u{2014} not all history. Wire key: commits_long."; -const CHURN_RECENT_TOOLTIP: &str = "Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: churn_recent."; -const CHURN_LONG_TOOLTIP: &str = "Lines added + deleted to this file in the long window (default 365 days, set via --long-window) \u{2014} not all history. Wire key: churn_long."; -const AUTHORS_RECENT_TOOLTIP: &str = "Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: authors_recent."; -const AUTHORS_LONG_TOOLTIP: &str = "Distinct authors who touched this file in the long window (default 365 days, set via --long-window) \u{2014} not all history. Wire key: authors_long."; +const COMMITS_RECENT_TOOLTIP: &str = "Distinct commits that touched this file in the recent window (default 90 days, set via --recent-window). Wire key: `commits_recent`."; +const COMMITS_LONG_TOOLTIP: &str = "Distinct commits that touched this file in the long window (default 365 days, set via --long-window) \u{2014} not all history. Wire key: `commits_long`."; +const CHURN_RECENT_TOOLTIP: &str = "Lines added + deleted to this file in the recent window (default 90 days, set via --recent-window). Wire key: `churn_recent`."; +const CHURN_LONG_TOOLTIP: &str = "Lines added + deleted to this file in the long window (default 365 days, set via --long-window) \u{2014} not all history. Wire key: `churn_long`."; +const AUTHORS_RECENT_TOOLTIP: &str = "Distinct authors who touched this file in the recent window (default 90 days, set via --recent-window). Wire key: `authors_recent`."; +const AUTHORS_LONG_TOOLTIP: &str = "Distinct authors who touched this file in the long window (default 365 days, set via --long-window) \u{2014} not all history. Wire key: `authors_long`."; const OWNERSHIP_TOOLTIP: &str = "Top-author edit share (0\u{2013}1): fraction of edits by the single most active author; lower means more diluted ownership."; const BURST_TOOLTIP: &str = "Recency of change (0\u{2013}1): recent commits as a share of long-window commits."; @@ -77,10 +77,10 @@ const REVERTS_TOOLTIP: &str = "Revert commits touching this file within the long const AGE_TOOLTIP: &str = "Days since the first in-window commit touching this file (capped at the long window)."; const LAST_MOD_TOOLTIP: &str = "Days since the most recent in-window commit touching this file."; -const CHANGE_ENTROPY_RECENT_TOOLTIP: &str = "Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the recent window (default 90 days, --recent-window). Higher means more diffuse, fault-prone change. Wire key: change_entropy_recent."; -const CHANGE_ENTROPY_LONG_TOOLTIP: &str = "Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the long window (default 365 days, --long-window). Higher means more diffuse, fault-prone change. Wire key: change_entropy_long."; -const COCHANGE_ENTROPY_RECENT_TOOLTIP: &str = "Co-change entropy (bits): how widely changes to this file ripple to other files, over the recent window (default 90 days, --recent-window). Higher means coupling to many different partners. Wire key: cochange_entropy_recent."; -const COCHANGE_ENTROPY_LONG_TOOLTIP: &str = "Co-change entropy (bits): how widely changes to this file ripple to other files, over the long window (default 365 days, --long-window). Higher means coupling to many different partners. Wire key: cochange_entropy_long."; +const CHANGE_ENTROPY_RECENT_TOOLTIP: &str = "Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the recent window (default 90 days, --recent-window). Higher means more diffuse, fault-prone change. Wire key: `change_entropy_recent`."; +const CHANGE_ENTROPY_LONG_TOOLTIP: &str = "Change entropy (bits): how scattered the changes to this file are across commits (Hassan 2009), over the long window (default 365 days, --long-window). Higher means more diffuse, fault-prone change. Wire key: `change_entropy_long`."; +const COCHANGE_ENTROPY_RECENT_TOOLTIP: &str = "Co-change entropy (bits): how widely changes to this file ripple to other files, over the recent window (default 90 days, --recent-window). Higher means coupling to many different partners. Wire key: `cochange_entropy_recent`."; +const COCHANGE_ENTROPY_LONG_TOOLTIP: &str = "Co-change entropy (bits): how widely changes to this file ripple to other files, over the long window (default 365 days, --long-window). Higher means coupling to many different partners. Wire key: `cochange_entropy_long`."; const HOTSPOT_TOOLTIP: &str = "Complexity \u{D7} recent churn: high-complexity files that also change often. Shown only when AST metrics are joined (e.g. report --vcs); omitted by plain bca vcs."; /// Format an integer count as a `Cell::Num` with comma thousands @@ -626,7 +626,7 @@ fn write_html_body( let _ = out.write_str("
\n"); let _ = writeln!(out, "

{}

", provenance(report)); if report.truncated_shallow_clone { - let _ = writeln!(out, "

{SHALLOW_NOTE}

"); + let _ = writeln!(out, "

{}

", note_html(SHALLOW_NOTE)); } let _ = out.write_str("
\n"); let specs = active_specs(report); From af8878ddfad36ee200bcae5c80ee5a01b4a8882f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:22:10 -0800 Subject: [PATCH 5/8] fix(cli): grade the change-history heat band against every ranked file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three defects in the `--vcs` section. The HTML severity-heat band graded each row by its rank among the rows rendered, so a `--top 50` table painted the repository's 41st–50th riskiest files green and `--top 1` painted its single riskiest file green; `Report` now carries the pre-truncation population (`ranked_total`, never serialized) and `rank()` records it before `rank_by_risk` cuts. The `Hotspot` column rendered `748436.0` beside thousands-separated siblings for a score that is always an integer product; it goes through the shared count formatter. And the Markdown pointer under the table told a `bca report --vcs` reader to re-run with `--format csv`, which `report` rejects; it names `bca vcs --format csv|json` (no Hotspot column) and `bca metrics --vcs`. Each is pinned: an end-to-end `--top 1` test on a three-file repository for both `vcs --format html` and `report --vcs` (recording the count after truncation fails it), a unit test over the population, the rich fixture's score raised to prove the separator, and a test that parses every command the pointer names through the real clap definition and shows `report --format csv` is rejected. --- ...s_report__tests__vcs_report_html_rich.snap | 2 +- ...port__tests__vcs_report_markdown_rich.snap | 4 +- big-code-analysis-cli/src/vcs_command.rs | 63 +++++- big-code-analysis-cli/src/vcs_report.rs | 184 +++++++++++++++--- big-code-analysis-cli/tests/vcs/vcs_rank.rs | 79 ++++++++ 5 files changed, 298 insertions(+), 34 deletions(-) diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap index 67105f64a..8ad614ebc 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap @@ -20,7 +20,7 @@ expression: html
RankFileRiskCommits (recent)Commits (long)Churn (recent)Churn (long)Authors (recent)Authors (long)OwnershipBurstBug fixesSec fixesRevertsAge (d)Last mod (d)Change entropy (recent)Change entropy (long)Co-change entropy (recent)Co-change entropy (long)Hotspot
RankFileRiskCommits (recent)Commits (long)Churn (recent)Churn (long)Authors (recent)Authors (long)OwnershipBurstBug fixesSec fixesRevertsAge (d)Last mod (d)Change entropy (recent)Change entropy (long)Co-change entropy (recent)Co-change entropy (long)Hotspot
1src/hot.rs9.450602,0005,000230.750.5041020051.502.500.801.20123.0
2src/warm.rs6.120308002,000230.750.5041020051.502.500.801.20
- + diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap index cce97ac19..e73f555bd 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_markdown_rich.snap @@ -8,11 +8,11 @@ _Long window 365d, recent window 90d, risk formula v1. Risk is ordinal: only rel | Rank | File | Risk | Commits (recent) | Churn (recent) | Authors (recent) | Ownership | Bug fixes | Hotspot | | ---: | ------------------ | ---: | ---------------: | -------------: | ---------------: | --------: | --------: | ------: | -| 1 | src/hot.rs | 9.4 | 50 | 2,000 | 2 | 0.75 | 4 | 123.0 | +| 1 | src/hot.rs | 9.4 | 50 | 2,000 | 2 | 0.75 | 4 | 748,436 | | 2 | src/warm.rs | 6.1 | 20 | 800 | 2 | 0.75 | 4 | | | 3 | docs/with\|pipe.md | 2.0 | 1 | 40 | 2 | 0.75 | 4 | | -Full per-file change-history record (all columns): re-run with `--format csv` or `--format json`. +Full per-file change-history record (all columns): run `bca vcs --format csv` or `bca vcs --format json` (no Hotspot column), or `bca metrics --vcs` for the per-file block including it. ## Bus factor diff --git a/big-code-analysis-cli/src/vcs_command.rs b/big-code-analysis-cli/src/vcs_command.rs index 6f18eda97..1f668ff85 100644 --- a/big-code-analysis-cli/src/vcs_command.rs +++ b/big-code-analysis-cli/src/vcs_command.rs @@ -55,6 +55,39 @@ pub(crate) struct Report { #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) vcs_aggregate: Option, pub(crate) files: Vec, + /// How many entries were ranked before `--top` truncated `files` — + /// the tracked files the walk admitted and, under `--include-deleted`, + /// the deleted ones appended — so the HTML severity-heat bands + /// (`vcs_report::risk_heat_class`) grade each row against the whole + /// population rather than the rows shown; with `--top 1` the + /// repository's riskiest file was otherwise painted green. + /// Presentation state, never serialized. Invariant: at least + /// `files.len()`, since truncation only removes. + #[serde(skip)] + pub(crate) ranked_total: usize, +} + +impl Report { + /// The population the risk ranking was drawn from. + pub(crate) fn ranked_population(&self) -> usize { + debug_assert!( + self.ranked_total >= self.files.len(), + "ranked_total ({}) below the rows carried ({})", + self.ranked_total, + self.files.len() + ); + self.ranked_total + } + + /// Test-fixture finisher: a report whose population is exactly the + /// rows it carries, as an untruncated ranking produces. A struct + /// literal cannot read its own `files`, so fixtures write a + /// placeholder `ranked_total` and call this. + #[cfg(test)] + pub(crate) fn with_untruncated_total(mut self) -> Self { + self.ranked_total = self.files.len(); + self + } } /// Entry point for `Command::Vcs`. @@ -102,7 +135,7 @@ pub(crate) fn run(mut globals: GlobalOpts, args: VcsArgs) { warn("shallow clone detected — history is truncated, so counts are lower bounds"); } - let entries = rank(&globals, &index, args.top, args.include_deleted); + let (entries, ranked_total) = rank(&globals, &index, args.top, args.include_deleted); let report = Report { long_window_days: options.long_window_days(), recent_window_days: options.recent_window_days(), @@ -111,6 +144,7 @@ pub(crate) fn run(mut globals: GlobalOpts, args: VcsArgs) { truncated_shallow_clone: index.truncated_shallow_clone(), vcs_aggregate: index.vcs_aggregate(), files: entries, + ranked_total, }; crate::die_unless_broken_pipe(emit(&report, &args), "writing vcs output"); @@ -144,7 +178,7 @@ pub(crate) fn reject_cache_flags_with_subcommand(args: &VcsArgs) -> Result<(), & pub(crate) fn build_default_report(globals: &GlobalOpts, top: usize) -> Option { let index = default_aggregate_index(globals)?; let options = Options::default(); - let entries = rank(globals, &index, top, false); + let (entries, ranked_total) = rank(globals, &index, top, false); let report = Report { long_window_days: options.long_window_days(), recent_window_days: options.recent_window_days(), @@ -153,6 +187,7 @@ pub(crate) fn build_default_report(globals: &GlobalOpts, top: usize) -> Option Option { /// Select the tracked files the global filters admit, sort them by risk /// score (descending; path as a stable tie-break), and truncate to the -/// top `top` (0 = all). +/// top `top` (0 = all). Also returns how many files were ranked before +/// truncation, for [`Report::ranked_total`]. fn rank( globals: &GlobalOpts, index: &vcs::HistoryIndex, top: usize, include_deleted: bool, -) -> Vec { +) -> (Vec, usize) { // Reuse the standard walk so `--paths/--include/--exclude/--no-ignore` // behave exactly as elsewhere; intersect the result with the tracked // set (untracked / binary files are simply absent from the index). @@ -361,8 +397,9 @@ fn rank( append_deleted_entries(&mut entries, &covered, globals, index); } + let ranked_total = entries.len(); vcs::rank_by_risk(&mut entries, top, |e| (e.path.as_str(), e.vcs.risk_score)); - entries + (entries, ranked_total) } /// Append entries for files present in the index but absent from the @@ -837,7 +874,9 @@ mod tests { vcs_aggregate: None, // `b.rs` has no AST entry below, so it must stay `None`. files: vec![file_entry("src/a.rs", 40), file_entry("src/b.rs", 10)], - }; + ranked_total: 0, + } + .with_untruncated_total(); let mut default = DefaultReport { report, workdir: Some(workdir_root), @@ -880,7 +919,9 @@ mod tests { truncated_shallow_clone: false, vcs_aggregate: None, files: vec![file_entry("src/a.rs", 40)], - }; + ranked_total: 0, + } + .with_untruncated_total(); let mut default = DefaultReport { report, workdir: None, @@ -908,7 +949,9 @@ mod tests { truncated_shallow_clone: false, vcs_aggregate: None, files: vec![entry], - }; + ranked_total: 0, + } + .with_untruncated_total(); let mut default = DefaultReport { report, workdir: Some(workdir_root), @@ -932,7 +975,9 @@ mod tests { truncated_shallow_clone: false, vcs_aggregate: None, files: vec![entry], - }; + ranked_total: 0, + } + .with_untruncated_total(); let dir = tempfile::tempdir().expect("tempdir"); let out = dir.path().join("vcs.csv"); write_csv(&report, Some(out.as_path())).expect("write_csv to temp file"); diff --git a/big-code-analysis-cli/src/vcs_report.rs b/big-code-analysis-cli/src/vcs_report.rs index 9baedb9d7..f1d158801 100644 --- a/big-code-analysis-cli/src/vcs_report.rs +++ b/big-code-analysis-cli/src/vcs_report.rs @@ -93,6 +93,15 @@ fn num_cell(n: u64) -> Cell { Cell::Num(thousands(usize::try_from(n).unwrap_or(usize::MAX))) } +/// A hotspot score as a [`num_cell`]: rounded to the nearest integer (the +/// product of two integers in every score this crate computes), negative +/// or NaN clamped to zero rather than wrapped. Scores stay far below +/// 2^53, so the `f64 -> u64` cast is exact. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +fn hotspot_cell(score: f64) -> Cell { + num_cell(score.round().max(0.0) as u64) +} + /// The change-history columns, defined once for both formats, with a leading /// Rank column. Order and content mirror the structured CSV record. HTML /// renders the full set (it is genuinely sortable, so the page is the @@ -248,14 +257,15 @@ const VCS_SPECS: &[VcsColumn] = &[ align: Align::Right, // Rendered only when some row carries a score (see `active_specs`); in a // mixed report (the normal `report --vcs` join) the column survives on the - // scored rows and `unwrap_or_default` blanks each unscored (`None`) row. + // scored rows and each unscored (`None`) row renders blank. + // The score is an integer cyclomatic count times an integer churn, + // so it takes the thousands formatter the sibling counts use + // (`748,436` rather than `748436.0`); the rounding only matters + // for a score a caller computed from a fractional complexity. cell: |_, e| { - Cell::Num( - e.vcs - .hotspot_score - .map(|h| format!("{h:.1}")) - .unwrap_or_default(), - ) + e.vcs + .hotspot_score + .map_or(Cell::Num(String::new()), hotspot_cell) }, tooltip: Some(HOTSPOT_TOOLTIP), in_markdown: true, @@ -294,8 +304,13 @@ fn markdown_specs(report: &Report) -> Vec<&'static VcsColumn> { } /// Appended after the curated Markdown table, pointing the reader at the -/// structured formats for the columns Markdown omits (issue #621). -const MARKDOWN_FULL_RECORD_POINTER: &str = "Full per-file change-history record (all columns): re-run with `--format csv` or `--format json`."; +/// structured formats for the columns Markdown omits (issue #621). Names +/// the command that takes those formats: `bca report` accepts only +/// `markdown` / `html`, so the earlier "re-run with `--format csv`" sent a +/// `report --vcs` reader to an argument error. Plain `bca vcs` ranks the +/// same files but carries no Hotspot column (that needs the AST join); +/// `bca metrics --vcs` emits the full block per file including it. +const MARKDOWN_FULL_RECORD_POINTER: &str = "Full per-file change-history record (all columns): run `bca vcs --format csv` or `bca vcs --format json` (no Hotspot column), or `bca metrics --vcs` for the per-file block including it."; /// Header of the column that carries the severity-heat tint in the HTML /// report. Matched structurally against [`VCS_SPECS`] (see @@ -330,8 +345,8 @@ fn risk_column_index() -> Option { .position(|c| c.header == RISK_COLUMN_HEADER) } -/// Severity-heat CSS class for the risk cell of the `row`-th file in a -/// report of `n_rows` risk-ranked files, or `None` when no band applies. +/// Severity-heat CSS class for the risk cell of the `row`-th file among +/// `n_rows` risk-ranked files, or `None` when no band applies. /// /// The band is a function of *rank*, not the raw `risk_score`: /// `report.files` is sorted by descending risk, so `row` (0-based) is the @@ -339,9 +354,14 @@ fn risk_column_index() -> Option { /// slices maps the top rows to band 0 (most severe) and the bottom rows to /// the last band (least severe), independent of the absolute values. /// -/// Edge case: a single row has no ranking to express, so it gets the -/// least-severe band (a lone file should not look alarming); `n_rows == 0` -/// never calls this (no rows are rendered). +/// `n_rows` is the ranked *population* ([`Report::ranked_population`]), +/// not the rendered row count: a `--top N` table shows the N riskiest +/// files, and grading them against each other painted the repository's +/// single riskiest file green under `--top 1`. +/// +/// Edge case: a single ranked file has no ranking to express, so it gets +/// the least-severe band (a lone file should not look alarming); +/// `n_rows == 0` never calls this (no rows are rendered). fn risk_heat_class(row: usize, n_rows: usize) -> Option<&'static str> { if n_rows <= 1 { return HEAT_CLASSES.last().copied(); @@ -643,7 +663,10 @@ fn write_html_body( // Hotspot column never shifts the Risk column, so the index stays // valid against the active spec set. let risk_col = risk_column_index(); - let n_rows = rows.len(); + // Grade against every file that was ranked, not only the rows + // `--top` left: the 41st–50th riskiest files in a top-50 table + // are not the repository's least risky. + let n_rows = report.ranked_population(); // The table arrives pre-ranked by Risk descending (`report.files` // is risk-ranked), so announce that as the initial sort on the Risk // column's `"), "HTML keeps Hotspot header"); - // `Some(123.0)` formats with one decimal place. - assert!(md.contains("123.0"), "Markdown renders the hotspot value"); - assert!(html.contains("123.0"), "HTML renders the hotspot value"); + // The score is an integral product (cyclomatic sum × churn), so it + // takes the thousands separator the count columns use rather than + // the bare `748436.0` it rendered as before. + assert!( + md.contains("| 748,436 |"), + "Markdown renders the hotspot value:\n{md}" + ); + assert!( + html.contains(""), + "HTML renders the hotspot value:\n{html}" + ); + assert!(!md.contains("748436.0"), "no bare float rendering survives"); // The legend documents the rendered column. assert!( legend_entries(&specs) @@ -1132,6 +1166,43 @@ mod tests { ); } + /// The full-record pointer names commands the CLI accepts. Its + /// previous wording told a `bca report` reader to re-run with + /// `--format csv`, which `report` rejects; nothing pinned it, so it + /// stayed wrong. Each command the text names is parsed through the + /// real clap definition, and the one it must not name is shown to + /// fail. + #[test] + fn full_record_pointer_names_commands_the_cli_accepts() { + use clap::Parser as _; + for name in [ + "--format csv", + "--format json", + "bca vcs", + "bca metrics --vcs", + ] { + assert!( + MARKDOWN_FULL_RECORD_POINTER.contains(name), + "pointer must mention {name:?}: {MARKDOWN_FULL_RECORD_POINTER}" + ); + } + for argv in [ + vec!["bca", "vcs", "--format", "csv"], + vec!["bca", "vcs", "--format", "json"], + vec!["bca", "metrics", "--vcs"], + ] { + assert!( + crate::Cli::try_parse_from(&argv).is_ok(), + "the pointer names {argv:?}, which the CLI must accept" + ); + } + assert!( + crate::Cli::try_parse_from(["bca", "report", "--format", "csv"]).is_err(), + "`report` takes no csv format, so the pointer must not send a reader there" + ); + assert!(!MARKDOWN_FULL_RECORD_POINTER.contains("bca report")); + } + #[test] fn hotspot_column_omitted_when_no_row_has_a_score() { // Plain `bca vcs` (no AST join): every row's `hotspot_score` is @@ -1143,6 +1214,7 @@ mod tests { entry("src/a.rs", 9.0, 30, None), entry("src/b.rs", 4.0, 10, None), ], + ranked_total: 2, ..rich_report() }; let specs = active_specs(&report); @@ -1152,12 +1224,15 @@ mod tests { ); let md = render_markdown(&report); let html = render_html(&report); + // The column, its header and its legend entry are gone; the + // full-record pointer still *names* the Hotspot column to say + // `bca vcs` lacks it, so the check is on the table cells. assert!( - !md.contains("Hotspot"), - "Markdown must omit the Hotspot column entirely" + !md.contains("| Hotspot |") && !md.contains("**Hotspot**"), + "Markdown must omit the Hotspot column entirely:\n{md}" ); assert!( - !html.contains("Hotspot"), + !html.contains(">Hotspot") && !html.contains("
Hotspot
"), "HTML must omit the Hotspot column entirely (header + legend)" ); // A still-rendered column proves the table itself is intact. @@ -1458,6 +1533,7 @@ mod tests { files: (0..5) .map(|i| entry(&format!("f{i}.rs"), 98.0 - f64::from(i), 5 - i, None)) .collect(), + ranked_total: 5, ..rich_report() }; let html = render_html(&report); @@ -1482,6 +1558,7 @@ mod tests { files: (0..5) .map(|i| entry(&format!("f{i}.rs"), 10.0 + f64::from(i), i + 1, None)) .collect(), + ranked_total: 5, ..rich_report() }; assert_eq!( @@ -1491,6 +1568,69 @@ mod tests { ); } + /// The heat band grades a row against every file that was ranked, not + /// only the rows `--top` kept: a `--top 1` table carries the + /// repository's riskiest file, which used to be painted the + /// least-severe band because it was the last of one row. + #[test] + fn risk_heat_grades_against_the_ranked_population_not_the_rows_shown() { + let top_one = Report { + vcs_aggregate: None, + files: vec![entry("worst.rs", 98.0, 5, None)], + ranked_total: 50, + ..rich_report() + }; + assert_eq!( + risk_heat_classes(&render_html(&top_one)), + vec!["risk-heat-0".to_owned()], + "the riskiest of 50 files must take the most-severe band" + ); + // Ten rows of a hundred: every shown row sits in the top tenth, + // so all ten land in band 0 rather than spreading over five. + let top_ten = Report { + vcs_aggregate: None, + files: (0..10) + .map(|i| entry(&format!("f{i}.rs"), 98.0 - f64::from(i), 10 - i, None)) + .collect(), + ranked_total: 100, + ..rich_report() + }; + assert_eq!( + risk_heat_classes(&render_html(&top_ten)), + vec!["risk-heat-0".to_owned(); 10] + ); + // A repository with one tracked file has no ranking to express, + // so its lone row reads least-severe. + let lone = Report { + vcs_aggregate: None, + files: vec![entry("only.rs", 98.0, 5, None)], + ranked_total: 1, + ..rich_report() + }; + assert_eq!(lone.ranked_population(), 1); + assert_eq!( + risk_heat_classes(&render_html(&lone)), + vec!["risk-heat-4".to_owned()] + ); + } + + /// `ranked_population` guards its invariant — the recorded population + /// is never smaller than the rows carried, since truncation only + /// removes — with a `debug_assert!`. This proves the guard fires on + /// the state it exists to reject, so it is a live check and not a + /// comment (a dev build is what the test suite and `make pre-commit` + /// run under). + #[test] + #[cfg(debug_assertions)] + #[should_panic(expected = "ranked_total (1) below the rows carried (3)")] + fn ranked_population_rejects_a_total_below_the_rows_carried() { + let report = Report { + ranked_total: 1, + ..rich_report() + }; + let _ = report.ranked_population(); + } + #[test] fn risk_heat_band_edges_are_relative() { // Unit check of the rank->band mapping and documented edge cases. diff --git a/big-code-analysis-cli/tests/vcs/vcs_rank.rs b/big-code-analysis-cli/tests/vcs/vcs_rank.rs index c6cc5494a..bfe1a5c93 100644 --- a/big-code-analysis-cli/tests/vcs/vcs_rank.rs +++ b/big-code-analysis-cli/tests/vcs/vcs_rank.rs @@ -785,6 +785,85 @@ fn vcs_html_writes_a_single_self_contained_file() { assert!(html.contains("src/work.rs")); } +/// The HTML risk-heat band grades a row against every file that was +/// ranked, not only the rows `--top` kept. With three tracked files and +/// `--top 1`, the one row shown is the repository's riskiest file and +/// must take the most-severe band; before the fix it was graded as the +/// last of one row and painted the least-severe one. Driven through the +/// binary so the pre-truncation count recorded in `rank()` is what is +/// tested, for both the standalone `vcs` page and the `report --vcs` +/// section. +#[test] +fn vcs_top_one_heats_the_riskiest_file_as_most_severe() { + let now = now(); + let dir = tempfile::tempdir().expect("tempdir"); + let git = |secs: i64, args: &[&str]| git_at(dir.path(), secs, args); + git(now, &["init", "-q", "-b", "main"]); + git(now, &["config", "commit.gpgsign", "false"]); + std::fs::create_dir(dir.path().join("src")).expect("mkdir"); + for name in ["a", "b", "c"] { + std::fs::write( + dir.path().join(format!("src/{name}.rs")), + format!("fn {name}() {{}}\n"), + ) + .expect("write"); + } + git(now - 200 * DAY, &["add", "."]); + git(now - 200 * DAY, &["commit", "-q", "-m", "add three"]); + // Only `a.rs` changes recently, so it ranks first by risk. + std::fs::write( + dir.path().join("src/a.rs"), + "fn a() {}\nfn a2() {}\nfn a3() {}\n", + ) + .expect("write"); + git(now - 5 * DAY, &["commit", "-aqm", "fix bug in a"]); + + let risk_cell = |html: &str| -> String { + let body = html.rsplit_once("").map_or(html, |(_, b)| b); + let row = body + .split("") + .find(|r| r.contains("src/a.rs")) + .expect("a.rs row"); + let start = row.find("risk-heat-").expect("heated risk cell"); + row[start..start + "risk-heat-N".len()].to_owned() + }; + + let out = dir.path().join("vcs.html"); + cli() + .current_dir(dir.path()) + .args([ + "vcs", + "--paths", + ".", + "--top", + "1", + "--format", + "html", + "--output", + out.to_str().expect("utf8 path"), + ]) + .assert() + .success(); + let html = std::fs::read_to_string(&out).expect("read html"); + assert!(!html.contains("src/b.rs"), "--top 1 shows one row:\n{html}"); + assert_eq!(risk_cell(&html), "risk-heat-0"); + + let report = cli() + .current_dir(dir.path()) + .args(["report", "html", "--vcs", "--top", "1", "--paths", "."]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let report = String::from_utf8(report).expect("utf8 html"); + let section = report + .split(">Change-history risk") + .nth(1) + .expect("change-history section"); + assert_eq!(risk_cell(section), "risk-heat-0"); +} + #[test] fn vcs_json_output_writes_a_single_file() { // Regression guard for the `--output` semantics fix: structured From 607c21157750453feb7276fccf99a6880d605709 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:23:05 -0800 Subject: [PATCH 6/8] fix(cli): say what the report's overview and legend columns measure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Per-language overview's `Avg MI` is the SLOC-weighted *unclamped* Visual Studio value (#725), so it reads negative for an unmaintainable codebase — correctly — while the Markdown legend had no entry for it and its per-file `MI` entry said "clamped to 0–100" three tables above. Both legends now define `Files`, `Functions`, `Avg MI`, `Avg CC` and `Avg Cognitive` from one `OVERVIEW_LEGEND` list (which also feeds the HTML tooltips, retiring the separate `AST_OVERVIEW_TOOLTIPS` copy); `MI` points at the unclamped average; and `Avg CC` names its population, since the CC note's `Average CC` covers a different set (CC above 0, by default not suppressed, before the top-N cut). Several legend entries described a different quantity from the one the column shows: `Exits`, `Methods`, `WMC`, `NPA` and `NPM` said "out of the function" / "declared on the class" while the columns are subtree sums (`nexits_sum`, `nom.total`, … — the deliberate #709 accessor split), and `Comments` said "lines that are entirely comment" while `cloc()` counts trailing comments too. The CC note's fields are joined by `;` rather than `|`: directly under a table the `|`-joined line is an orphaned table row to rumdl 0.2.2 (MD075, four hits on the published report). A new test walks every legend entry both reports can render and asserts no definition carries a character Markdown and HTML would read apart outside a code span, which is what lets the Markdown legend emit them unescaped. --- .bca-baseline.toml | 4 +- CHANGELOG.md | 38 ++++++ big-code-analysis-book/src/commands/report.md | 8 +- big-code-analysis-cli/src/html_report.rs | 6 +- .../src/html_report/sections.rs | 2 +- .../src/html_report/styling.rs | 26 +---- big-code-analysis-cli/src/markdown_report.rs | 108 ++++++++++++++++-- .../src/markdown_report/hotspot.rs | 48 ++++++-- .../src/markdown_report/sections.rs | 6 +- ..._html_report__tests__html_report_rich.snap | 35 +++--- ...l_report__tests__html_report_two_lang.snap | 31 ++--- ...n_report__tests__markdown_report_rich.snap | 23 ++-- big-code-analysis-cli/src/vcs_report.rs | 8 ++ 13 files changed, 256 insertions(+), 87 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index e25f5cf00..dde6e8a73 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -653,7 +653,7 @@ value = 49443.19551903411 path = "big-code-analysis-cli/src/markdown_report.rs" qualified = "" metric = "loc.ploc" -value = 633.0 +value = 637.0 [[entry]] path = "big-code-analysis-cli/src/markdown_report.rs" @@ -683,7 +683,7 @@ value = 6.0 path = "big-code-analysis-cli/src/markdown_report/hotspot.rs" qualified = "" metric = "loc.ploc" -value = 694.0 +value = 707.0 [[entry]] path = "big-code-analysis-cli/src/markdown_report/hotspot.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index 02595104d..faca3ea0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,44 @@ for historical reference. `utils/check-tools.sh --release-only` asks the script itself, names the binary it judged when it refuses one, and the install hints name CI's pin, `cargo-deny@0.20.2`. +- **`bca report` renders its tables and notes correctly in both formats.** + A review of the published report found: HTML numeric column headers were + left-aligned over right-aligned cells (only `td.numeric` carried the + rule); notes shared with the Markdown renderer showed literal backticks + in HTML ("the \`bca.toml\` \`[thresholds]\` table"); the change-history + `Hotspot` column rendered `748436.0` beside thousands-separated + siblings; the Markdown pointer under that table told a `bca report` + reader to re-run with `--format csv`, which `report` rejects (it is + `bca vcs --format csv`); the HTML risk-heat bands graded rows against + the rendered top-N rather than every ranked file, so `--top 1` painted + the repository's riskiest file green; the sortable-table script sent a + blank numeric cell *first* on a descending sort; and the `Average CC` + note's `|`-joined fields read as an orphaned table row (rumdl 0.2.2's + MD075, four hits on the published report) directly under the + cyclomatic table. Headers are now + focusable (`tabindex`) and sort on Enter / Space, so the sort is + reachable without a mouse. +- **GFM table cells escape Markdown and HTML metacharacters.** A path + such as `a.py` became an element under a + non-sanitising renderer, `a&b.py` displayed as `a&b.py`, and + `__init__.py` rendered as bold `init.py`. `escape_gfm_cell` (shared by + the report, `check`'s `--summary-file` step-summary digest and + `exemptions`) now backslash-escapes `` < & ` * _ ~ [ ] `` alongside the + existing `\` and `|`; GFM renders each as the literal character. The + legend definitions, which are crate-authored prose, are no longer + passed through it. +- **The report legends say what the columns measure.** The Per-language + overview's `Files` / `Functions` / `Avg MI` / `Avg CC` / `Avg Cognitive` + were defined only as HTML hover tooltips, so a Markdown reader meeting + a negative `Avg MI` (the SLOC-weighted *unclamped* average of #725) had + only the per-file `MI` entry's "clamped to 0–100" to go on; both legends + now carry them, the `MI` entry points at the unclamped average, and + `Avg CC` names its population (every function, suppression ignored, + unlike the CC note's `Average CC`). `Exits`, `Methods`, `WMC`, `NPA` + and `NPM` said "out of the function" / "declared on the class" while + the columns are subtree sums (`nexits_sum`, `nom.total`, …, the + deliberate #709 accessor split); and `Comments` said "lines that are + entirely comment" while `cloc()` counts trailing comments too. ## [2.5.1] - 2026-11-06 diff --git a/big-code-analysis-book/src/commands/report.md b/big-code-analysis-book/src/commands/report.md index a871ebebf..2fbffd9b5 100644 --- a/big-code-analysis-book/src/commands/report.md +++ b/big-code-analysis-book/src/commands/report.md @@ -183,8 +183,12 @@ summaries, hotspot membership, and captions, so both formats report identical numbers. Both formats carry a **Legend** that defines every metric column -abbreviation (`CC`, `MI`, `ABC`, `WMC`, and so on) plus the -global-header stats (`PLOC`, `Comments`, `Comment ratio`). It is a +abbreviation (`CC`, `MI`, `ABC`, `WMC`, and so on), the +global-header stats (`PLOC`, `Comments`, `Comment ratio`), and the +Per-language overview's columns (`Files`, `Functions`, `Avg MI`, +`Avg CC`, `Avg Cognitive`) — `Avg MI` in particular, since it is the +unclamped, SLOC-weighted average and can read negative where the +per-file `MI` column saturates at 0. It is a `## Legend` section in Markdown (its own outline entry, not nested under the last language) and an expanded (`
`) block in HTML, so it survives print, mobile, and screen readers as well as a hover diff --git a/big-code-analysis-cli/src/html_report.rs b/big-code-analysis-cli/src/html_report.rs index a057d94db..f4bbbd22f 100644 --- a/big-code-analysis-cli/src/html_report.rs +++ b/big-code-analysis-cli/src/html_report.rs @@ -949,12 +949,12 @@ mod tests { // required to appear in real output without anyone remembering to // update the test. The hotspot metric columns own their tooltip on // the spec (`hotspot::legend_entries`); the Per-language overview's - // averaged / count columns supply theirs via `AST_OVERVIEW_TOOLTIPS`. + // averaged / count columns supply theirs via `OVERVIEW_LEGEND`. // `needle` embeds the rendered title directly, so a divergence // between the spec tooltip and the `title=` attribute surfaces here. for (header, tip) in hotspot::legend_entries() .into_iter() - .chain(AST_OVERVIEW_TOOLTIPS.iter().copied()) + .chain(hotspot::OVERVIEW_LEGEND.iter().copied()) { // A metric header now links its hosted chapter (issue #675), so // its text is wrapped in an ``; a non-metric overview header @@ -1290,7 +1290,7 @@ mod tests { assert!( report.contains( - "CC > 10: 1 functions | CC > 20: 0 functions (excluding suppressed functions)" + "CC > 10: 1 functions; CC > 20: 0 functions (excluding suppressed functions)" ), "HTML CC note must be captioned and exclude the suppressed cc=30:\n{report}" ); diff --git a/big-code-analysis-cli/src/html_report/sections.rs b/big-code-analysis-cli/src/html_report/sections.rs index 6ab926a4d..a9c8a6c80 100644 --- a/big-code-analysis-cli/src/html_report/sections.rs +++ b/big-code-analysis-cli/src/html_report/sections.rs @@ -441,7 +441,7 @@ fn emit_cc_note_html( // `cyclomatic = N`. let _ = writeln!( out, - "

Average CC: {:.1} | Max: {:.0} | CC > {:.0}: {} functions | CC > {:.0}: {} functions{caption}

", + "

Average CC: {:.1}; Max: {:.0}; CC > {:.0}: {} functions; CC > {:.0}: {} functions{caption}

", stats.avg(), stats.max, stats.primary_cutoff, diff --git a/big-code-analysis-cli/src/html_report/styling.rs b/big-code-analysis-cli/src/html_report/styling.rs index c688f4078..41d1cf1e4 100644 --- a/big-code-analysis-cli/src/html_report/styling.rs +++ b/big-code-analysis-cli/src/html_report/styling.rs @@ -349,26 +349,6 @@ keyed.forEach(function(e){tbody.appendChild(e.r);});\ })();\ "; -/// Tooltips for the Per-language overview table's columns, which are NOT -/// part of the hotspot `SPECS` (they are per-language aggregates, not -/// per-function rows). The averaged CC / Cognitive columns reuse the -/// shared metric definitions from [`crate::markdown_report::hotspot`] so -/// "Avg CC" and the hotspot "CC" column can never describe the same metric -/// differently. "Avg MI" is the exception: it is SLOC-weighted and derived -/// from the *unclamped* MI, so it uses [`hotspot::AVG_MI_TOOLTIP`] rather -/// than the per-file `MI_TOOLTIP` (issue #725). -/// "Files" here means *source files analysed*; the bus-factor table's -/// like-named column means files-per-directory and supplies its own -/// tooltip (issue #610), so this entry never leaks onto it. -pub(crate) const AST_OVERVIEW_TOOLTIPS: &[(&str, &str)] = &[ - ("SLOC", hotspot::SLOC_TOOLTIP), - ("Avg MI", hotspot::AVG_MI_TOOLTIP), - ("Avg CC", hotspot::CC_TOOLTIP), - ("Avg Cognitive", hotspot::COGNITIVE_TOOLTIP), - ("Functions", "Number of functions and methods analysed."), - ("Files", "Number of source files analysed."), -]; - /// Plain-English tooltip for a metric column header, or `None` when the /// header names a non-metric dimension (file, function, class, line, /// language) or a column whose table supplies its own tooltips @@ -376,12 +356,14 @@ pub(crate) const AST_OVERVIEW_TOOLTIPS: &[(&str, &str)] = &[ /// spec tooltips through [`write_table_with_tooltips`]). /// /// This lookup serves only the tables that call the plain [`write_table`] -/// (the Per-language overview), so it consults [`AST_OVERVIEW_TOOLTIPS`]. +/// (the Per-language overview), so it consults +/// [`hotspot::OVERVIEW_LEGEND`] — the one definition list, so the `title=` +/// attribute and the rendered legend cannot drift. /// The hotspot and VCS columns own their definitions on /// [`crate::markdown_report::hotspot::Column`] / /// [`crate::vcs_report::VcsColumn`] and never route through here. pub(crate) fn header_tooltip(header: &str) -> Option<&'static str> { - AST_OVERVIEW_TOOLTIPS + hotspot::OVERVIEW_LEGEND .iter() .find_map(|&(name, tip)| (name == header).then_some(tip)) } diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index 64d9c9576..971df53a6 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -555,14 +555,21 @@ pub(crate) fn write_table( } /// The hotspot-column legend plus the global-header stat definitions -/// (PLOC / Comments / Comment ratio), so the AST report's legend defines -/// every number on the page — including the header stats no hotspot column -/// covers (issue #679). Shared by the Markdown and HTML AST renderers so the -/// two legends carry the same rows. +/// (PLOC / Comments / Comment ratio) and the Per-language overview's +/// columns, so the AST report's legend defines every number on the page — +/// including the header stats no hotspot column covers (issue #679) and the +/// overview averages, whose `Avg MI` can read negative while the per-file +/// `MI` entry says "clamped to 0–100". Shared by the Markdown and HTML AST +/// renderers so the two legends carry the same rows. `SLOC` recurs in the +/// overview and is deduplicated on its first (hotspot) definition. pub(crate) fn legend_entries_with_header_stats() -> Vec<(&'static str, &'static str)> { - let mut entries = hotspot::legend_entries(); - entries.extend_from_slice(hotspot::HEADER_STAT_LEGEND); - entries + hotspot::dedup_legend( + hotspot::legend_entries() + .into_iter() + .chain(hotspot::HEADER_STAT_LEGEND.iter().copied()) + .chain(hotspot::OVERVIEW_LEGEND.iter().copied()) + .map(|(h, t)| (h, Some(t))), + ) } /// Append a "Legend" subsection at the given heading `level` (number of @@ -1479,7 +1486,7 @@ mod tests { } // Identity columns describe the row, not a metric; they must not // appear as legend bullets. - for identity in ["Function", "File", "Line", "Type"] { + for identity in ["Function", "File", "Line", "Type", "Language"] { assert!( !out.contains(&format!("- **{identity}**")), "identity column {identity:?} should not be in the legend" @@ -1487,6 +1494,89 @@ mod tests { } } + /// The Per-language overview's columns are defined on the page: a + /// reader meeting a negative `Avg MI` had, before this, only an `MI` + /// entry saying "clamped to 0–100" and nothing naming the overview's + /// unclamped average or the population behind `Avg CC`. + #[test] + fn markdown_legend_defines_the_overview_columns() { + let out = generate_report(&rich_fixture(), 5, SuppressionPolicy::Honor); + let legend = out.split("## Legend").nth(1).expect("legend section"); + for header in ["Files", "Functions", "Avg MI", "Avg CC", "Avg Cognitive"] { + assert!( + legend.contains(&format!("- **{header}** — ")), + "legend missing overview entry {header:?}:\n{legend}" + ); + } + // `SLOC` is both a hotspot column and an overview column; it is + // defined once, on its linked hotspot entry. + assert_eq!(legend.matches("- **[SLOC](").count(), 1); + assert!(!legend.contains("- **SLOC** — ")); + // The two MI definitions reconcile: the per-file entry says where + // the clamp applies and points at the unclamped average. + assert!(legend.contains("The overview's Avg MI is unclamped and can be negative.")); + assert!(legend.contains("- **Avg MI** — ") && legend.contains("reads negative")); + // `Avg CC` names its population and the figure it can disagree with. + assert!( + legend.contains("ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut"), + "Avg CC entry must say which functions it averages:\n{legend}" + ); + } + + /// `write_legend` emits each definition as Markdown prose, unescaped, + /// and the HTML legend passes the same string through `note_html`. + /// That is sound only while no definition carries a character the two + /// readers would treat differently: `<` and `&` (raw HTML / an entity + /// in Markdown, escaped in HTML), `*`, `_`, `[`, `~` (Markdown markup, + /// literal in HTML) — and `|`, which would break a table if a + /// definition ever moved into one. Backticks are the one exception, + /// by design: both renderers read a paired span as code, and inside + /// it Markdown renders every character literally (`` `commits_recent` ``), + /// so the check skips code spans. This test is what makes the bypass + /// true by construction rather than by inspection, for every legend + /// the crate renders — and it found the VCS wire keys rendering with + /// a bare `_` the first time it ran. + #[test] + fn legend_definitions_carry_no_markup_the_two_renderers_would_read_apart() { + let mut entries = legend_entries_with_header_stats(); + entries.extend(crate::vcs_report::all_legend_entries_for_test()); + assert!(entries.len() > 20, "the legends were collected"); + for (header, definition) in entries { + let segments: Vec<&str> = definition.split('`').collect(); + assert!( + segments.len() % 2 == 1, + "legend entry {header:?} has an unpaired backtick: {definition}" + ); + // Even-indexed segments are the prose between code spans. + for prose in segments.iter().step_by(2) { + for ch in ['<', '&', '*', '_', '[', '~', '|'] { + assert!( + !prose.contains(ch), + "legend entry {header:?} carries {ch:?} outside a code span, which Markdown and HTML would render differently: {definition}" + ); + } + } + } + } + + /// The CC note's fields are not joined by `|`: directly under a table + /// that spelling is an orphaned table row to a Markdown linter + /// (MD075) and renders as one in some viewers. + #[test] + fn cc_note_is_not_a_stray_table_row() { + let out = generate_report(&rich_fixture(), 5, SuppressionPolicy::Honor); + let notes: Vec<&str> = out + .lines() + .filter(|l| l.starts_with("Average CC: ")) + .collect(); + // One note per language in the fixture (Python and Rust). + assert_eq!(notes.len(), 2, "one CC note per language:\n{out}"); + for note in notes { + assert!(!note.contains('|'), "CC note must not carry a pipe: {note}"); + assert!(note.contains("; Max: "), "fields are `;`-joined: {note}"); + } + } + /// First-column cell values of a Markdown report section, in row order /// (header + separator skipped, identifier backticks stripped). A section /// title repeats once per language, so this gathers the rows of **every** @@ -2364,7 +2454,7 @@ mod tests { // CC note: captioned, and tallies only the visible function (max 12). assert!( report.contains( - "Average CC: 12.0 | Max: 12 | CC > 10: 1 functions | CC > 20: 0 functions \ + "Average CC: 12.0; Max: 12; CC > 10: 1 functions; CC > 20: 0 functions \ (excluding suppressed functions)" ), "CC note must be captioned and exclude the suppressed cc=30:\n{report}" diff --git a/big-code-analysis-cli/src/markdown_report/hotspot.rs b/big-code-analysis-cli/src/markdown_report/hotspot.rs index d8df80c7b..5b55fe9a3 100644 --- a/big-code-analysis-cli/src/markdown_report/hotspot.rs +++ b/big-code-analysis-cli/src/markdown_report/hotspot.rs @@ -105,7 +105,7 @@ pub(crate) struct Column { // specs the single source of truth. pub(crate) const CC_TOOLTIP: &str = "Cyclomatic Complexity: number of linearly independent control-flow paths through the function."; pub(crate) const COGNITIVE_TOOLTIP: &str = "Cognitive Complexity: how hard the code is for a human to follow; nesting and breaks in linear flow add weight."; -pub(crate) const MI_TOOLTIP: &str = "Maintainability Index (Visual Studio rescale, clamped to 0\u{2013}100): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW. Large files commonly clamp to 0 \u{2014} a property of the formula's range, not a meaningful score."; +pub(crate) const MI_TOOLTIP: &str = "Maintainability Index (Visual Studio rescale, clamped to 0\u{2013}100 in the per-file tables): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW. Large files commonly clamp to 0 \u{2014} a property of the formula's range, not a meaningful score. The overview's Avg MI is unclamped and can be negative."; /// The trailing note rendered under the MI hotspot table in both formats /// (issue #627). States which MI variant the column shows, the rating bands, @@ -120,12 +120,41 @@ pub(crate) const MI_NOTE: &str = "MI shown is the Visual Studio rescale (mi_visu /// `mi_visual_studio`): the overview average is SLOC-weighted and derived /// from the *unclamped* value, so it can go negative for an unmaintainable /// codebase instead of saturating at 0 (issue #725). -pub(crate) const AVG_MI_TOOLTIP: &str = "Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW."; +pub(crate) const AVG_MI_TOOLTIP: &str = "Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW; any value below 10, however negative, is LOW."; +/// Tooltip for the Per-language overview's `Avg CC` column. Names the +/// population — every function, suppression markers ignored — because the +/// CC note under the cyclomatic hotspot table averages a *different* set +/// (suppressed functions excluded) and the two figures can disagree. +pub(crate) const AVG_CC_TOOLTIP: &str = "Mean Cyclomatic Complexity over every function and method in the language, ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut (CC above 0 and, by default, not suppressed), so the two can differ."; +/// Tooltip for the Per-language overview's `Avg Cognitive` column. +pub(crate) const AVG_COGNITIVE_TOOLTIP: &str = "Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers."; +pub(crate) const FILES_TOOLTIP: &str = "Number of source files analysed."; +pub(crate) const FUNCTIONS_TOOLTIP: &str = "Number of functions and methods analysed."; + +/// Tooltip / legend definitions for the Per-language overview table, +/// which is NOT part of the hotspot [`SPECS`] (per-language aggregates, +/// not per-function rows); its header and alignment lists live with the +/// two `write_per_language_overview` / `write_overview_table` callers. +/// The HTML renderer attaches these as `title=` tooltips and both +/// renderers list them in the legend, so a reader who +/// meets a negative `Avg MI` has the explanation on the page rather than +/// only on hover. `Language` is an identity column and carries none. +/// "Files" here means *source files analysed*; the bus-factor table's +/// like-named column means files-per-directory and supplies its own +/// tooltip (issue #610), so this entry never leaks onto it. +pub(crate) const OVERVIEW_LEGEND: &[(&str, &str)] = &[ + ("Files", FILES_TOOLTIP), + ("SLOC", SLOC_TOOLTIP), + ("Functions", FUNCTIONS_TOOLTIP), + ("Avg MI", AVG_MI_TOOLTIP), + ("Avg CC", AVG_CC_TOOLTIP), + ("Avg Cognitive", AVG_COGNITIVE_TOOLTIP), +]; pub(crate) const SLOC_TOOLTIP: &str = "Source Lines Of Code: total physical lines, including blanks and comments."; pub(crate) const PLOC_TOOLTIP: &str = "Physical Lines Of Code: source lines excluding blank lines and comments."; -pub(crate) const COMMENTS_TOOLTIP: &str = "Comment lines (CLOC): lines that are entirely comment."; +pub(crate) const COMMENTS_TOOLTIP: &str = "Comment lines (CLOC): lines carrying a comment, whether standalone or trailing code; a line with both code and a comment counts toward PLOC and CLOC alike."; pub(crate) const COMMENT_RATIO_TOOLTIP: &str = "Comment ratio: comment lines as a percentage of source lines (CLOC / SLOC)."; pub(crate) const TOKENS_TOOLTIP: &str = @@ -136,14 +165,15 @@ pub(crate) const VOLUME_TOOLTIP: &str = "Halstead volume: program length weighted by vocabulary size."; pub(crate) const BUGS_TOOLTIP: &str = "Halstead bugs: estimated defect count derived from program volume."; -pub(crate) const EXITS_TOOLTIP: &str = - "Number of exit points (returns, throws, breaks out of the function)."; +pub(crate) const EXITS_TOOLTIP: &str = "Number of exit points (returns, throws, breaks out of the function), summed over the function and every function or closure nested in it."; pub(crate) const ABC_TOOLTIP: &str = "ABC magnitude: sqrt(A\u{B2} + B\u{B2} + C\u{B2}) over Assignments, Branches, and Conditions."; -pub(crate) const WMC_TOOLTIP: &str = "Weighted Methods per Class: sum of cyclomatic complexity across a type's methods. \"Type\" covers all six kinds counted here: class, struct, trait, impl, interface, namespace."; -pub(crate) const METHODS_TOOLTIP: &str = "Number of methods declared on the class."; -pub(crate) const NPA_TOOLTIP: &str = "Number of Public Attributes declared on the class."; -pub(crate) const NPM_TOOLTIP: &str = "Number of Public Methods declared on the class."; +pub(crate) const WMC_TOOLTIP: &str = "Weighted Methods per Class: sum of cyclomatic complexity across a type's methods, including the methods of any type nested in it. \"Type\" covers all six kinds counted here: class, struct, trait, impl, interface, namespace."; +pub(crate) const METHODS_TOOLTIP: &str = "Number of functions, methods and closures in the type, including those of any type nested in it."; +pub(crate) const NPA_TOOLTIP: &str = + "Number of Public Attributes in the type, including those of any type nested in it."; +pub(crate) const NPM_TOOLTIP: &str = + "Number of Public Methods in the type, including those of any type nested in it."; pub(crate) const ARGS_TOOLTIP: &str = "Number of declared parameters of the function."; /// Base URL of the hosted metric reference (the mdBook's metrics chapter), diff --git a/big-code-analysis-cli/src/markdown_report/sections.rs b/big-code-analysis-cli/src/markdown_report/sections.rs index 024d20883..61555172c 100644 --- a/big-code-analysis-cli/src/markdown_report/sections.rs +++ b/big-code-analysis-cli/src/markdown_report/sections.rs @@ -98,10 +98,12 @@ pub(super) fn emit_cc_note_md( .unwrap_or_default(); // The bands use the resolved advisory CC cutoff and its severe multiple // (issue #630) — `> 10` / `> 20` by default, shifted when a manifest sets - // `cyclomatic = N`. + // `cyclomatic = N`. The fields are joined by `;`, not `|`: a `|`-joined + // line directly under a table is an orphaned table row to a Markdown + // linter (MD075) and to some renderers. let _ = writeln!( out, - "Average CC: {:.1} | Max: {:.0} | CC > {:.0}: {} functions | CC > {:.0}: {} functions{caption}", + "Average CC: {:.1}; Max: {:.0}; CC > {:.0}: {} functions; CC > {:.0}: {} functions{caption}", stats.avg(), stats.max, stats.primary_cutoff, diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap index 5404ad866..956eaaa86 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap @@ -14,7 +14,7 @@ expression: out

Code Quality Metrics Summary

Files analyzed: 3 Languages: Python, Rust

-

Total SLOC: 400 PLOC: 290 Comments: 30

+

Total SLOC: 400 PLOC: 290 Comments: 30

Functions/methods: 10 Types: 1

Comment ratio: 7.5%

@@ -68,7 +68,7 @@ expression: out

Click a column header — or Tab to it and press Enter — to sort any table.

RankFileRiskCommits (recent)Commits (long)Churn (recent)Churn (long)Authors (recent)Authors (long)OwnershipBurstBug fixesSec fixesRevertsAge (d)Last mod (d)Change entropy (recent)Change entropy (long)Co-change entropy (recent)Co-change entropy (long)Hotspot
1src/hot.rs9.450602,0005,000230.750.5041020051.502.500.801.20123.0
1src/hot.rs9.450602,0005,000230.750.5041020051.502.500.801.20748,436
2src/warm.rs6.120308002,000230.750.5041020051.502.500.801.20
3docs/with|pipe.md2.011140100230.750.5041020051.502.500.801.20
` — the existing CSS arrow then shows on first @@ -766,10 +789,11 @@ mod tests { truncated_shallow_clone: false, vcs_aggregate: Some(sample_aggregate()), files: vec![ - entry("src/hot.rs", 9.4, 50, Some(123.0)), + entry("src/hot.rs", 9.4, 50, Some(748_436.0)), entry("src/warm.rs", 6.1, 20, None), entry("docs/with|pipe.md", 2.0, 1, None), ], + ranked_total: 3, } } @@ -1092,6 +1116,7 @@ mod tests { fn empty_report_emits_message_not_table() { let report = Report { files: Vec::new(), + ranked_total: 0, // No matched files means no authorship to aggregate, so the // bus-factor section is absent too. vcs_aggregate: None, @@ -1120,9 +1145,18 @@ mod tests { let html = render_html(&report); assert!(md.contains("| Hotspot |"), "Markdown keeps Hotspot header"); assert!(html.contains(">Hotspot748,436
- + @@ -88,7 +88,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
Python1120228.08.59.0
Rust2280821.423.422.6
- + @@ -105,7 +105,7 @@ expression: out
FileMISLOCTokens
FileMISLOCTokens
src/main.py28.0120800
-

Average CC: 8.5 | Max: 10 | CC > 10: 0 functions | CC > 20: 0 functions (excluding suppressed functions)

+

Average CC: 8.5; Max: 10; CC > 10: 0 functions; CC > 20: 0 functions (excluding suppressed functions)

Cognitive complexity hotspots (top 5 by Cognitive)

@@ -173,7 +173,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

- + @@ -194,7 +194,7 @@ expression: out
FileMISLOCTokens
FileMISLOCTokens
src/lib.rs12.02001,500
src/util.rs45.080600
-

Average CC: 12.6 | Max: 25 | CC > 10: 4 functions | CC > 20: 1 functions (excluding suppressed functions)

+

Average CC: 12.6; Max: 25; CC > 10: 4 functions; CC > 20: 1 functions (excluding suppressed functions)

Cognitive complexity hotspots (top 5 by Cognitive)

@@ -249,7 +249,7 @@ expression: out

Type hotspots (top 5 by WMC)

- + @@ -258,7 +258,7 @@ expression: out

Exit points hotspots (top 5 by Exits)

TypeFileLineWMCMethodsNPANPMSLOCTokens
TypeFileLineWMCMethodsNPANPMSLOCTokens
Widgetsrc/lib.rs250408261801,100
- + @@ -284,7 +284,7 @@ expression: out
Legend
-
MI
Maintainability Index (Visual Studio rescale, clamped to 0–100): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD ≥ 20, MODERATE ≥ 10, else LOW. Large files commonly clamp to 0 — a property of the formula's range, not a meaningful score.
+
MI
Maintainability Index (Visual Studio rescale, clamped to 0–100 in the per-file tables): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD ≥ 20, MODERATE ≥ 10, else LOW. Large files commonly clamp to 0 — a property of the formula's range, not a meaningful score. The overview's Avg MI is unclamped and can be negative.
SLOC
Source Lines Of Code: total physical lines, including blanks and comments.
Tokens
Total lexical tokens (AST leaves excluding comments) of the function or file.
CC
Cyclomatic Complexity: number of linearly independent control-flow paths through the function.
@@ -293,15 +293,20 @@ expression: out
Volume
Halstead volume: program length weighted by vocabulary size.
Est. Bugs
Halstead bugs: estimated defect count derived from program volume.
Args
Number of declared parameters of the function.
-
WMC
Weighted Methods per Class: sum of cyclomatic complexity across a type's methods. "Type" covers all six kinds counted here: class, struct, trait, impl, interface, namespace.
-
Methods
Number of methods declared on the class.
-
NPA
Number of Public Attributes declared on the class.
-
NPM
Number of Public Methods declared on the class.
-
Exits
Number of exit points (returns, throws, breaks out of the function).
+
WMC
Weighted Methods per Class: sum of cyclomatic complexity across a type's methods, including the methods of any type nested in it. "Type" covers all six kinds counted here: class, struct, trait, impl, interface, namespace.
+
Methods
Number of functions, methods and closures in the type, including those of any type nested in it.
+
NPA
Number of Public Attributes in the type, including those of any type nested in it.
+
NPM
Number of Public Methods in the type, including those of any type nested in it.
+
Exits
Number of exit points (returns, throws, breaks out of the function), summed over the function and every function or closure nested in it.
ABC
ABC magnitude: sqrt(A² + B² + C²) over Assignments, Branches, and Conditions.
PLOC
Physical Lines Of Code: source lines excluding blank lines and comments.
-
Comments
Comment lines (CLOC): lines that are entirely comment.
+
Comments
Comment lines (CLOC): lines carrying a comment, whether standalone or trailing code; a line with both code and a comment counts toward PLOC and CLOC alike.
Comment ratio
Comment ratio: comment lines as a percentage of source lines (CLOC / SLOC).
+
Files
Number of source files analysed.
+
Functions
Number of functions and methods analysed.
+
Avg MI
Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD ≥ 20, MODERATE ≥ 10, else LOW; any value below 10, however negative, is LOW.
+
Avg CC
Mean Cyclomatic Complexity over every function and method in the language, ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut (CC above 0 and, by default, not suppressed), so the two can differ.
+
Avg Cognitive
Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers.
diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap index c764f7e46..d7e8a240d 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap @@ -14,7 +14,7 @@ expression: out

Code Quality Metrics Summary

Files analyzed: 2 Languages: Python, Rust

-

Total SLOC: 40 PLOC: 50 Comments: 10

+

Total SLOC: 40 PLOC: 50 Comments: 10

Functions/methods: 3 Types: 0

Comment ratio: 25.0%

@@ -58,7 +58,7 @@ expression: out

Click a column header — or Tab to it and press Enter — to sort any table.

FunctionFileLineExitsCCSLOCTokens
FunctionFileLineExitsCCSLOCTokens
secret_internalsrc/lib.rs22010993002,000
handle_eventsrc/lib.rs10061270400
- + @@ -76,7 +76,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
Python120150.03.02.0
Rust120250.03.02.0
- + @@ -92,7 +92,7 @@ expression: out
FileMISLOCTokens
FileMISLOCTokens
src/main.py50.02030
-

Average CC: 3.0 | Max: 3 | CC > 10: 0 functions | CC > 20: 0 functions (excluding suppressed functions)

+

Average CC: 3.0; Max: 3; CC > 10: 0 functions; CC > 20: 0 functions (excluding suppressed functions)

Cognitive complexity hotspots (top 5 by Cognitive)

@@ -141,7 +141,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

- + @@ -158,7 +158,7 @@ expression: out
FileMISLOCTokens
FileMISLOCTokens
src/lib.rs50.02030
-

Average CC: 3.0 | Max: 3 | CC > 10: 0 functions | CC > 20: 0 functions (excluding suppressed functions)

+

Average CC: 3.0; Max: 3; CC > 10: 0 functions; CC > 20: 0 functions (excluding suppressed functions)

Cognitive complexity hotspots (top 5 by Cognitive)

@@ -203,7 +203,7 @@ expression: out
Legend
-
MI
Maintainability Index (Visual Studio rescale, clamped to 0–100): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD ≥ 20, MODERATE ≥ 10, else LOW. Large files commonly clamp to 0 — a property of the formula's range, not a meaningful score.
+
MI
Maintainability Index (Visual Studio rescale, clamped to 0–100 in the per-file tables): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD ≥ 20, MODERATE ≥ 10, else LOW. Large files commonly clamp to 0 — a property of the formula's range, not a meaningful score. The overview's Avg MI is unclamped and can be negative.
SLOC
Source Lines Of Code: total physical lines, including blanks and comments.
Tokens
Total lexical tokens (AST leaves excluding comments) of the function or file.
CC
Cyclomatic Complexity: number of linearly independent control-flow paths through the function.
@@ -212,15 +212,20 @@ expression: out
Volume
Halstead volume: program length weighted by vocabulary size.
Est. Bugs
Halstead bugs: estimated defect count derived from program volume.
Args
Number of declared parameters of the function.
-
WMC
Weighted Methods per Class: sum of cyclomatic complexity across a type's methods. "Type" covers all six kinds counted here: class, struct, trait, impl, interface, namespace.
-
Methods
Number of methods declared on the class.
-
NPA
Number of Public Attributes declared on the class.
-
NPM
Number of Public Methods declared on the class.
-
Exits
Number of exit points (returns, throws, breaks out of the function).
+
WMC
Weighted Methods per Class: sum of cyclomatic complexity across a type's methods, including the methods of any type nested in it. "Type" covers all six kinds counted here: class, struct, trait, impl, interface, namespace.
+
Methods
Number of functions, methods and closures in the type, including those of any type nested in it.
+
NPA
Number of Public Attributes in the type, including those of any type nested in it.
+
NPM
Number of Public Methods in the type, including those of any type nested in it.
+
Exits
Number of exit points (returns, throws, breaks out of the function), summed over the function and every function or closure nested in it.
ABC
ABC magnitude: sqrt(A² + B² + C²) over Assignments, Branches, and Conditions.
PLOC
Physical Lines Of Code: source lines excluding blank lines and comments.
-
Comments
Comment lines (CLOC): lines that are entirely comment.
+
Comments
Comment lines (CLOC): lines carrying a comment, whether standalone or trailing code; a line with both code and a comment counts toward PLOC and CLOC alike.
Comment ratio
Comment ratio: comment lines as a percentage of source lines (CLOC / SLOC).
+
Files
Number of source files analysed.
+
Functions
Number of functions and methods analysed.
+
Avg MI
Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD ≥ 20, MODERATE ≥ 10, else LOW; any value below 10, however negative, is LOW.
+
Avg CC
Mean Cyclomatic Complexity over every function and method in the language, ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut (CC above 0 and, by default, not suppressed), so the two can differ.
+
Avg Cognitive
Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers.
diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__markdown_report__tests__markdown_report_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__markdown_report__tests__markdown_report_rich.snap index d89d57ab0..49a32c0b6 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__markdown_report__tests__markdown_report_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__markdown_report__tests__markdown_report_rich.snap @@ -57,7 +57,7 @@ _MI shown is the Visual Studio rescale (mi_visual_studio), clamped to 0–100: G | `main` | src/main.py | 10 | 10 | 12 | 60 | 300 | | `load_data` | src/main.py | 40 | 7 | 6 | 35 | 180 | -Average CC: 8.5 | Max: 10 | CC > 10: 0 functions | CC > 20: 0 functions (excluding suppressed functions) +Average CC: 8.5; Max: 10; CC > 10: 0 functions; CC > 20: 0 functions (excluding suppressed functions) ### Cognitive complexity hotspots (top 5 by Cognitive) @@ -136,7 +136,7 @@ _MI shown is the Visual Studio rescale (mi_visual_studio), clamped to 0–100: G | `handle_event` | src/lib.rs | 100 | 12 | 14 | 70 | 400 | | `compute_score` | src/lib.rs | 130 | 8 | 9 | 40 | 200 | -Average CC: 12.6 | Max: 25 | CC > 10: 4 functions | CC > 20: 1 functions (excluding suppressed functions) +Average CC: 12.6; Max: 25; CC > 10: 4 functions; CC > 20: 1 functions (excluding suppressed functions) ### Cognitive complexity hotspots (top 5 by Cognitive) @@ -204,7 +204,7 @@ Average CC: 12.6 | Max: 25 | CC > 10: 4 functions | CC > 20: 1 functions (exclud ## Legend -- **[MI](https://dekobon.github.io/big-code-analysis/metrics.html#maintainability-index-mi)** — Maintainability Index (Visual Studio rescale, clamped to 0–100): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD ≥ 20, MODERATE ≥ 10, else LOW. Large files commonly clamp to 0 — a property of the formula's range, not a meaningful score. +- **[MI](https://dekobon.github.io/big-code-analysis/metrics.html#maintainability-index-mi)** — Maintainability Index (Visual Studio rescale, clamped to 0–100 in the per-file tables): composite of Halstead volume, cyclomatic complexity, and PLOC (the rows that carry code); higher is more maintainable. GOOD ≥ 20, MODERATE ≥ 10, else LOW. Large files commonly clamp to 0 — a property of the formula's range, not a meaningful score. The overview's Avg MI is unclamped and can be negative. - **[SLOC](https://dekobon.github.io/big-code-analysis/metrics.html#lines-of-code)** — Source Lines Of Code: total physical lines, including blanks and comments. - **[Tokens](https://dekobon.github.io/big-code-analysis/metrics.html#tokens)** — Total lexical tokens (AST leaves excluding comments) of the function or file. - **[CC](https://dekobon.github.io/big-code-analysis/metrics.html#cyclomatic-complexity-cc)** — Cyclomatic Complexity: number of linearly independent control-flow paths through the function. @@ -213,12 +213,17 @@ Average CC: 12.6 | Max: 25 | CC > 10: 4 functions | CC > 20: 1 functions (exclud - **[Volume](https://dekobon.github.io/big-code-analysis/metrics.html#halstead)** — Halstead volume: program length weighted by vocabulary size. - **[Est. Bugs](https://dekobon.github.io/big-code-analysis/metrics.html#halstead)** — Halstead bugs: estimated defect count derived from program volume. - **[Args](https://dekobon.github.io/big-code-analysis/metrics.html#nargs)** — Number of declared parameters of the function. -- **[WMC](https://dekobon.github.io/big-code-analysis/metrics.html#wmc)** — Weighted Methods per Class: sum of cyclomatic complexity across a type's methods. "Type" covers all six kinds counted here: class, struct, trait, impl, interface, namespace. -- **[Methods](https://dekobon.github.io/big-code-analysis/metrics.html#nom)** — Number of methods declared on the class. -- **[NPA](https://dekobon.github.io/big-code-analysis/metrics.html#npa)** — Number of Public Attributes declared on the class. -- **[NPM](https://dekobon.github.io/big-code-analysis/metrics.html#npm)** — Number of Public Methods declared on the class. -- **[Exits](https://dekobon.github.io/big-code-analysis/metrics.html#nexits)** — Number of exit points (returns, throws, breaks out of the function). +- **[WMC](https://dekobon.github.io/big-code-analysis/metrics.html#wmc)** — Weighted Methods per Class: sum of cyclomatic complexity across a type's methods, including the methods of any type nested in it. "Type" covers all six kinds counted here: class, struct, trait, impl, interface, namespace. +- **[Methods](https://dekobon.github.io/big-code-analysis/metrics.html#nom)** — Number of functions, methods and closures in the type, including those of any type nested in it. +- **[NPA](https://dekobon.github.io/big-code-analysis/metrics.html#npa)** — Number of Public Attributes in the type, including those of any type nested in it. +- **[NPM](https://dekobon.github.io/big-code-analysis/metrics.html#npm)** — Number of Public Methods in the type, including those of any type nested in it. +- **[Exits](https://dekobon.github.io/big-code-analysis/metrics.html#nexits)** — Number of exit points (returns, throws, breaks out of the function), summed over the function and every function or closure nested in it. - **[ABC](https://dekobon.github.io/big-code-analysis/metrics.html#abc)** — ABC magnitude: sqrt(A² + B² + C²) over Assignments, Branches, and Conditions. - **[PLOC](https://dekobon.github.io/big-code-analysis/metrics.html#lines-of-code)** — Physical Lines Of Code: source lines excluding blank lines and comments. -- **[Comments](https://dekobon.github.io/big-code-analysis/metrics.html#lines-of-code)** — Comment lines (CLOC): lines that are entirely comment. +- **[Comments](https://dekobon.github.io/big-code-analysis/metrics.html#lines-of-code)** — Comment lines (CLOC): lines carrying a comment, whether standalone or trailing code; a line with both code and a comment counts toward PLOC and CLOC alike. - **[Comment ratio](https://dekobon.github.io/big-code-analysis/metrics.html#lines-of-code)** — Comment ratio: comment lines as a percentage of source lines (CLOC / SLOC). +- **Files** — Number of source files analysed. +- **Functions** — Number of functions and methods analysed. +- **Avg MI** — Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD ≥ 20, MODERATE ≥ 10, else LOW; any value below 10, however negative, is LOW. +- **Avg CC** — Mean Cyclomatic Complexity over every function and method in the language, ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut (CC above 0 and, by default, not suppressed), so the two can differ. +- **Avg Cognitive** — Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers. diff --git a/big-code-analysis-cli/src/vcs_report.rs b/big-code-analysis-cli/src/vcs_report.rs index f1d158801..370bf3c3e 100644 --- a/big-code-analysis-cli/src/vcs_report.rs +++ b/big-code-analysis-cli/src/vcs_report.rs @@ -522,6 +522,14 @@ fn bus_factor_tooltips() -> [Option<&'static str>; 3] { /// in column order, skipping identity columns. Both the HTML legend and the /// Markdown legend draw from this so a column's definition renders /// identically in the `title=` tooltip and the legend (issue #611). +/// Every legend entry the change-history pages can render — all columns, +/// Hotspot included, plus the bus-factor pair — for the crate-wide +/// legend-prose invariant test in `markdown_report`. +#[cfg(test)] +pub(crate) fn all_legend_entries_for_test() -> Vec<(&'static str, &'static str)> { + legend_entries(&VCS_SPECS.iter().collect::>()) +} + fn legend_entries(specs: &[&VcsColumn]) -> Vec<(&'static str, &'static str)> { // The bus-factor columns render in the same page but live outside // `VCS_SPECS`, so chain them onto the spec-driven pairs. From f0aa04ee6340bc320c884bf746688bc9fa747bf4 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:52:48 -0800 Subject: [PATCH 7/8] refactor(cli): derive the overview table from one column spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Per-language overview was the one spec-less table in the two renderers: its header and alignment lists were written twice, byte-identical, in `markdown_report.rs` and `html_report/sections.rs`, and its tooltips lived in a third place (`hotspot::OVERVIEW_LEGEND`), joined to the headers by string lookup through `styling:: header_tooltip` and the HTML `write_table` / `write_table_classed` pair that existed only to serve that path. A new overview column with no legend entry was caught by nothing automatic. `markdown_report/overview.rs` now holds the seven columns as `OVERVIEW_SPECS` — header, alignment, cell projector and tooltip, the shape `hotspot::SPECS` and `vcs_report::VCS_SPECS` already have — with `LangOverview` carrying the per-language aggregates the two folds compute (moved verbatim from `markdown_report.rs`) and the five overview tooltip consts moved out of `hotspot.rs`. Both renderers build the row from `LangOverview::cells()`; the HTML side goes through `write_table_with_tooltips` like every other table, and the three deleted helpers take their string-keyed lookup with them. `Cell::Text` carries the `Language` display name (a `Path` in all but name; `Name` would add a code span), and `Cell::into_text` replaces the or-pattern two consumers had each spelled out. Output is byte-identical: no snapshot moves. The Markdown overview's `Language` cell is now GFM-escaped where before it was written raw, and a test sweeping every `LANG` display name pins that none needs it, so a future name that does changes that test rather than a snapshot. Two further tests pin the seven headers, the alignment row, both fixture data rows and the five tooltips by hand against each renderer's output — independently of the spec, since a test that derives its expectations from `OVERVIEW_SPECS` drops an assertion along with whatever was removed — and read a header's label as its first text run, so a control wrapping it does not move them. --- .bca-baseline.toml | 10 +- big-code-analysis-cli/src/html_report.rs | 93 ++---- .../src/html_report/sections.rs | 53 ++-- .../src/html_report/styling.rs | 19 -- big-code-analysis-cli/src/markdown_report.rs | 269 +++++++++++++----- .../src/markdown_report/hotspot.rs | 51 +--- .../src/markdown_report/overview.rs | 184 ++++++++++++ .../src/markdown_report/sections.rs | 2 +- big-code-analysis-cli/src/vcs_report.rs | 20 +- 9 files changed, 454 insertions(+), 247 deletions(-) create mode 100644 big-code-analysis-cli/src/markdown_report/overview.rs diff --git a/.bca-baseline.toml b/.bca-baseline.toml index dde6e8a73..bd75c918f 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -601,12 +601,6 @@ qualified = "generate_html_report_with_vcs" metric = "nargs" value = 6.0 -[[entry]] -path = "big-code-analysis-cli/src/html_report.rs" -qualified = "write_table_classed" -metric = "nargs" -value = 5.0 - [[entry]] path = "big-code-analysis-cli/src/html_report.rs" qualified = "write_table_classed_with_tooltips" @@ -653,7 +647,7 @@ value = 49443.19551903411 path = "big-code-analysis-cli/src/markdown_report.rs" qualified = "" metric = "loc.ploc" -value = 637.0 +value = 583.0 [[entry]] path = "big-code-analysis-cli/src/markdown_report.rs" @@ -683,7 +677,7 @@ value = 6.0 path = "big-code-analysis-cli/src/markdown_report/hotspot.rs" qualified = "" metric = "loc.ploc" -value = 707.0 +value = 701.0 [[entry]] path = "big-code-analysis-cli/src/markdown_report/hotspot.rs" diff --git a/big-code-analysis-cli/src/html_report.rs b/big-code-analysis-cli/src/html_report.rs index f4bbbd22f..ea8aa5b9e 100644 --- a/big-code-analysis-cli/src/html_report.rs +++ b/big-code-analysis-cli/src/html_report.rs @@ -38,8 +38,8 @@ use big_code_analysis::{SpaceKind, SuppressionPolicy}; use crate::markdown_report::advisory::{AdvisoryCounts, AdvisoryThresholds}; use crate::markdown_report::hotspot::{self, Align, Cell, HotspotSpec, SPECS}; use crate::markdown_report::{ - FunctionSummary, LanguageTotals, comment_ratio_percent, is_class_like, lang_overview_row, - language_display_name, rated_avg_mi, thousands, + FunctionSummary, LanguageTotals, comment_ratio_percent, is_class_like, language_display_name, + overview, rated_avg_mi, thousands, }; mod sections; @@ -62,54 +62,19 @@ pub(crate) struct RankedColumn { /// Write a `
` with one `` and one /// ``. `aligns` controls per-cell text alignment AND the /// `data-numeric="1"` attribute that the inline sort handler reads to -/// pick numeric vs string comparison. -/// -/// Cell strings are escaped via [`escape_html`]; do not pre-escape. -pub(crate) fn write_table( - out: &mut String, - headers: &[&str], - aligns: &[Align], - rows: &[Vec], -) { - // No extra per-cell classes: every cell carries only its - // alignment-derived `numeric` class. The overview table is unranked, - // so no header announces an initial sort. - write_table_classed(out, headers, aligns, rows, |_, _| None); -} - -/// Like [`write_table`], but a `cell_class` callback can contribute an -/// extra CSS class (e.g. a severity-heat band) to a specific `` row: one `"); for (i, (h, a)) in headers.iter().zip(aligns).enumerate() { @@ -169,7 +132,7 @@ fn write_table_head<'t>( { let _ = write!(out, " aria-sort=\"{}\"", rank.dir); } - if let Some(tip) = tooltip_for(i, h) { + if let Some(tip) = tooltips.get(i).copied().flatten() { let _ = write!(out, " title=\"{}\"", escape_html(tip)); } // Link the header text to its hosted metric chapter when one exists @@ -194,16 +157,16 @@ fn write_table_head<'t>( } /// Shared table body for the HTML renderers: `cell_class` contributes an -/// optional per-cell CSS class keyed by `(row, col)`, and `tooltip_for` -/// resolves each header's `title=` text by `(col_index, header)`. -fn write_table_core<'t>( +/// optional per-cell CSS class keyed by `(row, col)`, and `tooltips[i]` +/// is column `i`'s `title=` text. +fn write_table_core( out: &mut String, headers: &[&str], aligns: &[Align], + tooltips: &[Option<&str>], rows: &[Vec], ranked: Option, cell_class: impl Fn(usize, usize) -> Option<&'static str>, - tooltip_for: impl Fn(usize, &str) -> Option<&'t str>, ) { debug_assert_eq!(headers.len(), aligns.len()); // Wrap every table in an overflow-x scroll container so a wide table @@ -211,7 +174,7 @@ fn write_table_core<'t>( // clipping its right-most metric columns past a narrow viewport (issue // #686). `white-space:nowrap` cells stay; the wrapper handles overflow. let _ = out.write_str("
\n
`, -/// keyed by `(row_index, column_index)`. The returned class is appended -/// after the alignment-derived `numeric` class on a single -/// space-separated `class="…"` attribute, so [`escape_html`] still runs -/// exactly once per cell and the attribute is never doubled. -pub(crate) fn write_table_classed( - out: &mut String, - headers: &[&str], - aligns: &[Align], - rows: &[Vec], - cell_class: impl Fn(usize, usize) -> Option<&'static str>, -) { - // Resolve each header's tooltip via the string-keyed overview - // catalogue (the only caller that takes this path is the Per-language - // overview). - write_table_core(out, headers, aligns, rows, None, cell_class, |_, h| { - header_tooltip(h) - }); -} - -/// Like [`write_table`], but each column's tooltip is supplied explicitly -/// by index rather than resolved from a string-keyed catalogue. This is -/// the path the hotspot and change-history tables take: their tooltip is -/// already authoritative on the shared column spec -/// ([`crate::markdown_report::hotspot::Column`] / -/// [`crate::vcs_report::VcsColumn`]), and passing it positionally avoids -/// the header-string ambiguity that made the bus-factor "Files" column +/// pick numeric vs string comparison. Each column's tooltip is supplied +/// positionally: every table's tooltip is authoritative on its column +/// spec ([`crate::markdown_report::hotspot::Column`], +/// [`crate::markdown_report::overview::OverviewColumn`], +/// [`crate::vcs_report::VcsColumn`]), and passing it by index avoids the +/// header-string ambiguity that once made the bus-factor "Files" column /// inherit the unrelated "source files analysed" definition (issue #610). /// `tooltips[i]` is the `title=` text for column `i`; `None` leaves the /// header bare. `ranked` names the column the table is already sorted by /// (and the direction) so its `` carries `aria-sort` at render time; /// pass `None` for an unranked table. +/// +/// Cell strings are escaped via [`escape_html`]; do not pre-escape. pub(crate) fn write_table_with_tooltips( out: &mut String, headers: &[&str], @@ -133,20 +98,18 @@ pub(crate) fn write_table_classed_with_tooltips( cell_class: impl Fn(usize, usize) -> Option<&'static str>, ) { debug_assert_eq!(headers.len(), tooltips.len()); - write_table_core(out, headers, aligns, rows, ranked, cell_class, |i, _| { - tooltips.get(i).copied().flatten() - }); + write_table_core(out, headers, aligns, tooltips, rows, ranked, cell_class); } /// Emit the `
` per header, carrying its numeric hint, /// the pre-ranked column's `aria-sort`, an optional tooltip, and a link to the /// metric's hosted chapter when one exists. -fn write_table_head<'t>( +fn write_table_head( out: &mut String, headers: &[&str], aligns: &[Align], + tooltips: &[Option<&str>], ranked: Option, - tooltip_for: impl Fn(usize, &str) -> Option<&'t str>, ) { let _ = out.write_str("
\n"); - write_table_head(out, headers, aligns, ranked, tooltip_for); + write_table_head(out, headers, aligns, tooltips, ranked); let _ = out.write_str("\n"); for (r, row) in rows.iter().enumerate() { debug_assert_eq!(row.len(), headers.len()); @@ -949,12 +912,12 @@ mod tests { // required to appear in real output without anyone remembering to // update the test. The hotspot metric columns own their tooltip on // the spec (`hotspot::legend_entries`); the Per-language overview's - // averaged / count columns supply theirs via `OVERVIEW_LEGEND`. + // averaged / count columns supply theirs via `overview::legend`. // `needle` embeds the rendered title directly, so a divergence // between the spec tooltip and the `title=` attribute surfaces here. for (header, tip) in hotspot::legend_entries() .into_iter() - .chain(hotspot::OVERVIEW_LEGEND.iter().copied()) + .chain(overview::legend()) { // A metric header now links its hosted chapter (issue #675), so // its text is wrapped in an ``; a non-metric overview header @@ -975,12 +938,16 @@ mod tests { } // Non-metric labels must remain bare so click-to-sort UX is not - // crowded with redundant tooltips for self-describing columns. + // crowded with redundant tooltips for self-describing columns. The + // overview's one identity column is declared tooltip-less on its + // spec; the hotspot identity columns are `tooltip: None` on theirs. + assert!( + overview::OVERVIEW_SPECS + .iter() + .all(|c| (c.header == "Language") == c.tooltip.is_none()), + "Language is the overview's only tooltip-less column" + ); for plain in ["File", "Function", "Type", "Line", "Language"] { - assert!( - header_tooltip(plain).is_none(), - "header {plain:?} should not carry a tooltip" - ); let needle = format!(">{plain}"); assert!( out.contains(&needle), diff --git a/big-code-analysis-cli/src/html_report/sections.rs b/big-code-analysis-cli/src/html_report/sections.rs index a9c8a6c80..2da73c749 100644 --- a/big-code-analysis-cli/src/html_report/sections.rs +++ b/big-code-analysis-cli/src/html_report/sections.rs @@ -95,10 +95,11 @@ impl Headings { } /// Render a hotspot table from the shared [`Column`] descriptors. Builds the -/// parallel `headers`/`aligns`/`rows` arrays and delegates to [`write_table`], -/// the single source of truth for table bytes and escaping. HTML escapes -/// every cell uniformly, so the raw [`Cell`] payload (regardless of kind) is -/// handed to `write_table`, whose `escape_html` runs exactly once per cell. +/// parallel `headers`/`aligns`/`rows` arrays and delegates to +/// [`write_table_with_tooltips`], the single source of truth for table +/// bytes and escaping. HTML escapes every cell uniformly, so the raw +/// [`Cell`] payload (regardless of kind) is handed over, and `escape_html` +/// runs exactly once per cell. fn write_hotspot_table(out: &mut String, spec: &HotspotSpec, entries: &[&FunctionSummary]) { let columns = spec.columns; let mut headers = Vec::with_capacity(columns.len()); @@ -113,8 +114,7 @@ fn write_hotspot_table(out: &mut String, spec: &HotspotSpec, entries: &[&Functio for s in entries { let mut row: Vec = Vec::with_capacity(columns.len()); for col in columns { - let (Cell::Name(text) | Cell::Path(text) | Cell::Num(text)) = (col.cell)(s); - row.push(text); + row.push((col.cell)(s).into_text()); } rows.push(row); } @@ -247,30 +247,25 @@ pub(crate) fn write_overview_table( let _ = out.write_str( "

Click a column header \u{2014} or Tab to it and press Enter \u{2014} to sort any table.

\n", ); - let mut rows: Vec> = Vec::with_capacity(by_lang.len()); - for (&lang_name, lang_summaries) in by_lang { - rows.push(lang_overview_row(lang_name, lang_summaries)); - } - write_table( + let rows: Vec> = by_lang + .iter() + .map(|(&lang_name, lang_summaries)| { + overview::LangOverview::from_summaries(lang_name, lang_summaries) + .cells() + .into_iter() + .map(Cell::into_text) + .collect() + }) + .collect(); + // The column spec carries the authoritative tooltip; pass it + // positionally so each header's `title=` matches the legend exactly. + // The overview is unranked, so no header announces an initial sort. + write_table_with_tooltips( out, - &[ - "Language", - "Files", - "SLOC", - "Functions", - "Avg MI", - "Avg CC", - "Avg Cognitive", - ], - &[ - Align::Left, - Align::Right, - Align::Right, - Align::Right, - Align::Right, - Align::Right, - Align::Right, - ], + &overview::headers(), + &overview::aligns(), + &overview::tooltips(), + None, &rows, ); } diff --git a/big-code-analysis-cli/src/html_report/styling.rs b/big-code-analysis-cli/src/html_report/styling.rs index 41d1cf1e4..5fc862562 100644 --- a/big-code-analysis-cli/src/html_report/styling.rs +++ b/big-code-analysis-cli/src/html_report/styling.rs @@ -349,25 +349,6 @@ keyed.forEach(function(e){tbody.appendChild(e.r);});\ })();\ "; -/// Plain-English tooltip for a metric column header, or `None` when the -/// header names a non-metric dimension (file, function, class, line, -/// language) or a column whose table supplies its own tooltips -/// out-of-band (the hotspot and change-history tables, which pass their -/// spec tooltips through [`write_table_with_tooltips`]). -/// -/// This lookup serves only the tables that call the plain [`write_table`] -/// (the Per-language overview), so it consults -/// [`hotspot::OVERVIEW_LEGEND`] — the one definition list, so the `title=` -/// attribute and the rendered legend cannot drift. -/// The hotspot and VCS columns own their definitions on -/// [`crate::markdown_report::hotspot::Column`] / -/// [`crate::vcs_report::VcsColumn`] and never route through here. -pub(crate) fn header_tooltip(header: &str) -> Option<&'static str> { - hotspot::OVERVIEW_LEGEND - .iter() - .find_map(|&(name, tip)| (name == header).then_some(tip)) -} - /// Write the shared HTML preamble (doctype, head with the inline CSS, and /// the opening `

`). `title` fills the `` element and `heading` /// the `<h1>`; both are escaped. Shared by the AST report and the VCS diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index 971df53a6..a1a6bd365 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -14,6 +14,7 @@ pub(crate) mod advisory; pub(crate) mod hotspot; +pub(crate) mod overview; mod sections; // `Align` now lives in the format-neutral `hotspot` module; re-export it so @@ -567,7 +568,7 @@ pub(crate) fn legend_entries_with_header_stats() -> Vec<(&'static str, &'static hotspot::legend_entries() .into_iter() .chain(hotspot::HEADER_STAT_LEGEND.iter().copied()) - .chain(hotspot::OVERVIEW_LEGEND.iter().copied()) + .chain(overview::legend()) .map(|(h, t)| (h, Some(t))), ) } @@ -1031,88 +1032,24 @@ fn write_global_header( fn write_per_language_overview(out: &mut String, by_lang: &BTreeMap<&str, Vec<&FunctionSummary>>) { let _ = writeln!(out, "\n## Per-language overview\n"); - let mut overview_rows: Vec<Vec<String>> = Vec::with_capacity(by_lang.len()); - for (&lang_name, lang_summaries) in by_lang { - overview_rows.push(lang_overview_row(lang_name, lang_summaries)); - } + let overview_rows: Vec<Vec<String>> = by_lang + .iter() + .map(|(&lang_name, lang_summaries)| { + overview::LangOverview::from_summaries(lang_name, lang_summaries) + .cells() + .into_iter() + .map(render_cell_md) + .collect() + }) + .collect(); write_table( out, - &[ - "Language", - "Files", - "SLOC", - "Functions", - "Avg MI", - "Avg CC", - "Avg Cognitive", - ], - &[ - Align::Left, - Align::Right, - Align::Right, - Align::Right, - Align::Right, - Align::Right, - Align::Right, - ], + &overview::headers(), + &overview::aligns(), &overview_rows, ); } -/// The seven-cell per-language overview row both reports render: Files / -/// SLOC / Functions and the averages over one language's summaries. -pub(crate) fn lang_overview_row( - lang_name: &str, - lang_summaries: &[&FunctionSummary], -) -> Vec<String> { - let (unit_count, lang_sloc, avg_mi) = unit_aggregates(lang_summaries); - let (func_count, avg_cc, avg_cog) = function_aggregates(lang_summaries); - vec![ - language_display_name(lang_name).into_owned(), - thousands(unit_count), - thousands(lang_sloc), - thousands(func_count), - // An empty cell, not `n/a`, when no file had code to measure: the - // HTML table sorter reads an empty cell as "no value" and sorts it - // last in either direction; any other text would parse as NaN and - // sort the same way, but read as a value in the cell. - avg_mi.map_or_else(String::new, |mi| format!("{mi:.1}")), - format!("{avg_cc:.1}"), - format!("{avg_cog:.1}"), - ] -} - -fn unit_aggregates(lang_summaries: &[&FunctionSummary]) -> (usize, usize, Option<f64>) { - let mut count = 0usize; - let mut sloc = 0usize; - let mut mi = MiAverage::default(); - for s in lang_summaries.iter().filter(|s| s.kind == SpaceKind::Unit) { - count += 1; - sloc += s.sloc; - mi.add(s); - } - (count, sloc, mi.average()) -} - -fn function_aggregates(lang_summaries: &[&FunctionSummary]) -> (usize, f64, f64) { - let mut count = 0usize; - let mut cc_sum = 0.0f64; - let mut cog_sum = 0.0f64; - for s in lang_summaries - .iter() - .filter(|s| s.kind == SpaceKind::Function) - { - count += 1; - cc_sum += s.cyclomatic; - cog_sum += s.cognitive; - } - if count > 0 { - (count, cc_sum / count as f64, cog_sum / count as f64) - } else { - (0, 0.0, 0.0) - } -} - fn write_language_section( out: &mut String, lang_name: &str, @@ -1494,6 +1431,184 @@ mod tests { } } + /// The overview's seven columns, pinned by hand against each + /// renderer's actual output rather than read off `OVERVIEW_SPECS`, + /// so a column dropped from the spec fails here instead of taking + /// its own assertion with it. Covers the header row, the alignment + /// row and both of the rich fixture's data rows (Rust and Python) in + /// Markdown, and the `<thead>` text in HTML — the latter extracted by + /// stripping tags, so a control inside a `<th>` does not break it. + #[test] + fn overview_columns_render_in_the_pinned_order_in_both_formats() { + const HEADERS: [&str; 7] = [ + "Language", + "Files", + "SLOC", + "Functions", + "Avg MI", + "Avg CC", + "Avg Cognitive", + ]; + let md = generate_report(&rich_fixture(), 5, SuppressionPolicy::Honor); + let section = md + .split("## Per-language overview\n") + .nth(1) + .expect("overview section"); + let rows: Vec<Vec<&str>> = section + .lines() + .skip_while(|l| l.is_empty()) + .take_while(|l| l.starts_with('|')) + .map(|l| l.trim_matches('|').split('|').map(str::trim).collect()) + .collect(); + assert_eq!( + rows.len(), + 4, + "header, separator, two languages:\n{section}" + ); + assert_eq!(rows[0], HEADERS); + assert!( + rows[1][0].chars().all(|c| c == '-'), + "Language is left-aligned" + ); + for (i, sep) in rows[1][1..].iter().enumerate() { + assert!( + sep.ends_with(':') && !sep.starts_with(':'), + "column {} is right-aligned: {sep:?}", + HEADERS[i + 1] + ); + } + // Rust: two units (200 + 80 SLOC), eight functions; the fixture + // keeps `mi_original` coherent with the displayed value, so the + // SLOC-weighted unclamped average is (20.5*200 + 77*80)/280 * 100/171 + // = 21.43. Python: one unit, 47.9 * 100/171 = 28.0. + assert_eq!(rows[2], ["Python", "1", "120", "2", "28.0", "8.5", "9.0"]); + assert_eq!(rows[3], ["Rust", "2", "280", "8", "21.4", "23.4", "22.6"]); + + let html = + crate::html_report::generate_html_report(&rich_fixture(), 5, SuppressionPolicy::Honor); + let got: Vec<String> = overview_header_cells(&html) + .into_iter() + .map(|(_, label)| label) + .collect(); + assert_eq!(got, HEADERS, "HTML overview header text:\n{html}"); + } + + /// The HTML overview's header cells as `(opening tag, label)` pairs, + /// one per `<th>`. The label is the cell's *first* text run only, so a + /// control wrapping the label or a glyph following it (a sort button, + /// a documentation link) does not change what the tests compare. + fn overview_header_cells(html: &str) -> Vec<(String, String)> { + let thead = html + .split("Per-language overview</h2>") + .nth(1) + .and_then(|t| t.split("<thead>").nth(1)) + .and_then(|t| t.split("</thead>").next()) + .expect("overview thead"); + thead + .split("<th") + .skip(1) + .map(|cell| { + let tag_end = cell.find('>').expect("th opening tag closes"); + let opening = format!("<th{}", &cell[..=tag_end]); + let mut label = String::new(); + let mut in_tag = false; + for ch in cell[tag_end + 1..].chars() { + match ch { + '<' => { + if !label.trim().is_empty() { + break; + } + in_tag = true; + } + '>' => in_tag = false, + _ if !in_tag => label.push(ch), + _ => {} + } + } + (opening, label.trim().to_owned()) + }) + .collect() + } + + /// The extractor the two overview tests share reads a header's label + /// as its first text run, so a sort control around the label and a + /// documentation glyph after it — the markup the sortable-header + /// work renders — leave the comparison unchanged. + #[test] + fn overview_header_extraction_survives_a_control_and_a_glyph() { + let html = "x<h2>Per-language overview</h2><table><thead><tr>\ + <th scope=\"col\"><button type=\"button\" class=\"sort\">Language<span aria-hidden=\"true\"></span></button></th>\ + <th scope=\"col\" data-numeric=\"1\" title=\"Source Lines\"><button type=\"button\" class=\"sort\">SLOC</button><a class=\"doc\" href=\"#\">?</a></th>\ + </tr></thead></table>"; + let cells = overview_header_cells(html); + let labels: Vec<&str> = cells.iter().map(|(_, l)| l.as_str()).collect(); + assert_eq!(labels, ["Language", "SLOC"]); + assert!(cells[1].0.contains(" title=\"Source Lines\"")); + assert!( + !cells[1].0.contains("button"), + "opening tag only: {}", + cells[1].0 + ); + } + + /// The overview's five tooltips, pinned by hand against both outputs + /// for the same reason: the spec-driven tooltip loop in + /// `html_report` skips a `None`, so it cannot see a tooltip that was + /// blanked. + #[test] + fn overview_tooltips_reach_both_renderers() { + const EXPECTED: [(&str, &str); 5] = [ + ("Files", "Number of source files analysed."), + ("Functions", "Number of functions and methods analysed."), + ("Avg MI", "Average Maintainability Index, SLOC-weighted"), + ("Avg CC", "Mean Cyclomatic Complexity over every function"), + ( + "Avg Cognitive", + "Mean Cognitive Complexity over every function", + ), + ]; + let md = generate_report(&rich_fixture(), 5, SuppressionPolicy::Honor); + let legend = md.split("## Legend").nth(1).expect("legend section"); + let html = + crate::html_report::generate_html_report(&rich_fixture(), 5, SuppressionPolicy::Honor); + let cells = overview_header_cells(&html); + for (header, text) in EXPECTED { + let bullet = legend + .lines() + .find(|l| l.starts_with(&format!("- **{header}** — "))) + .unwrap_or_else(|| panic!("legend bullet for {header}:\n{legend}")); + assert!(bullet.contains(text), "{header} legend text: {bullet}"); + let (opening, _) = cells + .iter() + .find(|(_, label)| label == header) + .unwrap_or_else(|| panic!("overview th for {header}:\n{cells:?}")); + assert!( + opening.contains(&format!(" title=\"{text}")), + "{header} title attribute: {opening}" + ); + } + } + + /// Every language display name survives GFM cell escaping unchanged. + /// The overview's `Language` cell is a `Cell::Text`, so it is escaped + /// in Markdown; today no name needs it (`C++`, `C#`, `C/C++ + /// Preprocessor` carry nothing in the escape set), which is what + /// made adopting the spec byte-identical. A future name that does + /// need escaping changes this test deliberately rather than a + /// snapshot silently. + #[test] + fn language_display_names_need_no_gfm_escaping() { + for lang in LANG::into_enum_iter() { + let display = language_display_name(lang.name()); + assert_eq!( + escape_cell(&display), + display.as_ref(), + "{} would render escaped in the Markdown overview", + lang.name() + ); + } + } + /// The Per-language overview's columns are defined on the page: a /// reader meeting a negative `Avg MI` had, before this, only an `MI` /// entry saying "clamped to 0–100" and nothing naming the overview's diff --git a/big-code-analysis-cli/src/markdown_report/hotspot.rs b/big-code-analysis-cli/src/markdown_report/hotspot.rs index 5b55fe9a3..a1a05b8a9 100644 --- a/big-code-analysis-cli/src/markdown_report/hotspot.rs +++ b/big-code-analysis-cli/src/markdown_report/hotspot.rs @@ -5,7 +5,7 @@ //! This module decides WHICH functions appear in each hotspot section, in //! what order, with what suppression, plus the per-section columns and the //! cyclomatic summary stats. It does NOT decide escaping or table markup — -//! each renderer keeps its own `write_table` and maps a [`Cell`] to its own +//! each renderer keeps its own table writer and maps a [`Cell`] to its own //! format. Sharing the [`SPECS`] table is what keeps the two reports from //! diverging (the "same data" guarantee; see the book's report //! "Format consistency" section). Despite living under `markdown_report`, @@ -69,17 +69,29 @@ pub(crate) enum Source { /// correctly. The payload is already value-formatted; only escaping differs: /// HTML escapes every kind uniformly via `escape_html`; Markdown wraps a /// [`Cell::Name`] in backticks (`escape_name`), GFM-escapes a [`Cell::Path`] -/// (`escape_cell`), and emits a [`Cell::Num`] raw. +/// or [`Cell::Text`] (`escape_cell`), and emits a [`Cell::Num`] raw. #[derive(Clone)] pub(crate) enum Cell { /// A function or class identifier. Name(String), /// A file path. Path(String), + /// Plain prose that is neither a path nor an identifier (a language + /// display name); GFM-escaped like a path. + Text(String), /// Pre-formatted numeric text (escaping is a no-op in either format). Num(String), } +impl Cell { + /// The payload regardless of kind, for HTML, where the table writer + /// escapes every kind uniformly so the kind itself does not matter. + pub(crate) fn into_text(self) -> String { + let (Self::Name(t) | Self::Path(t) | Self::Text(t) | Self::Num(t)) = self; + t + } +} + /// One column: header, alignment, a capture-free projector to a [`Cell`], /// and an optional plain-English `tooltip`. The tooltip is the single /// source of a metric column's definition: the HTML renderer attaches it @@ -115,41 +127,6 @@ pub(crate) const MI_TOOLTIP: &str = "Maintainability Index (Visual Studio rescal /// (`mi.original` / `mi.sei`), so the column number and the gate number are /// not one-to-one comparable. pub(crate) const MI_NOTE: &str = "MI shown is the Visual Studio rescale (mi_visual_studio), clamped to 0\u{2013}100: GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW. Large files commonly clamp to 0 \u{2014} a property of the formula's range, not a meaningful score; rows are still ranked by the unclamped value so the order remains informative. The bca check gate may evaluate a different MI variant (mi.original or mi.sei), so its threshold is not directly comparable to this column."; -/// Tooltip for the Per-language overview's `Avg MI` column. Distinct from -/// [`MI_TOOLTIP`] (the per-file hotspot column, which shows the *clamped* -/// `mi_visual_studio`): the overview average is SLOC-weighted and derived -/// from the *unclamped* value, so it can go negative for an unmaintainable -/// codebase instead of saturating at 0 (issue #725). -pub(crate) const AVG_MI_TOOLTIP: &str = "Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW; any value below 10, however negative, is LOW."; -/// Tooltip for the Per-language overview's `Avg CC` column. Names the -/// population — every function, suppression markers ignored — because the -/// CC note under the cyclomatic hotspot table averages a *different* set -/// (suppressed functions excluded) and the two figures can disagree. -pub(crate) const AVG_CC_TOOLTIP: &str = "Mean Cyclomatic Complexity over every function and method in the language, ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut (CC above 0 and, by default, not suppressed), so the two can differ."; -/// Tooltip for the Per-language overview's `Avg Cognitive` column. -pub(crate) const AVG_COGNITIVE_TOOLTIP: &str = "Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers."; -pub(crate) const FILES_TOOLTIP: &str = "Number of source files analysed."; -pub(crate) const FUNCTIONS_TOOLTIP: &str = "Number of functions and methods analysed."; - -/// Tooltip / legend definitions for the Per-language overview table, -/// which is NOT part of the hotspot [`SPECS`] (per-language aggregates, -/// not per-function rows); its header and alignment lists live with the -/// two `write_per_language_overview` / `write_overview_table` callers. -/// The HTML renderer attaches these as `title=` tooltips and both -/// renderers list them in the legend, so a reader who -/// meets a negative `Avg MI` has the explanation on the page rather than -/// only on hover. `Language` is an identity column and carries none. -/// "Files" here means *source files analysed*; the bus-factor table's -/// like-named column means files-per-directory and supplies its own -/// tooltip (issue #610), so this entry never leaks onto it. -pub(crate) const OVERVIEW_LEGEND: &[(&str, &str)] = &[ - ("Files", FILES_TOOLTIP), - ("SLOC", SLOC_TOOLTIP), - ("Functions", FUNCTIONS_TOOLTIP), - ("Avg MI", AVG_MI_TOOLTIP), - ("Avg CC", AVG_CC_TOOLTIP), - ("Avg Cognitive", AVG_COGNITIVE_TOOLTIP), -]; pub(crate) const SLOC_TOOLTIP: &str = "Source Lines Of Code: total physical lines, including blanks and comments."; pub(crate) const PLOC_TOOLTIP: &str = diff --git a/big-code-analysis-cli/src/markdown_report/overview.rs b/big-code-analysis-cli/src/markdown_report/overview.rs new file mode 100644 index 000000000..ba6af3538 --- /dev/null +++ b/big-code-analysis-cli/src/markdown_report/overview.rs @@ -0,0 +1,184 @@ +//! The Per-language overview table, defined once as a column spec. +//! +//! The overview is a per-language aggregate (one row per language), not +//! a per-function hotspot, so it cannot share [`hotspot::Column`]; but it +//! follows the same pattern — headers, alignments, cell projectors and +//! tooltips on one array — so the two renderers and both legends read +//! the same definition and a column cannot gain or lose a header, a +//! tooltip or an alignment on one side only. + +use super::hotspot::{self, Cell}; +use super::{Align, FunctionSummary, MiAverage, language_display_name, thousands}; +use big_code_analysis::SpaceKind; + +/// Tooltip for the Per-language overview's `Avg MI` column. Distinct from +/// [`hotspot::MI_TOOLTIP`] (the per-file hotspot column, which shows the +/// *clamped* `mi_visual_studio`): the overview average is SLOC-weighted +/// and derived from the *unclamped* value, so it can go negative for an +/// unmaintainable codebase instead of saturating at 0 (issue #725). +const AVG_MI_TOOLTIP: &str = "Average Maintainability Index, SLOC-weighted across the language's files so larger files dominate. Unlike the per-file MI column it uses the unclamped Visual Studio value, so a codebase of unmaintainable files reads negative rather than saturating at 0. GOOD \u{2265} 20, MODERATE \u{2265} 10, else LOW; any value below 10, however negative, is LOW."; +/// Tooltip for the Per-language overview's `Avg CC` column. Names the +/// population — every function, suppression markers ignored — because the +/// CC note under the cyclomatic hotspot table averages a *different* set +/// (suppressed functions excluded) and the two figures can disagree. +const AVG_CC_TOOLTIP: &str = "Mean Cyclomatic Complexity over every function and method in the language, ignoring suppression markers. The Average CC under the cyclomatic hotspot table covers every function eligible for that table before its top-N cut (CC above 0 and, by default, not suppressed), so the two can differ."; +/// Tooltip for the Per-language overview's `Avg Cognitive` column. +const AVG_COGNITIVE_TOOLTIP: &str = "Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers."; +/// "Files" here means *source files analysed*; the bus-factor table's +/// like-named column means files-per-directory and supplies its own +/// tooltip (issue #610), so this entry never leaks onto it. +const FILES_TOOLTIP: &str = "Number of source files analysed."; +const FUNCTIONS_TOOLTIP: &str = "Number of functions and methods analysed."; + +/// One language's overview aggregates: the quantities the seven columns +/// project. Computed once per language by [`LangOverview::from_summaries`]. +pub(crate) struct LangOverview { + display_name: String, + files: usize, + sloc: usize, + functions: usize, + /// `None` when no unit carried code to measure (see [`MiAverage`]). + avg_mi: Option<f64>, + avg_cc: f64, + avg_cognitive: f64, +} + +impl LangOverview { + /// Fold one language's summaries: the file-level quantities over its + /// `Unit` spaces and the averages over its `Function` spaces. + pub(crate) fn from_summaries(lang_name: &str, summaries: &[&FunctionSummary]) -> Self { + let (files, sloc, avg_mi) = unit_aggregates(summaries); + let (functions, avg_cc, avg_cognitive) = function_aggregates(summaries); + Self { + display_name: language_display_name(lang_name).into_owned(), + files, + sloc, + functions, + avg_mi, + avg_cc, + avg_cognitive, + } + } + + /// The row, one [`Cell`] per column of [`OVERVIEW_SPECS`]. + pub(crate) fn cells(&self) -> Vec<Cell> { + OVERVIEW_SPECS.iter().map(|c| (c.cell)(self)).collect() + } +} + +fn unit_aggregates(lang_summaries: &[&FunctionSummary]) -> (usize, usize, Option<f64>) { + let mut count = 0usize; + let mut sloc = 0usize; + let mut mi = MiAverage::default(); + for s in lang_summaries.iter().filter(|s| s.kind == SpaceKind::Unit) { + count += 1; + sloc += s.sloc; + mi.add(s); + } + (count, sloc, mi.average()) +} + +fn function_aggregates(lang_summaries: &[&FunctionSummary]) -> (usize, f64, f64) { + let mut count = 0usize; + let mut cc_sum = 0.0f64; + let mut cog_sum = 0.0f64; + for s in lang_summaries + .iter() + .filter(|s| s.kind == SpaceKind::Function) + { + count += 1; + cc_sum += s.cyclomatic; + cog_sum += s.cognitive; + } + if count > 0 { + (count, cc_sum / count as f64, cog_sum / count as f64) + } else { + (0, 0.0, 0.0) + } +} + +/// One Per-language overview column: header, alignment, the cell it +/// projects from the language's aggregates, and its tooltip (`None` for +/// the `Language` identity column). The tooltip is the single source of +/// the column's definition: the HTML renderer attaches it as `title=` +/// and both legends list it through [`legend`]. +pub(crate) struct OverviewColumn { + pub(crate) header: &'static str, + pub(crate) align: Align, + pub(crate) cell: fn(&LangOverview) -> Cell, + pub(crate) tooltip: Option<&'static str>, +} + +/// The seven overview columns, in render order. +pub(crate) const OVERVIEW_SPECS: &[OverviewColumn] = &[ + OverviewColumn { + header: "Language", + align: Align::Left, + cell: |o| Cell::Text(o.display_name.clone()), + tooltip: None, + }, + OverviewColumn { + header: "Files", + align: Align::Right, + cell: |o| Cell::Num(thousands(o.files)), + tooltip: Some(FILES_TOOLTIP), + }, + OverviewColumn { + header: "SLOC", + align: Align::Right, + cell: |o| Cell::Num(thousands(o.sloc)), + tooltip: Some(hotspot::SLOC_TOOLTIP), + }, + OverviewColumn { + header: "Functions", + align: Align::Right, + cell: |o| Cell::Num(thousands(o.functions)), + tooltip: Some(FUNCTIONS_TOOLTIP), + }, + OverviewColumn { + header: "Avg MI", + align: Align::Right, + // An empty cell, not `n/a`, when no file had code to measure: the + // HTML table sorter reads an empty cell as "no value" and sorts it + // last in either direction; any other text would parse as NaN and + // sort the same way, but read as a value in the cell. + cell: |o| Cell::Num(o.avg_mi.map_or_else(String::new, |mi| format!("{mi:.1}"))), + tooltip: Some(AVG_MI_TOOLTIP), + }, + OverviewColumn { + header: "Avg CC", + align: Align::Right, + cell: |o| Cell::Num(format!("{:.1}", o.avg_cc)), + tooltip: Some(AVG_CC_TOOLTIP), + }, + OverviewColumn { + header: "Avg Cognitive", + align: Align::Right, + cell: |o| Cell::Num(format!("{:.1}", o.avg_cognitive)), + tooltip: Some(AVG_COGNITIVE_TOOLTIP), + }, +]; + +pub(crate) fn headers() -> Vec<&'static str> { + OVERVIEW_SPECS.iter().map(|c| c.header).collect() +} + +pub(crate) fn aligns() -> Vec<Align> { + OVERVIEW_SPECS.iter().map(|c| c.align).collect() +} + +pub(crate) fn tooltips() -> Vec<Option<&'static str>> { + OVERVIEW_SPECS.iter().map(|c| c.tooltip).collect() +} + +/// The overview's legend entries, derived from the spec so a column +/// cannot exist without its definition being considered, nor the legend +/// name a column that does not render. Listed in both renderers' legends +/// so a reader who meets a negative `Avg MI` has the explanation on the +/// page rather than only on hover; `Language` carries none. +pub(crate) fn legend() -> Vec<(&'static str, &'static str)> { + OVERVIEW_SPECS + .iter() + .filter_map(|c| c.tooltip.map(|t| (c.header, t))) + .collect() +} diff --git a/big-code-analysis-cli/src/markdown_report/sections.rs b/big-code-analysis-cli/src/markdown_report/sections.rs index 61555172c..4bff4e905 100644 --- a/big-code-analysis-cli/src/markdown_report/sections.rs +++ b/big-code-analysis-cli/src/markdown_report/sections.rs @@ -76,7 +76,7 @@ pub(super) fn emit_section_md( pub(crate) fn render_cell_md(cell: Cell) -> String { match cell { Cell::Name(s) => escape_name(&s), - Cell::Path(s) => escape_cell(&s), + Cell::Path(s) | Cell::Text(s) => escape_cell(&s), Cell::Num(s) => s, } } diff --git a/big-code-analysis-cli/src/vcs_report.rs b/big-code-analysis-cli/src/vcs_report.rs index 370bf3c3e..ef52296d3 100644 --- a/big-code-analysis-cli/src/vcs_report.rs +++ b/big-code-analysis-cli/src/vcs_report.rs @@ -7,11 +7,12 @@ //! curated [`VcsColumn::in_markdown`] subset of that same slice, so the //! two cannot drift on a shared column (guarded by //! `markdown_columns_are_a_curated_subset_of_html`). Table markup and escaping are -//! delegated to the existing renderers' `write_table` helpers +//! delegated to the existing renderers' table writers //! (`crate::markdown_report::write_table` / -//! `crate::html_report::write_table`, or `write_table_classed` for the -//! HTML severity-heat tint on the `risk_score` cell, see -//! [`risk_heat_class`]) and the shared HTML scaffolding +//! `crate::html_report::write_table_with_tooltips`, or +//! `write_table_classed_with_tooltips` for the HTML severity-heat tint on +//! the `risk_score` cell, see [`risk_heat_class`]) and the shared HTML +//! scaffolding //! (`write_html_head` / `write_html_tail`), so the page carries //! `report.html`'s styling and inline click-to-sort behaviour. @@ -407,13 +408,6 @@ fn cell_rows(report: &Report, specs: &[&VcsColumn]) -> Vec<Vec<Cell>> { .collect() } -/// Extract a `Cell`'s text payload for HTML, where `write_table` escapes -/// every kind uniformly (so the kind itself does not matter here). -fn cell_text(cell: Cell) -> String { - let (Cell::Name(t) | Cell::Path(t) | Cell::Num(t)) = cell; - t -} - /// One-line provenance shared by both formats: window lengths and the /// risk-formula version, plus the ordinal-only caveat. The /// `vcs_schema_version` is wire jargon (it stamps the structured CSV/JSON @@ -663,7 +657,7 @@ fn write_html_body( } else { let rows: Vec<Vec<String>> = cell_rows(report, &specs) .into_iter() - .map(|row| row.into_iter().map(cell_text).collect()) + .map(|row| row.into_iter().map(Cell::into_text).collect()) .collect(); // Tint only the risk cell, by relative rank. `report.files` is // risk-ranked, so the row index is the rank; the Markdown path @@ -734,7 +728,7 @@ fn write_html_bus_factor( if !bf.by_directory.is_empty() { let rows: Vec<Vec<String>> = bus_factor_rows(bf) .into_iter() - .map(|row| row.into_iter().map(cell_text).collect()) + .map(|row| row.into_iter().map(Cell::into_text).collect()) .collect(); write_table_with_tooltips( out, From b85a3cb52dac761431e3881d86833be2057e55a6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:03:05 -0800 Subject: [PATCH 8/8] feat(cli): make report column headers native sort buttons MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous sortable header was a `<th tabindex="0">` with a `keydown` handler: reachable from the keyboard, but announced as a plain column header with no cue that Enter sorts, and with the label doubling as the documentation link, so clicking the text navigated while clicking the padding sorted — the ambiguity two `e.target` guards papered over. Each header is now the WAI-ARIA APG sortable-column shape. The label is a `<button type="button" class="sort">`, natively focusable and activated by Enter / Space, so the script binds `click` on the button alone and carries no key handling or target guards; `aria-sort` and `title` stay on the `<th>`, where ARIA defines them, with the `title` repeated on the button since a focused element's description comes from itself, not an ancestor; the sort arrow is an empty `aria-hidden` span inside the button that the CSS fills from the parent's `aria-sort`, so it never joins the button's accessible name; and the documentation link is a small `?` after the label. That link carries a `title`, not an `aria-label`: a column header's name is computed from its content, descending into the link, so a label there would be read with the column name on every cell a screen reader crosses. The button carries the cell's padding, so the whole header area still sorts, the target stays above WCAG's 24-pixel minimum, and the old header hover tint moves onto it. Every `<th>` carries `scope="col"`. The "click a column header's label" hint is shared with the standalone `bca vcs --format html` page, whose headers sort the same way and which had no hint; there it sits under the provenance summary and only when a table follows. The DOM-stub harness builds headers as the page renders them, with a second table, and the test asserts the button carries the one listener and the header none, that a click on the icon reaches the button, that a click targeting the documentation link or the cell itself does not sort, and that sorting one table leaves the other as rendered — a baseline read before the script runs at all, so a script that sorted at load time would fail it too. A header-shape test walks every `<th>` on the AST page, the standalone change-history page with and without its Hotspot column, and the embedded section, asserting the shape positively: button first, icon span closing it, at most one trailing link. Tests that selected a header by `>Label</th>` read it through one `header_cells` extractor keyed on the button's label, so the attribute order, icon and glyph around it are not what they pin. --- .bca-baseline.toml | 6 - CHANGELOG.md | 14 + big-code-analysis-book/src/commands/report.md | 29 +- big-code-analysis-book/src/commands/vcs.md | 4 +- big-code-analysis-cli/src/html_report.rs | 386 ++++++++++++------ .../src/html_report/sections.rs | 7 +- .../src/html_report/styling.rs | 44 +- big-code-analysis-cli/src/markdown_report.rs | 60 +-- ..._html_report__tests__html_report_rich.snap | 40 +- ...l_report__tests__html_report_two_lang.snap | 32 +- ...s_report__tests__vcs_report_html_rich.snap | 9 +- big-code-analysis-cli/src/vcs_report.rs | 123 ++++-- .../tests/fixtures/sort_script_harness.mjs | 149 ++++--- 13 files changed, 568 insertions(+), 335 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index bd75c918f..151d5042b 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -607,12 +607,6 @@ qualified = "write_table_classed_with_tooltips" metric = "nargs" value = 7.0 -[[entry]] -path = "big-code-analysis-cli/src/html_report.rs" -qualified = "write_table_core" -metric = "nargs" -value = 7.0 - [[entry]] path = "big-code-analysis-cli/src/html_report.rs" qualified = "write_table_head" diff --git a/CHANGELOG.md b/CHANGELOG.md index faca3ea0e..ae76484b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,20 @@ for historical reference. ### Changed +- **The HTML report's column headers are native sort buttons.** Each + header's label is now a `<button>` inside the `<th>` — the WAI-ARIA + sortable-table shape — so it is announced as a control, sorts on + Enter / Space through the browser's own activation, and needs no + `tabindex` or key handling of our own; `aria-sort` stays on the + cell and the sort arrow is hidden from assistive technology so it + never joins the button's name. The documentation link that was the + label itself is a small `?` after it, so clicking the label sorts + and clicking the glyph navigates; the button carries the cell's + padding, so the rest of the header still sorts as before. Every + `<th>` carries `scope="col"`, and the "click a column header" hint + now appears on the standalone `bca vcs --format html` page as well + as on `bca report html`. + - **`roles/mod.rs` no longer allows `dead_code` module-wide** (#1792). The allow was recorded as hiding 58 unread macro-emitted items; with it overridden (`RUSTFLAGS=--force-warn dead_code`) the library diff --git a/big-code-analysis-book/src/commands/report.md b/big-code-analysis-book/src/commands/report.md index 2fbffd9b5..a4c907579 100644 --- a/big-code-analysis-book/src/commands/report.md +++ b/big-code-analysis-book/src/commands/report.md @@ -249,17 +249,24 @@ bca report --paths /path/to/project \ html --top 10 --output report.html ``` -Click any column header — or Tab to it and press Enter or Space — to -sort that table ascending, and again to toggle descending. Each table -sorts independently. Empty cells (where a metric was not measured) sort -last in both directions, so "no data" rows never surface at the top of -a hotspot. - -Hover (or keyboard-focus, where the browser supports it) any metric -column header (`SLOC`, `MI`, `CC`, `ABC`, `WMC`, `NPA`, `NPM`, -`Exits`, and the rest) for a one-sentence plain-English explanation of -the metric. The tooltip is delivered through the native HTML `title` -attribute, so it works offline with no JavaScript. +Every column header is a native button: click its label — or Tab to +it and press Enter or Space — to sort that table ascending, and again +to toggle descending. Each table sorts independently. Empty cells +(where a metric was not measured) sort last in both directions, so +"no data" rows never surface at the top of a hotspot. The header +follows the WAI-ARIA sortable-table pattern — the label is the +`<button>`, the cell carries `aria-sort`, and the sort arrow is hidden +from assistive technology — so a screen reader announces the control +as a button and the column's current order. The button fills the +header cell, so clicking anywhere in it sorts; the `?` beside a metric +label is the one thing in a header that does not. + +Hover any metric column header (`SLOC`, `MI`, `CC`, `ABC`, `WMC`, +`NPA`, `NPM`, `Exits`, and the rest) for a one-sentence plain-English +explanation of the metric. The tooltip is delivered through the native +HTML `title` attribute, so it works offline with no JavaScript. The +small `?` after a metric's label is the link to that metric's chapter +in this book. Because `title` tooltips are hover-only (invisible in print, on mobile, and to screen readers), the page also ends with a visible, diff --git a/big-code-analysis-book/src/commands/vcs.md b/big-code-analysis-book/src/commands/vcs.md index 9bd2c57d2..b92eece62 100644 --- a/big-code-analysis-book/src/commands/vcs.md +++ b/big-code-analysis-book/src/commands/vcs.md @@ -76,8 +76,8 @@ bca vcs --top 50 --format markdown --output vcs.md ``` `--format html` produces a self-contained, sortable page styled like -`bca report html` (click any column header, or focus it and press -Enter, to re-sort); `--format +`bca report html` (click any column header's label, or Tab to it and +press Enter, to re-sort); `--format markdown` produces the same ranked table as [GitHub-Flavored Markdown](https://github.github.com/gfm/). Both render every signal column, the same data the structured formats carry. The diff --git a/big-code-analysis-cli/src/html_report.rs b/big-code-analysis-cli/src/html_report.rs index ea8aa5b9e..b8b4e993c 100644 --- a/big-code-analysis-cli/src/html_report.rs +++ b/big-code-analysis-cli/src/html_report.rs @@ -86,24 +86,55 @@ pub(crate) fn write_table_with_tooltips( write_table_classed_with_tooltips(out, headers, aligns, tooltips, ranked, rows, |_, _| None); } -/// [`write_table_with_tooltips`] plus a `cell_class` callback (the -/// severity-heat tint the change-history table paints on its risk cell). -pub(crate) fn write_table_classed_with_tooltips( - out: &mut String, - headers: &[&str], - aligns: &[Align], - tooltips: &[Option<&str>], - ranked: Option<RankedColumn>, - rows: &[Vec<String>], - cell_class: impl Fn(usize, usize) -> Option<&'static str>, -) { - debug_assert_eq!(headers.len(), tooltips.len()); - write_table_core(out, headers, aligns, tooltips, rows, ranked, cell_class); +/// Every header cell in `html`, as the text between its `<th` and `</th>`, +/// across every table on the page. `<thead>` shares the prefix, so the +/// split is on `<th ` / `<th>` only. +#[cfg(test)] +pub(crate) fn header_cells(html: &str) -> Vec<&str> { + html.split("<th") + .skip(1) + .filter(|c| c.starts_with(' ') || c.starts_with('>')) + .map(|c| c.split("</th>").next().expect("th closes")) + .collect() } -/// Emit the `<thead>` row: one `<th>` per header, carrying its numeric hint, -/// the pre-ranked column's `aria-sort`, an optional tooltip, and a link to the -/// metric's hosted chapter when one exists. +/// The rendered header cell for the column labelled `label`, or `None`. +/// A label is read as the text of its sort button, so a test selecting a +/// column by name reads the one place the label lives and is not written +/// against the attribute order, the icon span or the documentation glyph +/// around it. +#[cfg(test)] +pub(crate) fn header_cell<'a>(html: &'a str, label: &str) -> Option<&'a str> { + // The button's tag may carry a `title`, so the label is matched on the + // text run the tag closes into, bounded by the icon span after it. + let needle = format!(">{label}<span class=\"sort-icon\""); + header_cells(html) + .into_iter() + .find(|c| c.contains("class=\"sort\"") && c.contains(&needle)) +} + +/// Emit the `<thead>` row: one `<th>` per header, carrying its numeric +/// hint, the pre-ranked column's `aria-sort`, an optional tooltip, and a +/// link to the metric's hosted chapter when one exists. +/// +/// Each header is the WAI-ARIA APG sortable-column shape: the label is a +/// `<button>` the inline JS binds the sort to, natively focusable and +/// activated by Enter / Space, and announced as a button; `aria-sort` +/// and `title` stay on the `<th>`, where ARIA defines them. The sort +/// arrow is an empty, `aria-hidden` span the CSS fills from the parent's +/// `aria-sort`, so it never joins the button's accessible name. The +/// documentation link, once the label itself, is a small `?` beside it +/// — so clicking the label sorts and clicking the glyph navigates, and +/// neither handler needs to guess which the reader meant. It carries a +/// `title`, not an `aria-label`: a column header's accessible name is +/// computed from its content, descending into the link, so a label there +/// would be read out with the column name on every cell a screen reader +/// crosses ("CC CC: documentation 25"); the link's purpose is clear from +/// its context in the header, and the legend links every chapter by +/// name. The tooltip is repeated on the button, since a focused element's +/// description comes from the element itself, not an ancestor. Attribute +/// order on the `<th>` is fixed (`scope`, `data-numeric`, `aria-sort`, +/// `title`) because tests select on it. fn write_table_head( out: &mut String, headers: &[&str], @@ -118,10 +149,7 @@ fn write_table_head( } else { "" }; - // `tabindex="0"` puts the header in the tab order so the sort the - // inline JS binds to click is also reachable by keyboard (Enter / - // Space); without it a bare `<th>` can never take focus. - let _ = write!(out, "<th tabindex=\"0\"{numeric_attr}"); + let _ = write!(out, "<th scope=\"col\"{numeric_attr}"); // Announce the pre-ranked column's initial sort order at render // time. The `dir` string comes from `SortDir::aria_sort`, so it is // always the literal `ascending`/`descending` the inline JS toggles @@ -132,43 +160,44 @@ fn write_table_head( { let _ = write!(out, " aria-sort=\"{}\"", rank.dir); } - if let Some(tip) = tooltips.get(i).copied().flatten() { - let _ = write!(out, " title=\"{}\"", escape_html(tip)); - } - // Link the header text to its hosted metric chapter when one exists - // (issue #675). The link sits inside the still-clickable `<th>`, so - // clicking the padding sorts and clicking the term opens the docs; - // non-metric headers (File, Rank, overview averages) render bare. - match hotspot::metric_doc_url(h) { - Some(url) => { - let _ = write!( - out, - "><a href=\"{}\">{}</a></th>", - escape_html(&url), - escape_html(h) - ); - } - None => { - let _ = write!(out, ">{}</th>", escape_html(h)); - } + let tip = tooltips.get(i).copied().flatten().map(escape_html); + let title_attr = tip + .as_deref() + .map(|t| format!(" title=\"{t}\"")) + .unwrap_or_default(); + let _ = write!( + out, + "{title_attr}><button type=\"button\" class=\"sort\"{title_attr}>{}<span class=\"sort-icon\" aria-hidden=\"true\"></span></button>", + escape_html(h) + ); + // The hosted metric chapter (issue #675); non-metric headers (File, + // Rank, the overview averages) carry no link. + if let Some(url) = hotspot::metric_doc_url(h) { + let _ = write!( + out, + "<a class=\"doc\" href=\"{}\" title=\"Documentation\">?</a>", + escape_html(&url) + ); } + let _ = out.write_str("</th>"); } let _ = out.write_str("</tr></thead>\n"); } -/// Shared table body for the HTML renderers: `cell_class` contributes an -/// optional per-cell CSS class keyed by `(row, col)`, and `tooltips[i]` -/// is column `i`'s `title=` text. -fn write_table_core( +/// [`write_table_with_tooltips`] plus a `cell_class` callback (the +/// severity-heat tint the change-history table paints on its risk cell), +/// contributing an optional per-cell CSS class keyed by `(row, col)`. +pub(crate) fn write_table_classed_with_tooltips( out: &mut String, headers: &[&str], aligns: &[Align], tooltips: &[Option<&str>], - rows: &[Vec<String>], ranked: Option<RankedColumn>, + rows: &[Vec<String>], cell_class: impl Fn(usize, usize) -> Option<&'static str>, ) { debug_assert_eq!(headers.len(), aligns.len()); + debug_assert_eq!(headers.len(), tooltips.len()); // Wrap every table in an overflow-x scroll container so a wide table // (the 21-column VCS table especially) scrolls horizontally instead of // clipping its right-most metric columns past a narrow viewport (issue @@ -513,42 +542,126 @@ mod tests { // The selector keys on the attribute the sorter already emits, so // the real output carries it on exactly the numeric headers. let out = generate_html_report(&rust_fixture(), 20, SuppressionPolicy::Honor); - assert!(out.contains("<th tabindex=\"0\" data-numeric=\"1\"")); + assert!(out.contains("<th scope=\"col\" data-numeric=\"1\"")); assert!( - out.contains("<th tabindex=\"0\">File</th>"), + out.contains("<th scope=\"col\"><button type=\"button\" class=\"sort\">File<"), "identity headers stay text-aligned (no data-numeric):\n{out}" ); } - /// Sorting is reachable from the keyboard: every header is in the tab - /// order and the handler fires on Enter / Space as well as click. - /// Before, a bare `<th>` could never take focus, and the only - /// focusable thing in a metric header was its documentation link. + /// Each header is the APG sortable-column shape: the label is a native + /// `<button>` (focusable and activated by Enter / Space with no key + /// handling of our own), the sort arrow is an `aria-hidden` span inside + /// it so it never joins the button's accessible name, `scope="col"` is + /// set, and nothing on the `<th>` itself is focusable or bound. The + /// previous shape — `tabindex="0"` on the `th` with a `keydown` + /// listener — was reachable but announced as a plain column header. + /// Walks every header rather than comparing global counts, over the + /// AST report, the standalone change-history page with and without + /// its Hotspot column (whose 20-plus columns and bus-factor table have + /// no documentation links), and the aggregated page with the + /// change-history section embedded. #[test] - fn headers_are_focusable_and_sort_on_keyboard() { - let out = generate_html_report(&rust_fixture(), 20, SuppressionPolicy::Honor); - // `<th ` and `<th>` only — `<thead>` shares the prefix. - let total = out.matches("<th ").count() + out.matches("<th>").count(); - assert!(total > 0); - assert_eq!( - out.matches("<th tabindex=\"0\"").count(), - total, - "every <th> must be focusable" - ); - assert!(INLINE_JS.contains("th.addEventListener('keydown'")); - assert!(INLINE_JS.contains("e.key==='Enter'||e.key===' '")); - // A metric header holds a documentation link; Enter on *that* - // must follow the link, not sort. The handler ignores a keydown - // that bubbled from a child, before it reads the key. - let guard = INLINE_JS - .find("if(e.target!==th)return;") - .expect("target guard"); - let key = INLINE_JS.find("e.key==='Enter'").expect("key test"); - assert!(guard < key, "the target guard must run before the key test"); + fn headers_are_native_sort_buttons() { + let ast = generate_html_report(&rust_fixture(), 20, SuppressionPolicy::Honor); + let vcs_report = crate::vcs_report::rich_report_for_test(); + let vcs = crate::vcs_report::render_html(&vcs_report); + let vcs_unscored = + crate::vcs_report::render_html(&crate::vcs_report::unscored_report_for_test()); + let embedded = generate_html_report_with_vcs( + &rust_fixture(), + 20, + SuppressionPolicy::Honor, + &AdvisoryThresholds::DEFAULT, + Some(&vcs_report), + None, + ); + assert!( + header_cell(&vcs, "Hotspot").is_some() + && header_cell(&vcs_unscored, "Hotspot").is_none() + ); + for (page, html) in [ + ("ast", &ast), + ("vcs", &vcs), + ("vcs-unscored", &vcs_unscored), + ("embedded", &embedded), + ] { + let cells = header_cells(html); + assert!(cells.len() >= 10, "{page}: headers found: {}", cells.len()); + for cell in &cells { + let (opening, body) = cell.split_once('>').expect("opening tag closes"); + assert!( + opening.starts_with(" scope=\"col\""), + "{page}: scope=\"col\" leads every th: <th{opening}>" + ); + // The one negative worth spelling: the `th` was focusable + // before, and a focusable `th` beside a focusable button is + // two stops announcing two different things. + assert!( + !opening.contains("tabindex"), + "{page}: no tabindex on a th: {cell}" + ); + let button_at = body + .find("<button type=\"button\" class=\"sort\"") + .unwrap_or_else(|| panic!("{page}: a sort button opens the th body: {cell}")); + assert_eq!( + button_at, 0, + "{page}: the button is the first child: {cell}" + ); + assert_eq!( + body.matches("<button").count(), + 1, + "{page}: exactly one button per th: {cell}" + ); + let button_end = body.find("</button>").expect("button closes"); + assert!( + body[..button_end] + .ends_with("<span class=\"sort-icon\" aria-hidden=\"true\"></span>"), + "{page}: the button ends with its hidden icon span: {cell}" + ); + // After the button: nothing, or exactly one documentation + // link that is the cell's last child. + let rest = &body[button_end + "</button>".len()..]; + assert!( + rest.is_empty() + || (rest.starts_with("<a class=\"doc\" href=") + && rest.ends_with(">?</a>") + && rest.matches("<a ").count() == 1), + "{page}: the doc link, if any, follows the button and ends the cell: {cell}" + ); + } + assert_html_well_formed(html); + } + // The AST page has metric headers with a doc link; the VCS page + // has none (no change-history column maps to a hosted chapter). + let cc = header_cell(&ast, "CC").expect("a CC header on the AST page"); + assert!( + cc.ends_with("title=\"Documentation\">?</a>"), + "the metric doc link carries a title, not an aria-label that would join the column's name: {cc}" + ); + assert!(!cc.contains("aria-label"), "{cc}"); + assert!( + header_cells(&vcs) + .iter() + .all(|c| !c.contains("class=\"doc\"")) + ); + // The script binds the button, with no key handling of its own: + // the harness test proves the listeners land there; this pins the + // one selector the two share. + assert!(INLINE_JS.contains("th.querySelector('button.sort')")); + assert!(!INLINE_JS.contains("keydown"), "no key handling of our own"); assert!( - INLINE_CSS.contains("table.hotspot th:focus-visible{outline:"), - "a focused header must be visibly focused" + INLINE_CSS.contains("table.hotspot th button.sort:focus-visible{outline:"), + "a focused sort button must be visibly focused" ); + assert!( + INLINE_CSS.contains("th[aria-sort=ascending] .sort-icon::after"), + "the arrow is drawn in the hidden icon span" + ); + // The button, not the header's padding, is the hover target and + // carries the cell's padding so the whole header area activates it. + assert!(INLINE_CSS.contains("table.hotspot th button.sort:hover{background:")); + assert!(INLINE_CSS.contains("table.hotspot th button.sort{font:inherit;color:inherit;background:none;border:0;padding:0.4rem 0.6rem;")); } /// An empty numeric cell (the overview's `Avg MI` when no file carries @@ -576,7 +689,9 @@ mod tests { /// Runs [`INLINE_JS`] under Node against a DOM stub /// (`tests/fixtures/sort_script_harness.mjs`) and asserts what it /// *does*: the substring tests above pin the spelling and would pass - /// a script that, say, guarded the wrong event target. The harness + /// a script that, say, bound its listener one element up. The stub + /// proves click routing and sort state only — not native keyboard + /// activation, focus, accessible names, layout or print. The harness /// needs nothing newer than Node 14; the floor is `make plugin-test`'s /// 22.7 so one runtime serves every Node-driven test. Without it the /// test skips locally with a note, and **fails** under `CI` — the @@ -643,20 +758,36 @@ mod tests { assert_eq!(strs("textAscending"), ["a.rs", "b.rs", "c.rs", "d.rs"]); assert!(got["numericAriaCleared"].is_null(), "{got}"); assert!(got["rankedAriaCleared"].is_null(), "{got}"); - // Keyboard: Enter / Space on the header sort and swallow the key. - assert_eq!(strs("enterOnHeaderSorts"), ["d.rs", "c.rs", "b.rs", "a.rs"]); - assert_eq!(got["enterOnHeaderPrevented"], true); - assert_eq!(strs("spaceOnHeaderSorts"), ["5", "12", "1,000", ""]); - assert_eq!(got["spaceOnHeaderPrevented"], true); - // Enter on the header's documentation link neither sorts nor - // cancels the link's own navigation — including the `click` a - // browser synthesizes to activate the link, which bubbles to the - // header's click handler. A mouse click on the link is likewise - // the link's alone. - assert_eq!(got["enterOnLinkPrevented"], false, "{got}"); - assert_eq!(got["enterOnLinkMovedRows"], false, "{got}"); - assert_eq!(got["clickOnLinkMovedRows"], false, "{got}"); - assert_eq!(got["tabPrevented"], false); + // The button is the control: it carries the one listener, the + // header itself none — so Enter / Space on the focused button sort + // through the browser's native activation with no key handling of + // our own, and nothing can intercept a key on the header. + assert_eq!( + got["headerListeners"], + serde_json::json!([0, 0, 0, 0]), + "{got}" + ); + assert_eq!( + got["buttonListeners"], + serde_json::json!([1, 1, 1, 1]), + "{got}" + ); + // Sorting one table leaves the other alone, in both directions. The + // baseline is the second table's order as rendered, read before the + // script ran, so a script that sorted at load time is seen too. + assert_eq!(strs("otherAsRendered"), ["src", "docs", "tests"]); + assert_eq!(got["otherUntouchedBySort"], true, "{got}"); + assert_eq!(strs("otherAscending"), ["docs", "src", "tests"]); + assert_eq!(got["firstUntouchedByOther"], true, "{got}"); + // A click on the arrow inside the button still reaches the button. + assert_eq!(got["iconClickMovedRows"], true, "{got}"); + // Only the button is the control: a click targeting the + // documentation link, or the header cell itself, leaves the order + // alone. The button carries the cell's padding, so the whole header + // area still sorts in a browser; the cell-target case proves the + // listener lives on the button and nowhere above it. + assert_eq!(got["linkClickMovedRows"], false, "{got}"); + assert_eq!(got["cellClickMovedRows"], false, "{got}"); } #[test] @@ -919,22 +1050,30 @@ mod tests { .into_iter() .chain(overview::legend()) { - // A metric header now links its hosted chapter (issue #675), so - // its text is wrapped in an `<a>`; a non-metric overview header - // (Avg CC, …) stays bare. Either way the `title=` tooltip - // precedes it. - let needle = match hotspot::metric_doc_url(header) { - Some(url) => format!( - " title=\"{}\"><a href=\"{}\">{header}</a></th>", - escape_html(tip), - escape_html(&url) - ), - None => format!(" title=\"{}\">{header}</th>", escape_html(tip)), - }; + // The `title=` sits on the `<th>`; a metric header also links + // its hosted chapter (issue #675) through the `?` glyph after + // the label, and a non-metric overview header (Avg CC, …) has + // no glyph. + let cell = header_cell(&out, header) + .unwrap_or_else(|| panic!("header {header:?} should render:\n{out}")); + let (opening, body) = cell.split_once('>').expect("th opening tag"); assert!( - out.contains(&needle), - "header {header:?} should render with title attribute; expected substring {needle:?}" + opening.contains(&format!(" title=\"{}\"", escape_html(tip))), + "header {header:?} should carry its tooltip: <th{opening}>" ); + match hotspot::metric_doc_url(header) { + Some(url) => assert!( + body.ends_with(&format!( + "<a class=\"doc\" href=\"{}\" title=\"Documentation\">?</a>", + escape_html(&url) + )), + "metric header {header:?} should end with its doc glyph: {body}" + ), + None => assert!( + !body.contains("<a "), + "non-metric header {header:?} should carry no link: {body}" + ), + } } // Non-metric labels must remain bare so click-to-sort UX is not @@ -948,10 +1087,12 @@ mod tests { "Language is the overview's only tooltip-less column" ); for plain in ["File", "Function", "Type", "Line", "Language"] { - let needle = format!(">{plain}</th>"); + let cell = header_cell(&out, plain) + .unwrap_or_else(|| panic!("expected a <th> labelled {plain} in output")); + let (opening, _) = cell.split_once('>').expect("th opening tag"); assert!( - out.contains(&needle), - "expected bare <th>{plain}</th> in output" + !opening.contains("title="), + "identity header {plain:?} must carry no tooltip: <th{opening}>" ); } } @@ -983,27 +1124,34 @@ mod tests { "legend missing linked header-stat entry {header:?}" ); } + let mut rendered = 0usize; for (header, tip) in hotspot::legend_entries() { // Only assert entries whose column the fixture actually renders; // every metric column the rust fixture exercises must define - // itself in the legend. Metric terms link their chapter (#675), so - // both the `<th>` render-check and the `<dt>` term carry the link. - let (th_needle, dt_term) = match hotspot::metric_doc_url(header) { - Some(url) => ( - format!("<a href=\"{}\">{header}</a></th>", escape_html(&url)), - format!( - "<a href=\"{}\">{}</a>", - escape_html(&url), - escape_html(header) - ), - ), - None => (format!(">{header}</th>"), escape_html(header).into_owned()), - }; - let dt = format!("<dt>{dt_term}</dt><dd>{}</dd>", escape_html(tip)); - if out.contains(&th_needle) { + // itself in the legend. Every hotspot legend term links its + // chapter (#675; `every_legend_header_has_a_doc_anchor` pins + // that none lacks one), so the `<dt>` carries the link. + let url = hotspot::metric_doc_url(header) + .expect("every hotspot legend header has a doc anchor"); + let dt = format!( + "<dt><a href=\"{}\">{}</a></dt><dd>{}</dd>", + escape_html(&url), + escape_html(header), + escape_html(tip) + ); + if header_cell(&out, header).is_some() { + rendered += 1; assert!(out.contains(&dt), "legend missing entry for {header:?}"); } } + // The fixture renders most hotspot sections, so the loop above + // must have asserted on a real majority of the legend, not matched + // nothing and passed vacuously. + assert!( + rendered >= hotspot::legend_entries().len() / 2, + "only {rendered} of {} legend columns were found rendered", + hotspot::legend_entries().len() + ); } #[test] diff --git a/big-code-analysis-cli/src/html_report/sections.rs b/big-code-analysis-cli/src/html_report/sections.rs index 2da73c749..eb2bd32c3 100644 --- a/big-code-analysis-cli/src/html_report/sections.rs +++ b/big-code-analysis-cli/src/html_report/sections.rs @@ -241,12 +241,7 @@ pub(crate) fn write_overview_table( ) { headings.emit_h2(out, "Per-language overview", "Per-language overview"); let _ = out.write_str("\n"); - // One discoverability hint near the first table: the columns are - // sortable, which is otherwise invisible until a reader happens to - // click a header (issue #622). - let _ = out.write_str( - "<p class=\"sort-hint\">Click a column header \u{2014} or Tab to it and press Enter \u{2014} to sort any table.</p>\n", - ); + write_sort_hint(out); let rows: Vec<Vec<String>> = by_lang .iter() .map(|(&lang_name, lang_summaries)| { diff --git a/big-code-analysis-cli/src/html_report/styling.rs b/big-code-analysis-cli/src/html_report/styling.rs index 5fc862562..b0c9bfcdf 100644 --- a/big-code-analysis-cli/src/html_report/styling.rs +++ b/big-code-analysis-cli/src/html_report/styling.rs @@ -205,14 +205,20 @@ table.hotspot{border-collapse:collapse;width:100%;font-size:0.85rem;\ background:#fff;box-shadow:0 1px 2px rgba(0,0,0,0.06);margin-bottom:0.5rem}\ table.hotspot th,table.hotspot td{padding:0.4rem 0.6rem;\ border-bottom:1px solid #e5e5e5;text-align:left;white-space:nowrap}\ -table.hotspot th{background:#f0f0f0;cursor:pointer;user-select:none;\ -font-weight:600}\ -table.hotspot th:hover{background:#e5e5e5}\ -table.hotspot th[aria-sort=ascending]::after{content:\" \\2191\"}\ -table.hotspot th[aria-sort=descending]::after{content:\" \\2193\"}\ +table.hotspot th{background:#f0f0f0;user-select:none;font-weight:600;\ +padding:0}\ +table.hotspot th button.sort{font:inherit;color:inherit;background:none;\ +border:0;padding:0.4rem 0.6rem;cursor:pointer;text-align:inherit}\ +table.hotspot th button.sort:hover{background:#e5e5e5}\ +table.hotspot th button.sort:focus-visible{outline:2px solid #3d82cc;\ +outline-offset:-2px}\ +table.hotspot th[aria-sort=ascending] .sort-icon::after{content:\" \\2191\"}\ +table.hotspot th[aria-sort=descending] .sort-icon::after{content:\" \\2193\"}\ +table.hotspot th a.doc{padding:0.4rem 0.6rem 0.4rem 0;font-size:0.85em;\ +color:#555}\ +table.hotspot th a.doc:hover,table.hotspot th a.doc:focus-visible{color:#222}\ table.hotspot tr:nth-child(even) td{background:#fafafa}\ table.hotspot th[data-numeric=\"1\"]{text-align:right}\ -table.hotspot th:focus-visible{outline:2px solid #3d82cc;outline-offset:-2px}\ table.hotspot td.numeric{text-align:right;font-variant-numeric:tabular-nums}\ table.hotspot td.risk-heat-0,table.hotspot td.risk-heat-1,\ table.hotspot td.risk-heat-2,table.hotspot td.risk-heat-3,\ @@ -243,7 +249,9 @@ details.legend dd{color:#999}\ table.hotspot{background:#1e1e1e}\ table.hotspot th,table.hotspot td{border-bottom-color:#333}\ table.hotspot th{background:#2a2a2a}\ -table.hotspot th:hover{background:#383838}\ +table.hotspot th button.sort:hover{background:#383838}\ +table.hotspot th a.doc{color:#aaa}\ +table.hotspot th a.doc:hover,table.hotspot th a.doc:focus-visible{color:#e0e0e0}\ table.hotspot tr:nth-child(even) td{background:#232323}\ table.hotspot tr:nth-child(even) td.risk-heat-0,table.hotspot td.risk-heat-0\ {background:#7a1f17;color:#f0f0f0}\ @@ -309,14 +317,9 @@ function num(s){return s===''?NaN:parseFloat(s.replace(/,/g,''));}\ document.querySelectorAll('table.hotspot').forEach(function(table){\ var headers=table.querySelectorAll('thead th');\ headers.forEach(function(th,idx){\ -th.addEventListener('click',function(e){\ -if(e.target!==th)return;\ -sort(table,idx,th);\ -});\ -th.addEventListener('keydown',function(e){\ -if(e.target!==th)return;\ -if(e.key==='Enter'||e.key===' '){e.preventDefault();sort(table,idx,th);}\ -});\ +var b=th.querySelector('button.sort');\ +if(!b)return;\ +b.addEventListener('click',function(){sort(table,idx,th);});\ });\ });\ function sort(tbl,idx,th){\ @@ -349,6 +352,17 @@ keyed.forEach(function(e){tbody.appendChild(e.r);});\ })();\ "; +/// One discoverability hint near a page's first table: the columns are +/// sortable, which is otherwise invisible until a reader happens to +/// activate a header (issue #622). Lives beside [`INLINE_JS`], whose +/// behaviour it describes, and is shared by the aggregated report and the +/// standalone change-history page. +pub(crate) fn write_sort_hint(out: &mut String) { + let _ = out.write_str( + "<p class=\"sort-hint\">Click a column header's label \u{2014} or Tab to it and press Enter \u{2014} to sort any table.</p>\n", + ); +} + /// Write the shared HTML preamble (doctype, head with the inline CSS, and /// the opening `<h1>`). `title` fills the `<title>` element and `heading` /// the `<h1>`; both are escaped. Shared by the AST report and the VCS diff --git a/big-code-analysis-cli/src/markdown_report.rs b/big-code-analysis-cli/src/markdown_report.rs index a1a6bd365..296d7e5f5 100644 --- a/big-code-analysis-cli/src/markdown_report.rs +++ b/big-code-analysis-cli/src/markdown_report.rs @@ -1494,9 +1494,10 @@ mod tests { } /// The HTML overview's header cells as `(opening tag, label)` pairs, - /// one per `<th>`. The label is the cell's *first* text run only, so a - /// control wrapping the label or a glyph following it (a sort button, - /// a documentation link) does not change what the tests compare. + /// one per `<th>`, over the crate's one header extractor. The label is + /// the text the sort button's tag closes into, bounded by the icon + /// span after it, so what surrounds the label does not change what the + /// tests compare. fn overview_header_cells(html: &str) -> Vec<(String, String)> { let thead = html .split("Per-language overview</h2>") @@ -1504,53 +1505,20 @@ mod tests { .and_then(|t| t.split("<thead>").nth(1)) .and_then(|t| t.split("</thead>").next()) .expect("overview thead"); - thead - .split("<th") - .skip(1) + crate::html_report::header_cells(thead) + .into_iter() .map(|cell| { - let tag_end = cell.find('>').expect("th opening tag closes"); - let opening = format!("<th{}", &cell[..=tag_end]); - let mut label = String::new(); - let mut in_tag = false; - for ch in cell[tag_end + 1..].chars() { - match ch { - '<' => { - if !label.trim().is_empty() { - break; - } - in_tag = true; - } - '>' => in_tag = false, - _ if !in_tag => label.push(ch), - _ => {} - } - } - (opening, label.trim().to_owned()) + let (opening, body) = cell.split_once('>').expect("th opening tag closes"); + let label = body + .split_once("<span class=\"sort-icon\"") + .and_then(|(before, _)| before.rsplit_once('>')) + .map(|(_, label)| label) + .expect("a sort button labels the th"); + (format!("<th{opening}>"), label.to_owned()) }) .collect() } - /// The extractor the two overview tests share reads a header's label - /// as its first text run, so a sort control around the label and a - /// documentation glyph after it — the markup the sortable-header - /// work renders — leave the comparison unchanged. - #[test] - fn overview_header_extraction_survives_a_control_and_a_glyph() { - let html = "x<h2>Per-language overview</h2><table><thead><tr>\ - <th scope=\"col\"><button type=\"button\" class=\"sort\">Language<span aria-hidden=\"true\"></span></button></th>\ - <th scope=\"col\" data-numeric=\"1\" title=\"Source Lines\"><button type=\"button\" class=\"sort\">SLOC</button><a class=\"doc\" href=\"#\">?</a></th>\ - </tr></thead></table>"; - let cells = overview_header_cells(html); - let labels: Vec<&str> = cells.iter().map(|(_, l)| l.as_str()).collect(); - assert_eq!(labels, ["Language", "SLOC"]); - assert!(cells[1].0.contains(" title=\"Source Lines\"")); - assert!( - !cells[1].0.contains("button"), - "opening tag only: {}", - cells[1].0 - ); - } - /// The overview's five tooltips, pinned by hand against both outputs /// for the same reason: the spec-driven tooltip loop in /// `html_report` skips a `None`, so it cannot see a tooltip that was @@ -3071,7 +3039,7 @@ mod tests { let table_slice = &html[start..]; let body_start = table_slice.find("<tbody").unwrap_or(table_slice.len()); assert!( - table_slice[..body_start].contains(">Line</th>"), + crate::html_report::header_cell(&table_slice[..body_start], "Line").is_some(), "Line column missing from HTML {header} header" ); } diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap index 956eaaa86..e5e8b8063 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_rich.snap @@ -8,7 +8,7 @@ expression: out <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Code Quality Metrics Summary — big-code-analysis - +

Code Quality Metrics Summary

@@ -65,10 +65,10 @@ expression: out

Per-language overview

-

Click a column header — or Tab to it and press Enter — to sort any table.

+

Click a column header's label — or Tab to it and press Enter — to sort any table.

- + @@ -88,7 +88,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
?
Python1120228.08.59.0
Rust2280821.423.422.6
- + @@ -98,7 +98,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
???
src/main.py28.0120800
- + @@ -109,7 +109,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
????
mainsrc/main.py10101260300
load_datasrc/main.py407635180
- + @@ -119,7 +119,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
????
mainsrc/main.py10121060300
load_datasrc/main.py406735180
- + @@ -129,7 +129,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
?????
mainsrc/main.py102,0001,0000.3360300
load_datasrc/main.py401,2006000.2335180
- + @@ -139,7 +139,7 @@ expression: out

Many parameters hotspots (top 5 by Args)

FunctionFileLineSLOCTokensCCCognitive
????
mainsrc/main.py10603001012
load_datasrc/main.py403518076
- + @@ -148,7 +148,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineArgsSLOCTokens
???
load_datasrc/main.py40435180
- + @@ -173,7 +173,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

FunctionFileLineABCSLOCTokens
???
mainsrc/main.py109.060300
load_datasrc/main.py407.035180
- + @@ -184,7 +184,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
???
src/lib.rs12.02001,500
src/util.rs45.080600
- + @@ -198,7 +198,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
????
process_requestsrc/lib.rs102530150900
validate_inputsrc/lib.rs402024120700
- + @@ -211,7 +211,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
????
secret_internalsrc/lib.rs22080993002,000
process_requestsrc/lib.rs103025150900
- + @@ -224,7 +224,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
?????
secret_internalsrc/lib.rs22020,00010,0003.303002,000
process_requestsrc/lib.rs109,0004,5000.83150900
- + @@ -237,7 +237,7 @@ expression: out

Many parameters hotspots (top 5 by Args)

FunctionFileLineSLOCTokensCCCognitive
????
secret_internalsrc/lib.rs2203002,0009980
process_requestsrc/lib.rs101509002530
- + @@ -249,7 +249,7 @@ expression: out

Type hotspots (top 5 by WMC)

FunctionFileLineArgsSLOCTokens
???
secret_internalsrc/lib.rs22083002,000
process_requestsrc/lib.rs106150900
- + @@ -258,7 +258,7 @@ expression: out

Exit points hotspots (top 5 by Exits)

TypeFileLineWMCMethodsNPANPMSLOCTokens
??????
Widgetsrc/lib.rs250408261801,100
- + @@ -270,7 +270,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineExitsCCSLOCTokens
????
secret_internalsrc/lib.rs22010993002,000
handle_eventsrc/lib.rs10061270400
- + @@ -309,6 +309,6 @@ expression: out
Avg Cognitive
Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers.
- + diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap index d7e8a240d..347d6d341 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__html_report__tests__html_report_two_lang.snap @@ -8,7 +8,7 @@ expression: out Code Quality Metrics Summary — big-code-analysis - +

Code Quality Metrics Summary

@@ -55,10 +55,10 @@ expression: out

No major quality concerns detected.

Per-language overview

-

Click a column header — or Tab to it and press Enter — to sort any table.

+

Click a column header's label — or Tab to it and press Enter — to sort any table.

FunctionFileLineABCSLOCTokens
???
secret_internalsrc/lib.rs22050.03002,000
process_requestsrc/lib.rs1022.0150900
- + @@ -76,7 +76,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

LanguageFilesSLOCFunctionsAvg MIAvg CCAvg Cognitive
?
Python120150.03.02.0
Rust120250.03.02.0
- + @@ -86,7 +86,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
???
src/main.py50.02030
- + @@ -96,7 +96,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
????
greetsrc/main.py1322030
- + @@ -105,7 +105,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
????
greetsrc/main.py1232030
- + @@ -114,7 +114,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
?????
greetsrc/main.py15001000.102030
- + @@ -123,7 +123,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineSLOCTokensCCCognitive
????
greetsrc/main.py1203032
- + @@ -141,7 +141,7 @@ expression: out

Maintainability Index hotspots (lowest 5 by MI)

FunctionFileLineABCSLOCTokens
???
greetsrc/main.py15.02030
- + @@ -151,7 +151,7 @@ expression: out

Cyclomatic complexity hotspots (top 5 by CC)

FileMISLOCTokens
???
src/lib.rs50.02030
- + @@ -162,7 +162,7 @@ expression: out

Cognitive complexity hotspots (top 5 by Cognitive)

FunctionFileLineCCCognitiveSLOCTokens
????
computesrc/lib.rs1322030
do_stuffsrc/lib.rs1322030
- + @@ -172,7 +172,7 @@ expression: out

Halstead effort hotspots (top 5 by Effort)

FunctionFileLineCognitiveCCSLOCTokens
????
computesrc/lib.rs1232030
do_stuffsrc/lib.rs1232030
- + @@ -182,7 +182,7 @@ expression: out

Function size hotspots (top 5 by SLOC)

FunctionFileLineEffortVolumeEst. BugsSLOCTokens
?????
computesrc/lib.rs15001000.102030
do_stuffsrc/lib.rs15001000.102030
- + @@ -192,7 +192,7 @@ expression: out

ABC magnitude hotspots (top 5 by ABC)

FunctionFileLineSLOCTokensCCCognitive
????
computesrc/lib.rs1203032
do_stuffsrc/lib.rs1203032
- + @@ -228,6 +228,6 @@ expression: out
Avg Cognitive
Mean Cognitive Complexity over every function and method in the language, ignoring suppression markers.
- + diff --git a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap index 8ad614ebc..ed95dda9b 100644 --- a/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap +++ b/big-code-analysis-cli/src/snapshots/big_code_analysis_cli__vcs_report__tests__vcs_report_html_rich.snap @@ -8,7 +8,7 @@ expression: html Change-history risk — big-code-analysis - +

Change-history risk

@@ -16,9 +16,10 @@ expression: html

Long window 365d, recent window 90d, risk formula v1. Risk is ordinal: only relative ranks carry meaning, not the absolute value.

+

Click a column header's label — or Tab to it and press Enter — to sort any table.

FunctionFileLineABCSLOCTokens
???
computesrc/lib.rs15.02030
do_stuffsrc/lib.rs15.02030
- + @@ -32,7 +33,7 @@ expression: html

Repository: 2 (over 3 files, coverage threshold 0.50).

RankFileRiskCommits (recent)Commits (long)Churn (recent)Churn (long)Authors (recent)Authors (long)OwnershipBurstBug fixesSec fixesRevertsAge (d)Last mod (d)Change entropy (recent)Change entropy (long)Co-change entropy (recent)Co-change entropy (long)Hotspot
1src/hot.rs9.450602,0005,000230.750.5041020051.502.500.801.20748,436
2src/warm.rs6.120308002,000230.750.5041020051.502.500.801.20
- + @@ -67,6 +68,6 @@ expression: html - + diff --git a/big-code-analysis-cli/src/vcs_report.rs b/big-code-analysis-cli/src/vcs_report.rs index ef52296d3..6cf3263bd 100644 --- a/big-code-analysis-cli/src/vcs_report.rs +++ b/big-code-analysis-cli/src/vcs_report.rs @@ -20,7 +20,8 @@ use std::fmt::Write as _; use crate::html_report::{ Headings, RankedColumn, note_html, write_html_head, write_html_tail, write_legend_html, - write_table_classed_with_tooltips as write_html_table_classed, write_table_with_tooltips, + write_sort_hint, write_table_classed_with_tooltips as write_html_table_classed, + write_table_with_tooltips, }; use crate::markdown_report::hotspot::{self, Cell}; use crate::markdown_report::{ @@ -512,10 +513,20 @@ fn bus_factor_tooltips() -> [Option<&'static str>; 3] { ] } -/// The deduplicated `(header, tooltip)` pairs for the change-history table, -/// in column order, skipping identity columns. Both the HTML legend and the -/// Markdown legend draw from this so a column's definition renders -/// identically in the `title=` tooltip and the legend (issue #611). +/// The rich test report, for the crate-wide header-shape test in +/// `html_report`, which walks every table family a page can render. +#[cfg(test)] +pub(crate) fn rich_report_for_test() -> Report { + tests::rich_report() +} + +/// The same with every hotspot score cleared — the plain `bca vcs` shape, +/// which drops the Hotspot column (#615) — for the same test. +#[cfg(test)] +pub(crate) fn unscored_report_for_test() -> Report { + tests::unscored_report() +} + /// Every legend entry the change-history pages can render — all columns, /// Hotspot included, plus the bus-factor pair — for the crate-wide /// legend-prose invariant test in `markdown_report`. @@ -524,6 +535,10 @@ pub(crate) fn all_legend_entries_for_test() -> Vec<(&'static str, &'static str)> legend_entries(&VCS_SPECS.iter().collect::>()) } +/// The deduplicated `(header, tooltip)` pairs for the change-history table, +/// in column order, skipping identity columns. Both the HTML legend and the +/// Markdown legend draw from this so a column's definition renders +/// identically in the `title=` tooltip and the legend (issue #611). fn legend_entries(specs: &[&VcsColumn]) -> Vec<(&'static str, &'static str)> { // The bus-factor columns render in the same page but live outside // `VCS_SPECS`, so chain them onto the spec-driven pairs. @@ -616,7 +631,7 @@ pub(crate) fn render_html(report: &Report) -> String { let mut headings = Headings::default(); let _ = out.write_str("
\n"); // Page title is `

`, so subsections start at `

` (issue #618). - write_html_body(&mut out, &mut headings, report, STANDALONE_SUBSECTION_LEVEL); + write_html_body(&mut out, &mut headings, report, Page::Standalone); let _ = out.write_str("

\n"); write_html_tail(&mut out); out @@ -632,19 +647,34 @@ pub(crate) fn push_html_section(out: &mut String, headings: &mut Headings, repor headings.emit_h2(out, HEADING, HEADING); let _ = out.write_str("\n"); // Section header is `

`, so subsections start at `

`. - write_html_body(out, headings, report, EMBEDDED_SUBSECTION_LEVEL); + write_html_body(out, headings, report, Page::Embedded); let _ = out.write_str("\n"); } +/// Which page the change-history HTML is rendered into: its own +/// (`bca vcs --format html`), or a section of the aggregated report. +/// Decides the subsection heading depth and whether this body carries the +/// page's sort hint — the aggregated page places that above its first +/// table, the overview, so an embedded section must not repeat it. +#[derive(Clone, Copy)] +enum Page { + Standalone, + Embedded, +} + +impl Page { + fn subsection_level(self) -> usize { + match self { + Self::Standalone => STANDALONE_SUBSECTION_LEVEL, + Self::Embedded => EMBEDDED_SUBSECTION_LEVEL, + } + } +} + /// Provenance summary + sortable table (or the empty-set message). No /// `
` wrapper or heading — the caller supplies those. -/// `subsection_level` is the heading depth for the Bus factor subsection. -fn write_html_body( - out: &mut String, - headings: &mut Headings, - report: &Report, - subsection_level: usize, -) { +fn write_html_body(out: &mut String, headings: &mut Headings, report: &Report, page: Page) { + let subsection_level = page.subsection_level(); let _ = out.write_str("
\n"); let _ = writeln!(out, "

{}

", provenance(report)); if report.truncated_shallow_clone { @@ -655,6 +685,11 @@ fn write_html_body( if report.files.is_empty() { let _ = writeln!(out, "

{EMPTY_MESSAGE}

"); } else { + // The hint sits directly above the first table it describes, and + // only when there is one to sort. + if matches!(page, Page::Standalone) { + write_sort_hint(out); + } let rows: Vec> = cell_rows(report, &specs) .into_iter() .map(|row| row.into_iter().map(Cell::into_text).collect()) @@ -782,7 +817,7 @@ mod tests { /// A small ranked report: descending risk, one row with a hotspot /// score and one without (the `bca vcs` vs `metrics --vcs` split). - fn rich_report() -> Report { + pub(super) fn rich_report() -> Report { Report { long_window_days: 365, recent_window_days: 90, @@ -799,6 +834,16 @@ mod tests { } } + /// [`rich_report`] with every hotspot score cleared: the plain `bca vcs` + /// shape, with no AST join, which drops the Hotspot column (#615). + pub(super) fn unscored_report() -> Report { + let mut report = rich_report(); + for entry in &mut report.files { + entry.vcs.hotspot_score = None; + } + report + } + /// A small, fixed bus-factor aggregate so the rich-report snapshots /// exercise the rendered `## Bus factor` / `
` blocks. fn sample_aggregate() -> big_code_analysis::vcs::VcsAggregate { @@ -1056,7 +1101,7 @@ mod tests { // HTML carries every active header; Markdown carries the curated core. for header in headers(&active) { assert!( - html.contains(&format!(">{header}")), + crate::html_report::header_cell(&html, header).is_some(), "HTML missing column header {header:?}" ); } @@ -1146,7 +1191,10 @@ mod tests { let md = render_markdown(&report); let html = render_html(&report); assert!(md.contains("| Hotspot |"), "Markdown keeps Hotspot header"); - assert!(html.contains(">Hotspot"), "HTML keeps Hotspot header"); + assert!( + crate::html_report::header_cell(&html, "Hotspot").is_some(), + "HTML keeps Hotspot header" + ); // The score is an integral product (cyclomatic sum × churn), so it // takes the thousands separator the count columns use rather than // the bare `748436.0` it rendered as before. @@ -1210,15 +1258,7 @@ mod tests { // Plain `bca vcs` (no AST join): every row's `hotspot_score` is // `None`. The all-blank column is dropped from both formats and the // legend, instead of a permanently-empty trailing column (#615). - let report = Report { - vcs_aggregate: None, - files: vec![ - entry("src/a.rs", 9.0, 30, None), - entry("src/b.rs", 4.0, 10, None), - ], - ranked_total: 2, - ..rich_report() - }; + let report = unscored_report(); let specs = active_specs(&report); assert!( !specs.iter().any(|c| c.header == HOTSPOT_HEADER), @@ -1234,12 +1274,13 @@ mod tests { "Markdown must omit the Hotspot column entirely:\n{md}" ); assert!( - !html.contains(">Hotspot") && !html.contains("
Hotspot
"), + crate::html_report::header_cell(&html, "Hotspot").is_none() + && !html.contains("
Hotspot
"), "HTML must omit the Hotspot column entirely (header + legend)" ); // A still-rendered column proves the table itself is intact. assert!(md.contains("| Rank |")); - assert!(html.contains(">Risk")); + assert!(crate::html_report::header_cell(&html, "Risk").is_some()); } #[test] @@ -1255,14 +1296,12 @@ mod tests { let report = rich_report(); let html = render_html(&report); for (header, tip) in legend_entries(&active_specs(&report)) { - let needle = format!( - " title=\"{}\">{}", - escape_html(tip), - escape_html(header) - ); + let cell = crate::html_report::header_cell(&html, header) + .unwrap_or_else(|| panic!("VCS header {header:?} should render")); + let needle = format!(" title=\"{}\">", escape_html(tip)); assert!( - html.contains(&needle), - "VCS header {header:?} should render with its tooltip; expected {needle:?}" + cell.contains(&needle), + "VCS header {header:?} should render with its tooltip; expected {needle:?} in {cell}" ); } } @@ -1292,12 +1331,14 @@ mod tests { .split("
") .nth(1) .expect("rich report renders a bus-factor section"); + let files = crate::html_report::header_cell(bus_factor_html, "Files") + .expect("bus-factor table renders a Files header"); assert!( - bus_factor_html.contains(&format!( - " title=\"{}\">Files", + files.contains(&format!( + " title=\"{}\">", crate::html_report::escape_html(BUS_FACTOR_FILES_TOOLTIP) )), - "bus-factor Files column must carry its own tooltip" + "bus-factor Files column must carry its own tooltip: {files}" ); } @@ -1348,9 +1389,11 @@ mod tests { // carries its own definition rather than inheriting the unrelated // overview one. let html = render_html(&rich_report()); + let files = + crate::html_report::header_cell(&html, "Files").expect("a Files header renders"); assert!( - html.contains(&format!(" title=\"{BUS_FACTOR_FILES_TOOLTIP}\">Files")), - "bus-factor Files column should carry its own tooltip" + files.contains(&format!(" title=\"{BUS_FACTOR_FILES_TOOLTIP}\">")), + "bus-factor Files column should carry its own tooltip: {files}" ); assert!( !html.contains("Number of source files analysed."), diff --git a/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs b/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs index 552a92fed..52c9e807a 100644 --- a/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs +++ b/big-code-analysis-cli/tests/fixtures/sort_script_harness.mjs @@ -6,8 +6,9 @@ // Usage: node sort_script_harness.mjs // // The stub implements only what the script touches: `document -// .querySelectorAll('table.hotspot')`, `thead th` lookup, `tBodies`, -// `rows`, `cells`, `textContent`, `dataset`, the `aria-sort` attribute, +// .querySelectorAll('table.hotspot')`, `thead th` lookup, `th +// .querySelector('button.sort')`, `tBodies`, `rows`, `cells`, +// `textContent`, `dataset`, the `aria-sort` attribute, // `addEventListener` and `appendChild`. Collections are array-likes with // the browser's method surface — `NodeList` has `forEach` but no `map`, // `HTMLCollection` has neither — so a script that reaches for an Array @@ -16,9 +17,12 @@ // computes: a `

`. +function header(row, label, { numeric = false, doc = false, sorted = null } = {}) { + const th = row.appendChild(new Node("th")) + th.setAttribute("scope", "col") + if (numeric) th.setAttribute("data-numeric", "1") + if (sorted) th.setAttribute("aria-sort", sorted) + const button = th.appendChild(new Node("button", label)) + button.setAttribute("type", "button") + button.setAttribute("class", "sort") + const icon = button.appendChild(new Node("span")) + icon.setAttribute("class", "sort-icon") + icon.setAttribute("aria-hidden", "true") + let link = null + if (doc) { + link = th.appendChild(new Node("a", "?")) + link.setAttribute("class", "doc") + link.setAttribute("href", "#") + } + return { th, button, icon, link } +} + const table = document.appendChild(new Node("table")) table.setAttribute("class", "hotspot") -const thead = table.appendChild(new Node("thead")) -const headRow = thead.appendChild(new Node("tr")) -const numericTh = headRow.appendChild(new Node("th")) -numericTh.setAttribute("data-numeric", "1") -const link = numericTh.appendChild(new Node("a", "SLOC")) -const textTh = headRow.appendChild(new Node("th", "File")) -const rankedTh = headRow.appendChild(new Node("th", "Risk")) -rankedTh.setAttribute("data-numeric", "1") -rankedTh.setAttribute("aria-sort", "descending") +const headRow = table.appendChild(new Node("thead")).appendChild(new Node("tr")) +const numeric = header(headRow, "SLOC", { numeric: true, doc: true }) +const text = header(headRow, "File") +const ranked = header(headRow, "Risk", { numeric: true, sorted: "descending" }) const tbody = table.appendChild(new Node("tbody")) -for (const [num, text, risk] of [ +for (const [num, file, risk] of [ ["5", "b.rs", "9.0"], ["12", "a.rs", "7.0"], ["", "d.rs", "3.0"], @@ -156,56 +186,75 @@ for (const [num, text, risk] of [ ]) { const tr = tbody.appendChild(new Node("tr")) tr.appendChild(new Node("td", num)) - tr.appendChild(new Node("td", text)) + tr.appendChild(new Node("td", file)) tr.appendChild(new Node("td", risk)) } -// The script reads `document` as a free global. -new Function("document", script)(document) +const other = document.appendChild(new Node("table")) +other.setAttribute("class", "hotspot") +const otherHead = other.appendChild(new Node("thead")).appendChild(new Node("tr")) +const otherCol = header(otherHead, "Directory") +const otherBody = other.appendChild(new Node("tbody")) +for (const dir of ["src", "docs", "tests"]) { + otherBody.appendChild(new Node("tr")).appendChild(new Node("td", dir)) +} const column = (idx) => Array.from(tbody.rows, (r) => r.cells[idx].textContent) +const otherColumn = () => Array.from(otherBody.rows, (r) => r.cells[0].textContent) const out = {} +// The second table's order as rendered, captured before the script runs +// at all, so a script that sorted at load time — not only on click — is +// seen by the isolation check below. +const otherAsRendered = otherColumn() +out.otherAsRendered = otherAsRendered + +// The script reads `document` as a free global. +new Function("document", script)(document) + +// The page binds nothing to the header itself: the button is the control. +out.headerListeners = [numeric, text, ranked, otherCol].map((h) => h.th.listeners.size) +out.buttonListeners = [numeric, text, ranked, otherCol].map((h) => h.button.listeners.size) + + // The pre-ranked column announces `descending` at render time, so its // first activation must reverse to `ascending`, and clear nothing else // since no other header is sorted yet. -rankedTh.dispatch("click", {}) +ranked.button.dispatch("click", {}) out.rankedFirstClick = column(2) -out.rankedAriaAfterFirstClick = rankedTh.getAttribute("aria-sort") +out.rankedAriaAfterFirstClick = ranked.th.getAttribute("aria-sort") -numericTh.dispatch("click", {}) +numeric.button.dispatch("click", {}) out.numericAscending = column(0) -out.ariaAfterFirstClick = numericTh.getAttribute("aria-sort") -numericTh.dispatch("click", {}) +out.ariaAfterFirstClick = numeric.th.getAttribute("aria-sort") +numeric.button.dispatch("click", {}) out.numericDescending = column(0) -out.ariaAfterSecondClick = numericTh.getAttribute("aria-sort") +out.ariaAfterSecondClick = numeric.th.getAttribute("aria-sort") -textTh.dispatch("click", {}) +text.button.dispatch("click", {}) out.textAscending = column(1) -out.numericAriaCleared = numericTh.getAttribute("aria-sort") -out.rankedAriaCleared = rankedTh.getAttribute("aria-sort") - -// Keyboard on the header itself sorts and swallows the key's default. -const enterOnHeader = textTh.dispatch("keydown", { key: "Enter" }) -out.enterOnHeaderSorts = column(1) -out.enterOnHeaderPrevented = enterOnHeader.defaultPrevented -const spaceOnHeader = numericTh.dispatch("keydown", { key: " " }) -out.spaceOnHeaderSorts = column(0) -out.spaceOnHeaderPrevented = spaceOnHeader.defaultPrevented -// Enter on the child link bubbles to the header; the link must keep its -// default (navigation) and the order must not move. A browser activates -// an anchor whose Enter was not cancelled by synthesizing a `click` on -// it, which bubbles to the header too, so model that second event. +out.numericAriaCleared = numeric.th.getAttribute("aria-sort") +out.rankedAriaCleared = ranked.th.getAttribute("aria-sort") + +// Sorting one table leaves the other untouched, and vice versa. +out.otherUntouchedBySort = otherColumn().join() === otherAsRendered.join() +otherCol.button.dispatch("click", {}) +out.otherAscending = otherColumn() +out.firstUntouchedByOther = column(1).join() === ["a.rs", "b.rs", "c.rs", "d.rs"].join() + +// A click on the icon inside the button bubbles to the button and sorts. +const beforeIcon = column(0) +numeric.icon.dispatch("click", {}) +out.iconClickMovedRows = column(0).join() !== beforeIcon.join() + +// Only the button is the control: a click whose target is the +// documentation link, or the header cell itself, leaves the order alone. +// (The button carries the cell's padding, so in a browser the cell is +// rarely the target; the stub proves the listener is not on the th.) const before = column(0) -const enterOnLink = link.dispatch("keydown", { key: "Enter" }) -out.enterOnLinkPrevented = enterOnLink.defaultPrevented -if (!enterOnLink.defaultPrevented) link.dispatch("click", {}) -out.enterOnLinkMovedRows = column(0).join() !== before.join() -// A mouse click on the link is the link's too. -link.dispatch("click", {}) -out.clickOnLinkMovedRows = column(0).join() !== before.join() -// An unrelated key does nothing. -const tab = numericTh.dispatch("keydown", { key: "Tab" }) -out.tabPrevented = tab.defaultPrevented +numeric.link.dispatch("click", {}) +out.linkClickMovedRows = column(0).join() !== before.join() +numeric.th.dispatch("click", {}) +out.cellClickMovedRows = column(0).join() !== before.join() process.stdout.write(JSON.stringify(out))
DirectoryBus factorFiles
docs11
src22
` with a child `` reads `""`, which is fine while // the script never reads a header's text. One table carries a numeric // column whose cells are `5`, `12`, `` (blank) and `1,000` and a text -// column; its first header holds a child link, as the metric headers -// in the real page do, and its third ships `aria-sort="descending"`, -// as the pre-ranked column of every hotspot table does. +// column. Every header holds its label in a `button.sort` with an empty +// icon span, as the real page renders; the first also carries a sibling +// documentation link, as the metric headers do, and the third ships +// `aria-sort="descending"`, as the pre-ranked column of every hotspot +// table does. A second, one-column table proves sorting one does not +// touch the other. import { readFileSync } from "node:fs" @@ -94,6 +98,12 @@ class Node { return event } querySelectorAll(selector) { + return collection(this.#descendants(selector), { forEach: true }) + } + querySelector(selector) { + return this.#descendants(selector)[0] ?? null + } + #descendants(selector) { const out = [] const walk = (node) => { for (const child of node.#children) { @@ -102,7 +112,7 @@ class Node { } } walk(this) - return collection(out, { forEach: true }) + return out } // Each getter exists only on the element the DOM defines it for, so // a script reading `tbl.rows` or `tbody.children` fails here by name @@ -130,25 +140,45 @@ function matches(node, selector) { return node.tag === "table" && node.attrs.get("class") === "hotspot" case "thead th": return node.tag === "th" && node.parent?.parent?.tag === "thead" + case "button.sort": + return node.tag === "button" && node.attrs.get("class") === "sort" default: throw new Error(`stub does not model selector ${selector}`) } } const document = new Node("document") + +// A header as the page renders it: `[?]