repometry 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -104,14 +104,21 @@
104
104
  },
105
105
  "products": {
106
106
  "type": "object",
107
+ "properties": {
108
+ "repometry.lcov-lines/v1": {
109
+ "type": "array",
110
+ "minItems": 1,
111
+ "maxItems": 1,
112
+ "items": {
113
+ "$ref": "#/$defs/reportProduct",
114
+ "type": "object",
115
+ "properties": { "value": { "$ref": "#/$defs/lcovLines" } }
116
+ }
117
+ }
118
+ },
107
119
  "additionalProperties": {
108
120
  "type": "array",
109
- "items": {
110
- "type": "object",
111
- "required": ["operation", "value"],
112
- "properties": { "operation": { "type": "string" }, "path": { "type": "string" }, "value": true },
113
- "additionalProperties": false
114
- }
121
+ "items": { "$ref": "#/$defs/reportProduct" }
115
122
  }
116
123
  }
117
124
  },
@@ -132,6 +139,35 @@
132
139
  },
133
140
  "additionalProperties": false,
134
141
  "$defs": {
142
+ "reportProduct": {
143
+ "type": "object",
144
+ "required": ["operation", "value"],
145
+ "properties": { "operation": { "type": "string" }, "path": { "type": "string" }, "value": true },
146
+ "additionalProperties": false
147
+ },
148
+ "lcovLines": {
149
+ "type": "object",
150
+ "additionalProperties": {
151
+ "type": "object",
152
+ "required": ["covered", "uncovered"],
153
+ "additionalProperties": false,
154
+ "properties": {
155
+ "covered": { "$ref": "#/$defs/lcovLineRanges" },
156
+ "uncovered": { "$ref": "#/$defs/lcovLineRanges" },
157
+ "partial": { "$ref": "#/$defs/lcovLineRanges" }
158
+ }
159
+ }
160
+ },
161
+ "lcovLineRanges": {
162
+ "type": "array",
163
+ "description": "Sorted, merged 1-based inclusive line ranges.",
164
+ "items": {
165
+ "type": "array",
166
+ "minItems": 2,
167
+ "prefixItems": [{ "type": "integer", "minimum": 1 }, { "type": "integer", "minimum": 1 }],
168
+ "items": false
169
+ }
170
+ },
135
171
  "pluginRule": {
136
172
  "type": "object",
137
173
  "required": ["id", "category"],
@@ -49,6 +49,9 @@
49
49
  "findings": {
50
50
  "$ref": "urn:repometry:schema:report:2#/properties/findings"
51
51
  },
52
+ "lineCoverage": {
53
+ "$ref": "urn:repometry:schema:report:2#/$defs/lcovLines"
54
+ },
52
55
  "components": {
53
56
  "type": "array",
54
57
  "items": {
@@ -428,7 +428,17 @@
428
428
  .fx-source { min-width: 0; padding: 0; overflow: hidden; }
429
429
  .fx-source-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .25rem 1rem; padding: .625rem 1rem; background: var(--band); border-bottom: 1px solid var(--rule); }
430
430
  .fx-source-path { min-width: 0; font-size: .8125rem; color: var(--ink); overflow-wrap: anywhere; }
431
+ .fx-source-name { display: inline-flex; align-items: center; gap: .125rem; min-width: 0; }
432
+ .fx-source-name .fx-copy-inline { position: static; flex: none; width: 1.5rem; height: 1.5rem; }
433
+ .fx-source-name .fx-copy-inline svg { width: .8125rem; height: .8125rem; }
431
434
  .fx-source-meta { display: inline-flex; align-items: center; gap: .375rem; font-size: .75rem; color: var(--secondary); }
435
+ /* The switch between findings and coverage leads the head's right side; a narrow head wraps it under the name whole. */
436
+ .fx-source-tools { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: .375rem .875rem; min-width: 0; }
437
+ .fx-source-head:has(.fx-source-layer) { padding-block: .375rem; }
438
+ .fx-source-layer { height: 1.75rem; }
439
+ .fx-source-layer button { padding: 0 .625rem; font-size: .75rem; }
440
+ /* Under the file name, on a phone, the switch and the meta line up on the left, as the name does. */
441
+ @media (max-width: 42rem) { .fx-source-tools { justify-content: flex-start; } }
432
442
  .fx-source-wait, .fx-source-missing { margin: 0; padding: 1.25rem 1rem; }
433
443
  .fx-source-missing { color: var(--secondary); font-size: .875rem; }
434
444
  .src { overflow-x: auto; padding: .375rem 0 .75rem; font-family: var(--mono); font-size: .8125rem; line-height: 1.6; tab-size: 2; }
@@ -439,6 +449,19 @@
439
449
  .src-number:hover { color: var(--ink); }
440
450
  .src-code { padding-right: 1.5rem; font: inherit; white-space: pre; color: var(--ink); }
441
451
  .src-flagged { background: var(--warn-bg); }
452
+ /* Coverage replaces the findings in the gutter and leaves the code plain: each measured line's cell is tinted, quiet
453
+ green where tests ran, coral where they missed, amber where they missed branches, and says how often it ran where
454
+ the report counts it; a miss needs no number. Blank and comment lines keep the strip's tint without a count; unmeasured lines
455
+ stay plain, and runs of lines join into one strip. */
456
+ .src-cov { display: none; }
457
+ .src[data-layer="coverage"] .src-complexity, .src[data-layer="coverage"] .src-note { display: none; }
458
+ .src[data-layer="coverage"] .src-flagged { background: none; }
459
+ .src[data-layer="coverage"] .src-line { grid-template-columns: 3.25rem 3rem max-content; }
460
+ .src[data-layer="coverage"] .src-cov { display: flex; flex: 1; align-self: stretch; align-items: center; justify-content: flex-end;
461
+ padding-right: .5rem; font-family: var(--sans); font-size: .6875rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
462
+ .src-cov-mark-covered { color: var(--cov-hit-ink); background: var(--cov-hit-bg); }
463
+ .src-cov-mark-partial { color: var(--cov-part-ink); background: var(--cov-part-bg); }
464
+ .src-cov-mark-uncovered { color: var(--cov-miss-ink); background: var(--cov-miss-bg); }
442
465
  .src-target, .src-target:hover { background: var(--accent-soft); box-shadow: inset 3px 0 0 var(--accent); }
443
466
  .src-complexity { min-width: 1.375rem; padding: 0 .25rem; font-family: var(--sans); font-size: .6875rem; font-weight: 650; line-height: 1.125rem; text-align: center; border-radius: 4px; color: var(--secondary); background: var(--surface-2); box-shadow: inset 0 0 0 1px var(--rule); }
444
467
  .src-band-1 { color: var(--heat-ink); background: var(--heat-1); box-shadow: none; }
@@ -22,6 +22,13 @@
22
22
  --flag-good: #2f9445;
23
23
  --flag-bad: #c63d36;
24
24
  --bad-bg: #fdecea;
25
+ /* Line coverage cells in the source gutter: a quiet green, coral for what tests missed, amber for missed branches. */
26
+ --cov-hit-bg: #e2f2e8;
27
+ --cov-hit-ink: #2f6e49;
28
+ --cov-miss-bg: #fbe2df;
29
+ --cov-miss-ink: #a8382e;
30
+ --cov-part-bg: #fbedcd;
31
+ --cov-part-ink: #7d5a10;
25
32
  --bad-ink: #9f2a21;
26
33
  --warn-bg: #fdf3dc;
27
34
  --warn-ink: #81580a;
@@ -86,6 +93,12 @@
86
93
  --flag-good: #5fd06a;
87
94
  --flag-bad: #f0736b;
88
95
  --bad-bg: #3a1c1a;
96
+ --cov-hit-bg: #15301f;
97
+ --cov-hit-ink: #8fd0a9;
98
+ --cov-miss-bg: #3b1d1a;
99
+ --cov-miss-ink: #f0958c;
100
+ --cov-part-bg: #372a10;
101
+ --cov-part-ink: #e6c272;
89
102
  --bad-ink: #ffb1a8;
90
103
  --warn-bg: #352812;
91
104
  --warn-ink: #f2cd7f;
@@ -18,7 +18,7 @@ const selected = ['structure/size', 'structure/complexity', 'maintainability/fil
18
18
  const bindings = new Map(selected.map(operation => [operation, { syntax: { operation: 'babel-syntax/parse' } }]));
19
19
  const sourcePlan = plan({ plugins: sourcePlugins, select: selected, inputs: new Map([['file', sourceFile.id]]), bindings });
20
20
  const duplicationPlan = plan({ plugins: [duplication], select: ['duplication/detect'], inputs: new Map([['sources', duplicationInput.id]]) });
21
- const coveragePlan = plan({ plugins: [coverage], select: ['lcov/import'], inputs: new Map([['lcov', lcovInput.id]]) });
21
+ const coveragePlan = plan({ plugins: [coverage], select: ['lcov/import', 'lcov/lines'], inputs: new Map([['lcov', lcovInput.id]]) });
22
22
  const measurementDefinitions = {
23
23
  [definitions.lines]: 'Physical lines including blank lines and comments. A final line terminator does not add a line.',
24
24
  [definitions.functions]: 'Babel function nodes with bodies, including nested functions and methods.',
@@ -75,8 +75,10 @@ export async function analyzeSnapshot({ snapshot, excludedOutput, excludedPaths
75
75
  if (inputCoverage !== undefined) {
76
76
  const value = { text: inputCoverage.text, root: inputCoverage.sourceRoot, sourceLines: sourceLineCounts(snapshot.files),
77
77
  excludes: sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded) };
78
- const result = (await execute(coveragePlan, new Map([['lcov', { contract: lcovInput.id, value }]]))).get('lcov/import');
79
- record(coveragePlan[0], result);
78
+ const outcomes = await execute(coveragePlan, new Map([['lcov', { contract: lcovInput.id, value }]]));
79
+ for (const task of coveragePlan)
80
+ record(task, outcomes.get(task.key));
81
+ const result = outcomes.get('lcov/import');
80
82
  if (result.state === 'completed' && coverageResult.accepts(result.product.value)) {
81
83
  for (const { path, reason } of result.product.value.gaps) {
82
84
  diagnostics.push({ operation: 'lcov/import', state: 'partial', path, message: reason });
@@ -0,0 +1,9 @@
1
+ import type { DataContract } from '../engine/plugin.js';
2
+ export type CoveredLineRange = readonly [first: number, last: number];
3
+ export interface FileLineCoverage {
4
+ readonly covered: readonly CoveredLineRange[];
5
+ readonly uncovered: readonly CoveredLineRange[];
6
+ readonly partial?: readonly CoveredLineRange[];
7
+ }
8
+ export type LineCoverage = Readonly<Record<string, FileLineCoverage>>;
9
+ export declare const lcovLines: DataContract<LineCoverage>;
@@ -0,0 +1,21 @@
1
+ import { isRecord } from '../engine/plugin.js';
2
+ export const lcovLines = {
3
+ id: 'repometry.lcov-lines/v1',
4
+ accepts: (value) => isRecord(value) && Object.values(value).every(file => isRecord(file) && isMerged(file.covered) && isMerged(file.uncovered) &&
5
+ (file.partial === undefined || isMerged(file.partial))),
6
+ };
7
+ function isMerged(value) {
8
+ if (!Array.isArray(value))
9
+ return false;
10
+ let previous = -1;
11
+ for (const range of value) {
12
+ if (!Array.isArray(range) || range.length !== 2)
13
+ return false;
14
+ const [first, last] = range;
15
+ if (typeof first !== 'number' || typeof last !== 'number' || !Number.isSafeInteger(first)
16
+ || !Number.isSafeInteger(last) || first <= previous + 1 || last < first)
17
+ return false;
18
+ previous = last;
19
+ }
20
+ return true;
21
+ }
@@ -1,5 +1,6 @@
1
1
  import type { DataContract, Plugin } from '../../core/engine/plugin.js';
2
2
  import type { Measurement } from '../../core/model/measurement.js';
3
+ import type { LineCoverage } from '../../core/model/line-coverage.js';
3
4
  export interface CoverageInput {
4
5
  readonly text: string;
5
6
  readonly root: string;
@@ -12,6 +13,7 @@ interface CoverageResult {
12
13
  readonly path: string;
13
14
  readonly reason: string;
14
15
  }[];
16
+ readonly lineCoverage: LineCoverage;
15
17
  }
16
18
  export declare const lcovInput: DataContract<CoverageInput>;
17
19
  export declare const coverageResult: DataContract<CoverageResult>;
@@ -1,7 +1,9 @@
1
1
  import { posix, win32 } from 'node:path';
2
+ import reportSchema from '../../../resources/report/json/report-v2.schema.json' with { type: 'json' };
2
3
  import { isRecord, pluginApi } from '../../core/engine/plugin.js';
3
4
  import { comparePaths } from '../../core/model/snapshot.js';
4
5
  import { definitions, measurements } from '../../core/model/measurement.js';
6
+ import { lcovLines } from '../../core/model/line-coverage.js';
5
7
  export const lcovInput = {
6
8
  id: 'repometry.lcov-input/v1',
7
9
  accepts: (value) => isRecord(value) && typeof value.text === 'string'
@@ -11,7 +13,8 @@ export const lcovInput = {
11
13
  export const coverageResult = {
12
14
  id: 'repometry.coverage-result/v1',
13
15
  accepts: (value) => isRecord(value) && measurements.accepts(value.measurements)
14
- && Array.isArray(value.gaps) && value.gaps.every(gap => isRecord(gap) && typeof gap.path === 'string' && typeof gap.reason === 'string'),
16
+ && Array.isArray(value.gaps) && value.gaps.every(gap => isRecord(gap) && typeof gap.path === 'string' && typeof gap.reason === 'string')
17
+ && lcovLines.accepts(value.lineCoverage),
15
18
  };
16
19
  export const coverage = {
17
20
  id: 'lcov',
@@ -31,13 +34,20 @@ export const coverage = {
31
34
  ratio: { of: definitions.coveredFunctions, over: definitions.coverableFunctions }, bands: [0.6, 0.7, 0.8, 0.9], group: 'Coverage' },
32
35
  { id: definitions.coveredFunctions, label: 'Covered functions', unit: 'count', scope: 'file', aggregate: 'sum', better: 'higher', group: 'Coverage' },
33
36
  { id: definitions.coverableFunctions, label: 'Measured functions', unit: 'count', scope: 'file', aggregate: 'sum', better: 'none', group: 'Coverage' },
34
- ] }],
37
+ ] }, { contract: lcovLines.id, persistence: 'report',
38
+ schema: { ...reportSchema.$defs.lcovLines, $defs: { lcovLineRanges: reportSchema.$defs.lcovLineRanges } } }],
35
39
  operations: [{
36
40
  id: 'import',
37
41
  role: 'inspection',
38
42
  inputs: { report: lcovInput },
39
43
  output: coverageResult,
40
44
  execute: inputs => importCoverage(inputs.read('report', lcovInput)),
45
+ }, {
46
+ id: 'lines',
47
+ role: 'inspection',
48
+ inputs: { coverage: coverageResult },
49
+ output: lcovLines,
50
+ execute: inputs => inputs.read('coverage', coverageResult).lineCoverage,
41
51
  }],
42
52
  };
43
53
  export function mapCoverage({ text, root, sourceLines, excludes }) {
@@ -135,15 +145,21 @@ export function mapCoverage({ text, root, sourceLines, excludes }) {
135
145
  function importCoverage(input) {
136
146
  const { files, branches, functions, gaps } = mapCoverage(input);
137
147
  const rows = [];
148
+ const lineCoverage = [];
138
149
  let totalCovered = 0;
139
150
  let totalLines = 0;
140
151
  for (const [path, hits] of [...files].sort(([left], [right]) => comparePaths(left, right))) {
141
152
  if (gaps.has(path))
142
153
  continue;
143
- let covered = 0;
144
- for (const hit of hits.values())
145
- if (hit)
146
- covered++;
154
+ const hitLines = [], missedLines = [];
155
+ for (const [line, hit] of hits)
156
+ (hit ? hitLines : missedLines).push(line);
157
+ const partial = mergedRanges(partiallyCoveredLines(branches.get(path), input.sourceLines.get(path)));
158
+ if (hits.size || partial.length)
159
+ lineCoverage.push([path, {
160
+ covered: mergedRanges(hitLines), uncovered: mergedRanges(missedLines), ...(partial.length ? { partial } : {}),
161
+ }]);
162
+ const covered = hitLines.length;
147
163
  totalCovered += covered;
148
164
  totalLines += hits.size;
149
165
  rows.push({ definition: definitions.coverage, target: 'file', path, covered, total: hits.size, value: ratio(covered, hits.size) });
@@ -157,9 +173,29 @@ function importCoverage(input) {
157
173
  ...hitRows(branches, gaps, definitions.branchCoverage, definitions.coveredBranches, definitions.coverableBranches),
158
174
  ...hitRows(functions, gaps, definitions.functionCoverage, definitions.coveredFunctions, definitions.coverableFunctions),
159
175
  ];
160
- return { measurements: [...rows, ...counts, ...extra],
176
+ return { measurements: [...rows, ...counts, ...extra], lineCoverage: Object.fromEntries(lineCoverage),
161
177
  gaps: [...gaps].sort(([left], [right]) => comparePaths(left, right)).map(([path, reason]) => ({ path, reason })) };
162
178
  }
179
+ function partiallyCoveredLines(branches, lastLine) {
180
+ const taken = new Set(), missed = new Set();
181
+ for (const [branch, hit] of branches ?? []) {
182
+ const line = Number(branch.slice(0, branch.indexOf(',')));
183
+ if (line <= lastLine)
184
+ (hit ? taken : missed).add(line);
185
+ }
186
+ return [...taken].filter(line => missed.has(line));
187
+ }
188
+ function mergedRanges(lines) {
189
+ const ranges = [];
190
+ for (const line of lines.sort((left, right) => left - right)) {
191
+ const previous = ranges.at(-1);
192
+ if (previous && previous[1] + 1 === line)
193
+ previous[1] = line;
194
+ else
195
+ ranges.push([line, line]);
196
+ }
197
+ return ranges;
198
+ }
163
199
  /** Per-file and repository ratios with their counts, for a kind the LCOV reports; nothing when it reports none. */
164
200
  function hitRows(files, gaps, ratioId, coveredId, totalId) {
165
201
  const rows = [];
@@ -19,6 +19,8 @@ interface Navigation {
19
19
  readonly level?: string | undefined;
20
20
  /** What Hotspots ranks by. */
21
21
  readonly rank?: string | undefined;
22
+ /** What an open file's lines show: its findings (the default) or its coverage. */
23
+ readonly layer?: string | undefined;
22
24
  /** Source text of a file at this commit; absent where the view cannot load source. */
23
25
  readonly source?: ((path: string) => Promise<string | null>) | undefined;
24
26
  /** The file's page on its forge, when the export names one. */
@@ -37,6 +39,7 @@ export interface LinkOptions {
37
39
  readonly category?: string;
38
40
  readonly level?: string;
39
41
  readonly rank?: string;
42
+ readonly layer?: string;
40
43
  }
41
44
  /**
42
45
  * The finding categories Repometry counts as code smells, mirroring core's quality summary (structure and
@@ -1,7 +1,7 @@
1
1
  import { formatQuery, ignoredLabel, isLockfile, languageColor, languageOf, languageShares, lockfilesLabel, matches, parseQuery, queryField, sameClause, sized, suggest, usePluginMeasures } from './viewer-filter.js';
2
2
  import { bandLabels as pluginBandLabels, bandOf, bandScale, catalogIndex, compareValues, entryValue, firstSortAscending, format, rollUp } from './viewer-metric-registry.js';
3
3
  import { extendCatalog, labelOf, pluginMetrics, pluginSpec, securityRisks, size } from './viewer-metrics.js';
4
- import { highlightCode, lineSnippet, renderExcerpt, renderSource } from './viewer-source.js';
4
+ import { highlightCode, isSourceLayer, lineHits, lineSnippet, lineStates, renderExcerpt, renderSource, setSourceLayer } from './viewer-source.js';
5
5
  /**
6
6
  * The finding categories Repometry counts as code smells, mirroring core's quality summary (structure and
7
7
  * duplication), so the Overview's smell count links to exactly the findings it counts.
@@ -544,10 +544,9 @@ function directorySummary(entry, analysed, lockfiles, selection) {
544
544
  panel.setAttribute('aria-label', selection ? 'Selection totals' : 'Folder totals');
545
545
  const heading = element('div', 'fx-aside-heading');
546
546
  heading.append(element('h2', '', selection ? 'Selection' : entry.path ? basename(entry.path) : 'All files'));
547
+ // The breadcrumbs above name the folder; only a selection needs its words here.
547
548
  if (selection)
548
549
  heading.append(element('p', 'fx-aside-path fx-aside-selection', selection));
549
- else if (entry.path.includes('/'))
550
- heading.append(element('p', 'fx-aside-path', parentPath(entry.path) + '/'));
551
550
  const facts = element('dl', 'fx-kv');
552
551
  // A measurement the inspection did not take leaves no row behind.
553
552
  const quality = entry.quality;
@@ -578,13 +577,12 @@ function fileDetails(details, entry, navigation, hooks = {}) {
578
577
  const panel = element('aside', 'fx-aside fx-file');
579
578
  panel.setAttribute('aria-label', 'File details');
580
579
  const heading = element('div', 'fx-aside-heading');
580
+ // The breadcrumbs above name the folder, so the title is the file alone.
581
581
  const title = element('h2', '', basename(entry.path));
582
582
  const close = link(navigation.href('metrics', { directory: parentPath(entry.path) }), '', 'fx-close');
583
583
  close.setAttribute('aria-label', 'Close file details');
584
584
  close.title = 'Close file details';
585
585
  heading.append(title, close);
586
- if (entry.path.includes('/'))
587
- heading.append(element('p', 'fx-aside-path', parentPath(entry.path) + '/'));
588
586
  const facts = element('dl', 'fx-kv');
589
587
  const quality = entry.quality;
590
588
  if (quality?.codeLines !== undefined)
@@ -683,15 +681,37 @@ function fileView(details, navigation, file, load) {
683
681
  // The folder is in the breadcrumbs right above; the head names the file alone, with its full path on hover.
684
682
  const name = element('code', 'fx-source-path', basename(file.path));
685
683
  name.title = file.path;
686
- head.append(name, element('span', 'fx-source-meta'));
687
- head.lastElementChild.append(dot, `${language} · ${count(file.lines)} lines`);
684
+ // The whole path from the repository root is a click away; a refused clipboard shows it in the name's place, selected.
685
+ const named = element('span', 'fx-source-name');
686
+ named.append(name, copyPathButton(file.path, () => {
687
+ name.textContent = file.path;
688
+ return name;
689
+ }));
690
+ const meta = element('span', 'fx-source-meta');
691
+ meta.append(dot, `${language} · ${count(file.lines)} lines`);
692
+ // Lines show the findings, or the tests' coverage where the file has it; without coverage the head stays as it was.
693
+ const coverage = fileCoverage(details, file.path);
694
+ let layer = coverage ? sourceLayer(navigation.layer) : 'issues';
695
+ let line = navigation.line;
696
+ const place = () => nav.href('metrics', { directory: parentPath(file.path), file: file.path, ...line ? { line } : {},
697
+ ...layer === 'coverage' ? { layer } : {} });
698
+ const toggle = coverage ? segmented('Lines show', [['issues', 'Issues'], ['coverage', 'Coverage']], layer, value => {
699
+ layer = value;
700
+ rememberLayer(layer);
701
+ setSourceLayer(body, layer);
702
+ history.replaceState(history.state, '', place());
703
+ }) : null;
704
+ toggle?.classList.add('fx-source-layer');
705
+ const tools = element('div', 'fx-source-tools');
706
+ tools.append(...toggle ? [toggle] : [], meta);
707
+ head.append(named, tools);
688
708
  // The forge's page for the file, at the chosen line, whether or not the text opens here.
689
709
  const page = navigation.sourcePage?.(file.path, navigation.line);
690
710
  const forge = page ? link(page.href, `View on ${page.provider}`, 'fx-source-forge') : null;
691
711
  if (forge) {
692
712
  forge.target = '_blank';
693
713
  forge.rel = 'noopener noreferrer';
694
- head.lastElementChild.append(' · ', forge);
714
+ meta.append(' · ', forge);
695
715
  }
696
716
  const body = element('div', 'fx-source-body');
697
717
  body.append(element('p', 'fx-note fx-source-wait', 'Loading source…'));
@@ -708,11 +728,14 @@ function fileView(details, navigation, file, load) {
708
728
  if (text === null) {
709
729
  // No locator, a private repository, a commit never pushed: one quiet state, and the forge's page when there is one.
710
730
  body.replaceChildren(element('p', 'fx-source-missing', 'Source not available'));
731
+ // Nothing to shade: the head is the one a file without coverage has.
732
+ toggle?.remove();
711
733
  return;
712
734
  }
713
- const choose = (line) => {
714
- history.replaceState(history.state, '', nav.href('metrics', { directory: parentPath(file.path), file: file.path, line }));
715
- const moved = navigation.sourcePage?.(file.path, line);
735
+ const choose = (chosen) => {
736
+ line = chosen;
737
+ history.replaceState(history.state, '', place());
738
+ const moved = navigation.sourcePage?.(file.path, chosen);
716
739
  if (forge && moved)
717
740
  forge.href = moved.href;
718
741
  };
@@ -720,6 +743,7 @@ function fileView(details, navigation, file, load) {
720
743
  path: file.path,
721
744
  functions: functions.flatMap(record => record.line === null ? [] : [{ line: record.line, complexity: record.complexity, name: record.name }]),
722
745
  notes, line: navigation.line, choose,
746
+ coverage: coverage ? lineStates(coverage) : undefined, hits: coverage ? lineHits(coverage) : undefined, layer,
723
747
  });
724
748
  const next = fileDetails(details, file, nav, { text, reveal: line => { reveal(line); choose(line); } });
725
749
  aside.replaceWith(next);
@@ -727,6 +751,32 @@ function fileView(details, navigation, file, load) {
727
751
  });
728
752
  return view;
729
753
  }
754
+ /** A file's line coverage, where the inspection's coverage report names the file. */
755
+ function fileCoverage(details, path) {
756
+ const coverage = details.lineCoverage;
757
+ return coverage && Object.hasOwn(coverage, path) ? coverage[path] : undefined;
758
+ }
759
+ const layerKey = 'repometry.source-layer';
760
+ /** The URL's choice of what lines show, else the one made earlier in this session, else the findings. */
761
+ function sourceLayer(requested) {
762
+ if (isSourceLayer(requested))
763
+ return requested;
764
+ try {
765
+ const stored = sessionStorage.getItem(layerKey);
766
+ return isSourceLayer(stored) ? stored : 'issues';
767
+ }
768
+ catch {
769
+ return 'issues';
770
+ }
771
+ }
772
+ function rememberLayer(layer) {
773
+ try {
774
+ sessionStorage.setItem(layerKey, layer);
775
+ }
776
+ catch {
777
+ // Blocked storage only forgets the choice; the URL still carries it.
778
+ }
779
+ }
730
780
  /**
731
781
  * The top of a relative colour scale, per level: files against files, folders against the folders at their depth. One
732
782
  * scale for both would let a folder's sum outshine every file in it, and the map would read hot folders over pale files.
@@ -1747,6 +1797,38 @@ function ignoreSnippet(finding) {
1747
1797
  details.append(title, hint, code, feedback);
1748
1798
  return details;
1749
1799
  }
1800
+ /**
1801
+ * Copies a file's path from the repository root. Where the browser refuses the clipboard, `show` puts the path on the
1802
+ * page and it is selected, for the reader's own copy shortcut.
1803
+ */
1804
+ function copyPathButton(path, show) {
1805
+ const label = 'Copy path';
1806
+ const copy = element('button', 'fx-copy fx-copy-inline');
1807
+ copy.type = 'button';
1808
+ copy.title = `${label}: ${path}`;
1809
+ copy.setAttribute('aria-label', label);
1810
+ copy.append(copyIcon());
1811
+ const status = element('span', 'visually-hidden');
1812
+ status.setAttribute('role', 'status');
1813
+ copy.append(status);
1814
+ let reset;
1815
+ copy.addEventListener('click', async () => {
1816
+ clearTimeout(reset);
1817
+ try {
1818
+ if (!navigator.clipboard)
1819
+ throw new Error('Clipboard unavailable');
1820
+ await navigator.clipboard.writeText(path);
1821
+ copy.classList.add('fx-copied');
1822
+ status.textContent = 'Path copied';
1823
+ reset = setTimeout(() => { copy.classList.remove('fx-copied'); status.textContent = ''; }, 1500);
1824
+ }
1825
+ catch {
1826
+ window.getSelection()?.selectAllChildren(show());
1827
+ status.textContent = 'Path selected. Press your copy shortcut.';
1828
+ }
1829
+ });
1830
+ return copy;
1831
+ }
1750
1832
  /** The common copy glyph, two offset sheets, with the check it turns into once copied. */
1751
1833
  export function copyIcon() {
1752
1834
  const svg = svgElement('svg');
@@ -1,4 +1,5 @@
1
1
  import type { SourceLocator } from '../../json/wire/summary-model.js';
2
+ import type { InspectionDetails } from '../../json/wire/inspection-details-model.js';
2
3
  /** Where the viewer fetches a file's text, as the export names it: a URL template and the page a person would open. */
3
4
  export type { SourceLocator } from '../../json/wire/summary-model.js';
4
5
  export interface SourcePlace {
@@ -36,15 +37,42 @@ export interface SourceNote {
36
37
  readonly title: string;
37
38
  readonly message: string;
38
39
  }
40
+ /** Line ranges of one file's coverage: 1-based, inclusive and merged. Partial lines ran with some branches missed. */
41
+ export type FileLineCoverage = NonNullable<InspectionDetails['lineCoverage']>[string];
42
+ export type LineState = 'covered' | 'partial' | 'uncovered';
43
+ /** What the source view's lines show: the inspection's findings and complexity, or the tests' coverage. */
44
+ export type SourceLayer = 'issues' | 'coverage';
45
+ export declare function isSourceLayer(value: string | null | undefined): value is SourceLayer;
46
+ /**
47
+ * Each line's coverage, by line number; a line no range names was not measured. Where ranges overlap, the worse
48
+ * state wins: a line a test missed is never shown as covered.
49
+ */
50
+ export declare function lineStates(coverage: FileLineCoverage): Map<number, LineState>;
51
+ /** Runs of equal hit counts: first and last line, 1-based and inclusive, and how often tests ran them; 0 is a miss. */
52
+ export type HitRun = readonly [first: number, last: number, count: number];
53
+ /** How often tests ran each line, where the report carries the counts; an older report has none. */
54
+ export declare function lineHits(coverage: FileLineCoverage): Map<number, number>;
55
+ /** A count short enough for the gutter: 3×, 980×, 1.2K×, 45K×, 270K×, 3.4M×. */
56
+ export declare function hitLabel(count: number): string;
57
+ /** What a measured line says to a pointer and a screen reader: its state, and how often it ran where that is known. */
58
+ export declare function lineCoverageText(state: LineState, count?: number): string;
39
59
  export interface SourceOptions {
40
60
  readonly path: string;
41
61
  readonly functions: readonly SourceFunction[];
42
62
  readonly notes: readonly SourceNote[];
63
+ /** Each line's coverage, where the file has a coverage report. */
64
+ readonly coverage?: ReadonlyMap<number, LineState> | undefined;
65
+ /** How often tests ran each line, where the report counts it. */
66
+ readonly hits?: ReadonlyMap<number, number> | undefined;
67
+ /** What the lines show first; the view switches it with setSourceLayer. */
68
+ readonly layer?: SourceLayer | undefined;
43
69
  /** The line to bring into view and mark, from the URL. */
44
70
  readonly line?: number | undefined;
45
71
  /** Called when a line number is chosen, so the page can put it in the URL. */
46
72
  readonly choose: (line: number) => void;
47
73
  }
74
+ /** Switches a rendered source between its findings and its coverage, without drawing it again. */
75
+ export declare function setSourceLayer(container: HTMLElement, layer: SourceLayer): void;
48
76
  /** The source as numbered lines; returns a function that brings a line into view and marks it. */
49
77
  export declare function renderSource(container: HTMLElement, text: string, options: SourceOptions): (line: number) => void;
50
78
  export interface ExcerptOptions {
@@ -73,3 +101,5 @@ export type TokenKind = '' | 'c' | 's' | 'n' | 'k';
73
101
  * template literal stays coloured to its end. Other languages come back as plain text.
74
102
  */
75
103
  export declare function tokenizer(path: string): (line: string) => [TokenKind, string][];
104
+ /** A line with no code: blank, or nothing but comment. */
105
+ export declare function codeless(runs: readonly (readonly [TokenKind, string])[]): boolean;
@@ -56,15 +56,67 @@ export function sourcePage(sha, path, line) {
56
56
  const name = providerNames[locator.provider.toLowerCase()] ?? locator.provider.charAt(0).toUpperCase() + locator.provider.slice(1);
57
57
  return { href: expandLocator(locator.web, { revision: sha, path, line }), provider: name };
58
58
  }
59
+ export function isSourceLayer(value) {
60
+ return value === 'issues' || value === 'coverage';
61
+ }
62
+ /**
63
+ * Each line's coverage, by line number; a line no range names was not measured. Where ranges overlap, the worse
64
+ * state wins: a line a test missed is never shown as covered.
65
+ */
66
+ export function lineStates(coverage) {
67
+ const states = new Map();
68
+ const lay = (ranges, state) => {
69
+ for (const [from, to] of ranges ?? [])
70
+ for (let line = Math.max(1, from); line <= to; line++)
71
+ states.set(line, state);
72
+ };
73
+ lay(coverage.covered, 'covered');
74
+ lay(coverage.partial, 'partial');
75
+ lay(coverage.uncovered, 'uncovered');
76
+ return states;
77
+ }
78
+ /** How often tests ran each line, where the report carries the counts; an older report has none. */
79
+ export function lineHits(coverage) {
80
+ // The wire is getting `hits`; until it lands the field is read off the record as the agreed shape.
81
+ const runs = coverage.hits;
82
+ const hits = new Map();
83
+ for (const [from, to, count] of runs ?? [])
84
+ for (let line = Math.max(1, from); line <= to; line++)
85
+ hits.set(line, count);
86
+ return hits;
87
+ }
88
+ // Two figures are enough for a glance; the tooltip has the whole count.
89
+ const compactCount = new Intl.NumberFormat('en', { notation: 'compact', maximumSignificantDigits: 2 });
90
+ const fullCount = new Intl.NumberFormat();
91
+ /** A count short enough for the gutter: 3×, 980×, 1.2K×, 45K×, 270K×, 3.4M×. */
92
+ export function hitLabel(count) {
93
+ return `${count < 1000 ? count : compactCount.format(count)}×`;
94
+ }
95
+ /** What a measured line says to a pointer and a screen reader: its state, and how often it ran where that is known. */
96
+ export function lineCoverageText(state, count) {
97
+ if (count === undefined || state === 'uncovered')
98
+ return lineStateNames[state];
99
+ return `${lineStateNames[state]}. Ran ${fullCount.format(count)} ${count === 1 ? 'time' : 'times'}`;
100
+ }
101
+ const lineStateNames = {
102
+ covered: 'Covered', partial: 'Partly covered: some branches missed', uncovered: 'Not covered',
103
+ };
104
+ /** Switches a rendered source between its findings and its coverage, without drawing it again. */
105
+ export function setSourceLayer(container, layer) {
106
+ const code = container.querySelector(':scope > .src');
107
+ if (code)
108
+ code.dataset.layer = layer;
109
+ }
59
110
  /** The source as numbered lines; returns a function that brings a line into view and marks it. */
60
111
  export function renderSource(container, text, options) {
61
112
  const lines = text.replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n');
62
- const highlight = highlighter(options.path);
113
+ const tokenize = tokenizer(options.path);
63
114
  const starts = new Map(options.functions.map(entry => [entry.line, entry]));
64
115
  const notes = new Map();
65
116
  for (const note of options.notes)
66
117
  notes.set(note.line, [...notes.get(note.line) ?? [], note]);
67
118
  const code = element('div', 'src');
119
+ code.dataset.layer = options.layer ?? 'issues';
68
120
  code.setAttribute('role', 'region');
69
121
  code.setAttribute('aria-label', `Source of ${options.path}`);
70
122
  const rows = [];
@@ -80,6 +132,23 @@ export function renderSource(container, text, options) {
80
132
  badge.title = `Cyclomatic complexity ${start.complexity}`;
81
133
  mark.append(badge);
82
134
  }
135
+ // The coverage layer tints each measured line's gutter cell and writes in it how often the line ran; a miss's red says it.
136
+ // Some tools count blank and comment lines as run; nothing runs there, so they keep the strip's tint and say nothing.
137
+ const runs = tokenize(line);
138
+ const state = options.coverage?.get(number);
139
+ if (state && codeless(runs)) {
140
+ const cell = element('span', `src-cov src-cov-mark-${state}`);
141
+ cell.setAttribute('aria-hidden', 'true');
142
+ mark.append(cell);
143
+ }
144
+ else if (state) {
145
+ const count = options.hits?.get(number);
146
+ const cell = element('span', `src-cov src-cov-mark-${state}`, count === undefined || state === 'uncovered' ? '' : hitLabel(count));
147
+ cell.setAttribute('role', 'img');
148
+ cell.setAttribute('aria-label', lineCoverageText(state, count));
149
+ cell.title = lineCoverageText(state, count);
150
+ mark.append(cell);
151
+ }
83
152
  const anchor = element('a', 'src-number', String(number));
84
153
  anchor.href = `#L${number}`;
85
154
  anchor.addEventListener('click', event => {
@@ -88,7 +157,7 @@ export function renderSource(container, text, options) {
88
157
  options.choose(number);
89
158
  });
90
159
  const content = element('code', 'src-code');
91
- content.append(...highlight(line));
160
+ content.append(...runs.map(([kind, value]) => kind ? element('span', `tok-${kind}`, value) : document.createTextNode(value)));
92
161
  if (notes.has(number))
93
162
  row.classList.add('src-flagged');
94
163
  row.append(mark, anchor, content);
@@ -299,6 +368,10 @@ export function tokenizer(path) {
299
368
  return runs;
300
369
  };
301
370
  }
371
+ /** A line with no code: blank, or nothing but comment. */
372
+ export function codeless(runs) {
373
+ return runs.every(([kind, value]) => kind === 'c' || !value.trim());
374
+ }
302
375
  function highlighter(path) {
303
376
  const tokenize = tokenizer(path);
304
377
  return line => tokenize(line).map(([kind, value]) => kind ? element('span', `tok-${kind}`, value) : document.createTextNode(value));
@@ -135,6 +135,7 @@ function start({ reports, quality, context, counts, pullReviewCount, branch, met
135
135
  category: params.get('category') ?? undefined,
136
136
  level: params.get('level') ?? undefined,
137
137
  rank: params.get('rank') ?? undefined,
138
+ layer: params.get('layer') ?? undefined,
138
139
  };
139
140
  }
140
141
  function loadPulls() {
@@ -261,6 +262,7 @@ function start({ reports, quality, context, counts, pullReviewCount, branch, met
261
262
  category: current.category,
262
263
  level: current.level,
263
264
  rank: current.rank,
265
+ layer: current.layer,
264
266
  source: path => loadSource(report.sha, path),
265
267
  sourcePage: (path, line) => sourcePage(report.sha, path, line),
266
268
  href: (destination, options) => href({ page: destination, sha: report.sha, ...options }),
@@ -310,7 +312,7 @@ function start({ reports, quality, context, counts, pullReviewCount, branch, met
310
312
  message.hidden = true;
311
313
  render();
312
314
  }
313
- function href({ page, sha, directory, file, view, period, query, group, line, category, level, rank }) {
315
+ function href({ page, sha, directory, file, view, period, query, group, line, category, level, rank, layer }) {
314
316
  const params = new URLSearchParams({ sha });
315
317
  if (directory)
316
318
  params.set('dir', directory);
@@ -332,6 +334,8 @@ function href({ page, sha, directory, file, view, period, query, group, line, ca
332
334
  params.set('level', level);
333
335
  if (rank)
334
336
  params.set('rank', rank);
337
+ if (layer)
338
+ params.set('layer', layer);
335
339
  // Category lists read as written: category=structure,duplication.
336
340
  return `#${page}?${params.toString().replaceAll('%2C', ',')}`;
337
341
  }
@@ -1,4 +1,5 @@
1
1
  import { definitions } from '../../../core/model/measurement.js';
2
+ import { lcovLines } from '../../../core/model/line-coverage.js';
2
3
  import { comparePaths } from '../../../core/model/snapshot.js';
3
4
  import { fileMetrics } from './file-metrics.js';
4
5
  import { inspectionHistory } from './inspection-context.js';
@@ -9,6 +10,7 @@ export function inspectionAsset(report, components, context = inspectionHistory(
9
10
  }
10
11
  export function inspectionDetails(report, components = []) {
11
12
  const metrics = fileMetrics(report);
13
+ const lineCoverage = report.pluginData?.products[lcovLines.id]?.[0]?.value;
12
14
  const profile = profileSettings(report.appliedConfig);
13
15
  const ruleCatalog = report.pluginData?.rules.flatMap(({ plugin, rules }) => rules.map(rule => ({
14
16
  source: plugin, kind: 'check', rule: rule.id, category: rule.category,
@@ -18,6 +20,7 @@ export function inspectionDetails(report, components = []) {
18
20
  })));
19
21
  return { metrics, functions: complexFunctions(report), diagnostics: report.diagnostics, findings: report.findings,
20
22
  components: components.length ? componentFiles(components, metrics) : undefined,
23
+ ...(lcovLines.accepts(lineCoverage) ? { lineCoverage } : {}),
21
24
  ...(profile ? { profile: { ...profile, ...(ruleCatalog?.length ? { ruleCatalog } : {}) } } : {}) };
22
25
  }
23
26
  /** The applied configuration, field by field; whatever is missing or malformed is left out rather than guessed. */
@@ -5,6 +5,7 @@ import schemaV2 from '../../../../resources/report/json/report-v2.schema.json' w
5
5
  import { isRecord } from '../../../core/engine/plugin.js';
6
6
  import { isMetricDescriptor } from '../../../core/engine/manifest.js';
7
7
  import { isFinding } from '../../../core/model/finding.js';
8
+ import { lcovLines } from '../../../core/model/line-coverage.js';
8
9
  import { digest } from '../../../core/model/snapshot.js';
9
10
  import { compactJsonSchema, unpackJson } from '../wire/compact-json.js';
10
11
  import { legacyReportSchema, reportSchema } from '../../../core/model/report.js';
@@ -42,6 +43,9 @@ export function readReport(value) {
42
43
  if (ids.size !== metrics.length || !metrics.every(isMetricDescriptor)
43
44
  || [...measured, ...privateMetrics ?? []].some(id => !ids.has(id)))
44
45
  throw new Error('Invalid report: inconsistent metric catalog');
46
+ const lines = value.pluginData.products[lcovLines.id];
47
+ if (lines && !lcovLines.accepts(lines[0]?.value))
48
+ throw new Error('Invalid report: LCOV line ranges must be sorted and merged');
45
49
  }
46
50
  if (value.scope.parsed > value.scope.files)
47
51
  throw new Error('Invalid report: parsed count exceeds source count');
@@ -3,12 +3,14 @@ import type { FileMetricsReport } from './file-metrics-model.js';
3
3
  import type { InspectionContext } from './inspection-context-model.js';
4
4
  import type { ComplexFunction } from './public-history-model.js';
5
5
  import type { ComponentMetrics } from './component-model.js';
6
+ import type { LineCoverage } from '../../../core/model/line-coverage.js';
6
7
  export interface InspectionDetails {
7
8
  readonly metrics: FileMetricsReport;
8
9
  readonly functions: readonly ComplexFunction[];
9
10
  readonly diagnostics: Report['diagnostics'];
10
11
  readonly findings?: Report['findings'];
11
12
  readonly components?: readonly ComponentMetrics[];
13
+ readonly lineCoverage?: LineCoverage;
12
14
  /**
13
15
  * The colour band limits the profile sets for the metrics with a meaningful scale: four ascending upper bounds
14
16
  * (three for duplication, whose first band is zero). Absent, the viewer uses its defaults.