repometry 0.8.0 → 0.9.0

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.
Files changed (52) hide show
  1. package/README.md +24 -23
  2. package/package.json +1 -1
  3. package/target/main/resources/languages/go/parser.go +25 -5
  4. package/target/main/resources/languages/python/parser.py +12 -1
  5. package/target/main/resources/report/json/config-v1.schema.json +0 -1
  6. package/target/main/resources/report/json/report-v2.schema.json +12 -0
  7. package/target/main/ts/api/gh/github.d.ts +3 -1
  8. package/target/main/ts/api/gh/github.js +39 -54
  9. package/target/main/ts/api/git/changes.d.ts +6 -1
  10. package/target/main/ts/api/git/changes.js +19 -10
  11. package/target/main/ts/api/git/line-changes.d.ts +6 -0
  12. package/target/main/ts/api/git/line-changes.js +57 -0
  13. package/target/main/ts/cli/config.d.ts +2 -1
  14. package/target/main/ts/cli/config.js +12 -5
  15. package/target/main/ts/cli/main.js +33 -38
  16. package/target/main/ts/compose/review.d.ts +24 -13
  17. package/target/main/ts/compose/review.js +44 -32
  18. package/target/main/ts/core/model/changes.d.ts +29 -0
  19. package/target/main/ts/core/model/code-structure.d.ts +2 -0
  20. package/target/main/ts/core/model/code-structure.js +8 -2
  21. package/target/main/ts/core/model/finding.d.ts +6 -0
  22. package/target/main/ts/core/model/finding.js +23 -8
  23. package/target/main/ts/core/model/pull-review.d.ts +52 -30
  24. package/target/main/ts/core/model/pull-review.js +4 -1
  25. package/target/main/ts/core/usecases/review-effect.d.ts +18 -0
  26. package/target/main/ts/core/usecases/review-effect.js +37 -0
  27. package/target/main/ts/core/usecases/review-match.d.ts +14 -0
  28. package/target/main/ts/core/usecases/review-match.js +72 -0
  29. package/target/main/ts/core/usecases/review-position.d.ts +14 -0
  30. package/target/main/ts/core/usecases/review-position.js +53 -0
  31. package/target/main/ts/core/usecases/review-scope.d.ts +21 -0
  32. package/target/main/ts/core/usecases/review-scope.js +41 -0
  33. package/target/main/ts/core/usecases/review.d.ts +32 -21
  34. package/target/main/ts/core/usecases/review.js +89 -114
  35. package/target/main/ts/index.d.ts +4 -3
  36. package/target/main/ts/index.js +1 -1
  37. package/target/main/ts/plugins/duplication/duplication.js +1 -1
  38. package/target/main/ts/plugins/language-js/babel-provider.js +4 -2
  39. package/target/main/ts/plugins/language-js/function-facts.d.ts +3 -3
  40. package/target/main/ts/plugins/language-js/function-facts.js +3 -15
  41. package/target/main/ts/plugins/language-js/qualified-names.d.ts +11 -0
  42. package/target/main/ts/plugins/language-js/qualified-names.js +63 -0
  43. package/target/main/ts/plugins/language-js/structural-observations.d.ts +2 -1
  44. package/target/main/ts/plugins/language-js/structural-observations.js +18 -14
  45. package/target/main/ts/plugins/maintainability/structural-smells.js +3 -2
  46. package/target/main/ts/report/html/app/viewer-chart-bars.js +9 -5
  47. package/target/main/ts/report/json/store/pull-review-store.d.ts +0 -1
  48. package/target/main/ts/report/json/store/pull-review-store.js +2 -20
  49. package/target/main/ts/report/json/wire/pull-review-model.d.ts +49 -2
  50. package/target/main/ts/report/json/wire/pull-review-model.js +2 -0
  51. package/target/main/ts/report/markdown/pull-review.d.ts +5 -0
  52. package/target/main/ts/report/markdown/pull-review.js +122 -0
@@ -0,0 +1,14 @@
1
+ import type { FileLineChange } from '../model/changes.js';
2
+ import type { Finding } from '../model/finding.js';
3
+ /** A base finding and a head finding the diff places at the same lines. */
4
+ export interface PositionMatch {
5
+ readonly base: Finding;
6
+ readonly head: Finding;
7
+ }
8
+ /**
9
+ * Pairs by position, best first: most of a base finding's lines, carried through the diff, land inside a head finding of
10
+ * the same rule. More carried lines win, then the same anchor, then the closer size.
11
+ */
12
+ export declare function positionMatches(base: readonly Finding[], head: readonly Finding[], byBase: ReadonlyMap<string, FileLineChange>, headPath: (path: string) => string | null): PositionMatch[];
13
+ /** Where an unchanged base line sits on the head side; undefined for a changed line or a file without a counterpart. */
14
+ export declare function headLine(file: FileLineChange | undefined, line: number): number | undefined;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Pairs by position, best first: most of a base finding's lines, carried through the diff, land inside a head finding of
3
+ * the same rule. More carried lines win, then the same anchor, then the closer size.
4
+ */
5
+ export function positionMatches(base, head, byBase, headPath) {
6
+ const found = [];
7
+ for (const from of base.filter(located)) {
8
+ const carried = carriedLines(from, byBase.get(from.path));
9
+ const target = headPath(from.path);
10
+ for (const to of head.filter(item => located(item) && item.rule === from.rule && item.path === target)) {
11
+ const overlap = carried.filter(line => line >= to.line && line <= end(to)).length;
12
+ if (overlap * 2 > size(from)) {
13
+ found.push({ base: from, head: to, score: [overlap, Number(from.anchor === to.anchor), -Math.abs(size(from) - size(to))] });
14
+ }
15
+ }
16
+ }
17
+ return found.sort((left, right) => right.score[0] - left.score[0] || right.score[1] - left.score[1] || right.score[2] - left.score[2]);
18
+ }
19
+ /** Where an unchanged base line sits on the head side; undefined for a changed line or a file without a counterpart. */
20
+ export function headLine(file, line) {
21
+ if (file === undefined)
22
+ return line;
23
+ if (file.whole || file.path === null)
24
+ return undefined;
25
+ let offset = 0;
26
+ for (const { base, head } of file.hunks) {
27
+ const last = base.first + base.count - 1;
28
+ if (base.count > 0 && line >= base.first && line <= last)
29
+ return undefined;
30
+ if (base.count > 0 ? last < line : base.first < line)
31
+ offset += head.count - base.count;
32
+ }
33
+ return line + offset;
34
+ }
35
+ function carriedLines(finding, file) {
36
+ const lines = [];
37
+ for (let line = finding.line; line <= end(finding); line++) {
38
+ const moved = headLine(file, line);
39
+ if (moved !== undefined)
40
+ lines.push(moved);
41
+ }
42
+ return lines;
43
+ }
44
+ function located(finding) {
45
+ return finding.path !== undefined && finding.line !== undefined && finding.category !== 'duplication';
46
+ }
47
+ function end(finding) {
48
+ return finding.endLine ?? finding.line;
49
+ }
50
+ function size(finding) {
51
+ return end(finding) - finding.line + 1;
52
+ }
53
+ //# sourceMappingURL=review-position.js.map
@@ -0,0 +1,21 @@
1
+ import type { LineChanges, LineRange } from '../model/changes.js';
2
+ import type { Finding, FindingLocation } from '../model/finding.js';
3
+ /** A side's source text, line by line; undefined past the end of a file or for unreadable content. */
4
+ export interface SourceLines {
5
+ line(path: string, line: number): string | undefined;
6
+ }
7
+ /** One side of a change: its changed lines by path, and its source text. */
8
+ export interface ReviewSide {
9
+ readonly ranges: ReadonlyMap<string, readonly LineRange[] | 'whole'>;
10
+ readonly lines: SourceLines;
11
+ }
12
+ /** The base side's modified and removed lines, or the head side's added and modified ones. */
13
+ export declare function reviewSide(changes: LineChanges, side: 'base' | 'head', lines: SourceLines): ReviewSide;
14
+ /** A finding is in scope when it sits on changed lines; one without a line, or past its file's end, when its file changed. */
15
+ export declare function inScope(finding: Finding, side: ReviewSide): boolean;
16
+ /** A duplicate shows on its first changed copy, with the others as context. Other findings stay where they are. */
17
+ export declare function placed(finding: Finding, side: ReviewSide): {
18
+ finding: Finding;
19
+ context: readonly FindingLocation[];
20
+ };
21
+ export declare function compare(left: string, right: string): number;
@@ -0,0 +1,41 @@
1
+ /** The base side's modified and removed lines, or the head side's added and modified ones. */
2
+ export function reviewSide(changes, side, lines) {
3
+ const ranges = new Map();
4
+ for (const file of changes.files) {
5
+ const path = side === 'head' ? file.path : file.previous;
6
+ if (path !== null)
7
+ ranges.set(path, file.whole ? 'whole' : side === 'head' ? file.added : file.removed);
8
+ }
9
+ return { ranges, lines };
10
+ }
11
+ /** A finding is in scope when it sits on changed lines; one without a line, or past its file's end, when its file changed. */
12
+ export function inScope(finding, side) {
13
+ if (finding.path === undefined)
14
+ return false;
15
+ if (finding.category === 'duplication')
16
+ return locations(finding).some(copy => locationInScope(copy.path, copy.line, copy.endLine, side));
17
+ const fileLevel = finding.line === undefined || side.lines.line(finding.path, finding.line) === undefined;
18
+ return fileLevel ? side.ranges.has(finding.path) : locationInScope(finding.path, finding.line, finding.endLine ?? finding.line, side);
19
+ }
20
+ function locationInScope(path, line, endLine, side) {
21
+ const ranges = side.ranges.get(path);
22
+ return ranges === 'whole' || (ranges?.some(range => range.first <= endLine && range.last >= line) ?? false);
23
+ }
24
+ function locations(finding) {
25
+ const primary = { path: finding.path, line: finding.line, endLine: finding.endLine ?? finding.line };
26
+ return [primary, ...finding.related ?? []];
27
+ }
28
+ /** A duplicate shows on its first changed copy, with the others as context. Other findings stay where they are. */
29
+ export function placed(finding, side) {
30
+ if (finding.category !== 'duplication' || finding.path === undefined || finding.line === undefined)
31
+ return { finding, context: [] };
32
+ const copies = locations(finding).sort((left, right) => compare(left.path, right.path) || left.line - right.line);
33
+ const shown = copies.find(copy => locationInScope(copy.path, copy.line, copy.endLine, side)) ?? copies[0];
34
+ const { related: _related, ...rest } = finding;
35
+ return { finding: { ...rest, path: shown.path, line: shown.line, endLine: shown.endLine },
36
+ context: copies.filter(copy => copy !== shown) };
37
+ }
38
+ export function compare(left, right) {
39
+ return left < right ? -1 : left > right ? 1 : 0;
40
+ }
41
+ //# sourceMappingURL=review-scope.js.map
@@ -1,31 +1,42 @@
1
+ import type { LineChanges } from '../model/changes.js';
1
2
  import type { PullReview } from '../model/pull-review.js';
2
3
  import type { Report } from '../model/report.js';
4
+ import type { SourceLines } from './review-effect.js';
3
5
  import type { DiffCoverageReport } from './diff-coverage.js';
4
6
  export interface ReviewOptions {
5
7
  readonly number?: number;
6
- readonly minimumLines?: number;
7
8
  readonly minimumPercent?: number;
8
- readonly maxCoverageDrop?: number;
9
+ readonly minimumLines?: number;
9
10
  readonly maxNewIssues?: number;
10
11
  }
11
- export interface ReviewPorts {
12
- readHead(id: string): Promise<Report | null>;
13
- readBase(id: string): Promise<Report | null>;
14
- readRevisions(): Promise<{
15
- head: string;
16
- base: string;
17
- mergeBase(): Promise<string>;
18
- }>;
19
- measureChanged?(): Promise<{
20
- report: DiffCoverageReport;
21
- uncovered: PullReview['diff']['uncovered'];
22
- }>;
12
+ export interface ReviewInputs {
13
+ /** The base as requested, such as `origin/main`. */
14
+ readonly requestedBase: string;
15
+ /** The inspection of the merge base. */
16
+ readonly base: Report;
17
+ readonly head: Report;
18
+ readonly changes: LineChanges;
19
+ readonly sources: {
20
+ readonly base: SourceLines;
21
+ readonly head: SourceLines;
22
+ };
23
+ readonly coverage: {
24
+ readonly report: DiffCoverageReport;
25
+ readonly uncovered: readonly {
26
+ readonly path: string;
27
+ readonly lines: readonly number[];
28
+ }[];
29
+ } | null;
30
+ /** The change edits Repometry's settings. */
31
+ readonly settingsChanged: boolean;
23
32
  }
24
- export declare function executeReview(options: ReviewOptions, ports: ReviewPorts): Promise<PullReview>;
25
- type ChangedLines = Pick<DiffCoverageReport, 'generatedAt' | 'requestedBase' | 'base' | 'head' | 'covered' | 'total' | 'percent' | 'files' | 'gaps' | 'decision'> & {
26
- readonly status: PullReview['diff']['status'];
27
- readonly appliedConfig?: DiffCoverageReport['appliedConfig'];
33
+ export declare const coverageDefaults: {
34
+ readonly minimumPercent: 80;
35
+ readonly minimumLines: 20;
28
36
  };
29
- export declare function projectReview(request: ReviewOptions, diff: ChangedLines, uncovered: PullReview['diff']['uncovered'], head: Report | null, base: Report | null): PullReview;
30
- export declare function reviewExitCode(review: PullReview): number;
31
- export {};
37
+ export declare function projectReview(options: ReviewOptions, inputs: ReviewInputs): PullReview;
38
+ /** Throws for options the review can't apply. */
39
+ export declare function checkOptions({ number, maxNewIssues, minimumPercent }: ReviewOptions, coverage: boolean): void;
40
+ /** The verdict and its reason, in one line. */
41
+ export declare function reviewReason({ verdict, unmeasured, issueGate, coverage }: PullReview): string;
42
+ export declare function reviewExitCode(review: PullReview): 0 | 2 | 3;
@@ -1,129 +1,104 @@
1
- import { isDeepStrictEqual } from 'node:util';
2
- import { isRecord } from '../engine/plugin.js';
3
- import { isSensitiveFinding } from '../model/finding.js';
4
1
  import { pullReviewSchema } from '../model/pull-review.js';
5
- import { findingImportMethods } from '../model/scanner-import.js';
6
- import { compareInspections, observeCoverage } from './compare.js';
7
- export async function executeReview(options, ports) {
8
- if (!ports.measureChanged && options.minimumPercent !== undefined)
9
- throw new Error('Minimum diff coverage requires --lcov');
10
- if (ports.measureChanged) {
11
- const { report, uncovered } = await ports.measureChanged();
12
- const [head, base] = await Promise.all([ports.readHead(report.head), ports.readBase(report.requestedBase)]);
13
- return projectReview(options, report, uncovered, head, base);
14
- }
15
- const revisions = await ports.readRevisions();
16
- const [head, base, mergeBase] = await Promise.all([
17
- ports.readHead(revisions.head), ports.readBase(revisions.base), revisions.mergeBase(),
18
- ]);
19
- return projectReview(options, {
20
- generatedAt: new Date().toISOString(), requestedBase: revisions.base, base: mergeBase, head: revisions.head,
21
- status: 'unavailable', covered: 0, total: 0, percent: null, files: [], gaps: [], decision: null,
22
- }, [], head, base);
2
+ import { classifyIssues, debtEffect } from './review-effect.js';
3
+ export const coverageDefaults = { minimumPercent: 80, minimumLines: 20 };
4
+ const ignoredOperations = new Set(['lcov/import', 'git/churn', 'source/claims']);
5
+ const settingsNote = 'This change edits Repometry settings, which can hide issues from this check.';
6
+ export function projectReview(options, inputs) {
7
+ checkOptions(options, inputs.coverage !== null);
8
+ const { number, maxNewIssues = 0 } = options;
9
+ const issues = classifyIssues(inputs.base.findings ?? [], inputs.head.findings ?? [], inputs.changes, inputs.sources);
10
+ const count = issues.filter(issue => issue.effect === 'new' || issue.effect === 'worsened').length;
11
+ const issueGate = { maximum: maxNewIssues, count, status: count > maxNewIssues ? 'failed' : 'passed' };
12
+ const coverage = changedCoverage(options, inputs.coverage);
13
+ const { unmeasured, notes } = diagnose(inputs);
14
+ const failed = issueGate.status === 'failed' || coverage.gate?.status === 'failed';
15
+ return { schema: pullReviewSchema, number: number ?? null, generatedAt: new Date().toISOString(),
16
+ base: inputs.requestedBase, mergeBase: inputs.base.subject.id, head: inputs.head.subject.id, changedFiles: inputs.changes.files.length,
17
+ verdict: unmeasured.length ? 'unmeasured' : failed ? 'failed' : 'passed',
18
+ issues, debt: debtEffect(issues), coverage, issueGate, unmeasured,
19
+ notes: inputs.settingsChanged ? [...notes, { message: settingsNote }] : notes };
23
20
  }
24
- export function projectReview(request, diff, uncovered, head, base) {
25
- const minimumLines = request.minimumLines ?? 0;
26
- if (request.number !== undefined && (!Number.isSafeInteger(request.number) || request.number < 1)) {
21
+ /** Throws for options the review can't apply. */
22
+ export function checkOptions({ number, maxNewIssues = 0, minimumPercent }, coverage) {
23
+ if (number !== undefined && (!Number.isSafeInteger(number) || number < 1))
27
24
  throw new Error('Pull request number must be a positive integer');
28
- }
29
- if (!Number.isSafeInteger(minimumLines) || minimumLines < 0)
30
- throw new Error('Minimum diff lines must be a non-negative integer');
31
- if (request.maxNewIssues !== undefined && (!Number.isSafeInteger(request.maxNewIssues) || request.maxNewIssues < 0)) {
25
+ if (!Number.isSafeInteger(maxNewIssues) || maxNewIssues < 0)
32
26
  throw new Error('Maximum new issues must be a non-negative integer');
27
+ if (minimumPercent !== undefined && !coverage)
28
+ throw new Error('Minimum changed-line coverage requires --import lcov=PATH or go-cover=PATH');
29
+ }
30
+ /** The verdict and its reason, in one line. */
31
+ export function reviewReason({ verdict, unmeasured, issueGate, coverage }) {
32
+ if (verdict === 'unmeasured') {
33
+ const [first] = unmeasured;
34
+ const more = unmeasured.length > 1 ? `, and ${unmeasured.length - 1} more` : '';
35
+ return `Review not measured: ${first.operation}${first.path === undefined ? '' : ` on ${first.path}`}: ${first.message}${more}.`;
33
36
  }
34
- if (request.maxCoverageDrop !== undefined && (!Number.isFinite(request.maxCoverageDrop) || request.maxCoverageDrop < 0 || request.maxCoverageDrop > 100)) {
35
- throw new Error('Maximum coverage drop must be a number from 0 to 100');
37
+ const reasons = [];
38
+ if (issueGate.status === 'failed') {
39
+ reasons.push(`${issueGate.count} new or worsened ${issueGate.count === 1 ? 'issue' : 'issues'} on the changed lines, ${issueGate.maximum} allowed`);
36
40
  }
37
- if (request.minimumLines !== undefined && diff.decision === null) {
38
- throw new Error('Minimum diff lines requires a minimum diff coverage percentage');
41
+ if (coverage.gate?.status === 'failed') {
42
+ reasons.push(`changed-line coverage ${coverage.percent.toFixed(2)}% is under the ${coverage.gate.minimumPercent}% minimum`);
39
43
  }
40
- const { status, covered, total, percent, files, gaps, decision } = diff;
41
- const config = diff.appliedConfig;
42
- const source = config?.source;
43
- const lcov = config?.lcov;
44
- const excludedPaths = isRecord(source) && Array.isArray(source.excludedPaths)
45
- && source.excludedPaths.every((path) => typeof path === 'string') ? source.excludedPaths : null;
46
- const coverageInputDigest = isRecord(lcov) && typeof lcov.inputDigest === 'string' ? lcov.inputDigest : null;
47
- const gate = decision && {
48
- minimumPercent: decision.minimumPercent,
49
- minimumLines,
50
- status: total < minimumLines && status !== 'partial' ? 'not-applicable' : decision.status,
51
- };
52
- return { schema: pullReviewSchema, number: request.number ?? null, generatedAt: diff.generatedAt,
53
- base: diff.requestedBase, mergeBase: diff.base, head: diff.head,
54
- coverage: coverageImpact(head, base, diff, request.maxCoverageDrop),
55
- diff: { status, covered, total, percent, files, gaps, excludedPaths, coverageInputDigest, uncovered, gate },
56
- findings: findingImpact(head, base, request.maxNewIssues),
57
- };
44
+ return reasons.length ? `Review failed: ${reasons.join('; ')}.` : 'Review passed.';
58
45
  }
59
46
  export function reviewExitCode(review) {
60
- const decisions = [review.diff.gate, review.coverage.gate, review.findings.gate].map(gate => gate?.status);
61
- if (review.diff.status === 'partial' || decisions.includes('indeterminate')
62
- || (review.diff.status === 'unavailable' && review.findings.added === null && review.coverage.delta === null))
63
- return 2;
64
- return decisions.includes('failed') ? 3 : 0;
65
- }
66
- function coverageImpact(head, base, diff, maxDrop) {
67
- const method = head?.appliedConfig.coverage;
68
- const input = diff.appliedConfig?.lcov;
69
- const usesHeadCoverage = isRecord(method) && isRecord(input) && method.inputDigest === input.inputDigest;
70
- const mismatch = head !== null && diff.appliedConfig !== undefined && !usesHeadCoverage;
71
- const comparison = base && head && !mismatch ? compareInspections(base, head).metrics.lineCoverage : null;
72
- const delta = comparison?.delta ?? null;
73
- const gate = maxDrop === undefined ? null : { maxDrop,
74
- status: delta === null ? 'indeterminate' : delta + maxDrop < -Number.EPSILON * 100 ? 'failed' : 'passed' };
75
- return {
76
- base: base ? observeCoverage(base) : null,
77
- head: head && !mismatch ? observeCoverage(head) : null,
78
- delta, reason: comparison ? comparison.reason : mismatch ? 'head-coverage-changed' : 'reports-unavailable', gate,
79
- };
47
+ return review.verdict === 'unmeasured' ? 2 : review.verdict === 'failed' ? 3 : 0;
80
48
  }
81
- function findingImpact(head, base, maximum) {
82
- const { added, reason } = comparableFindings(head, base, false);
83
- const quality = added ?? comparableFindings(head, base, true).added;
84
- const qualityCount = quality ? quality.filter(finding => !isSensitiveFinding(finding.category)).length : null;
85
- return { added, qualityCount, reason, gate: maximum === undefined ? null : { maximum,
86
- status: qualityCount === null ? 'indeterminate' : qualityCount > maximum ? 'failed' : 'passed' } };
87
- }
88
- function comparableFindings(head, base, qualityOnly) {
89
- let reason = null;
90
- let added = null;
91
- if (!head || !base)
92
- reason = 'reports-unavailable';
93
- else if (!head.findings || !base.findings)
94
- reason = 'findings-unavailable';
95
- else if (incompleteAnalysis(head, qualityOnly) || incompleteAnalysis(base, qualityOnly))
96
- reason = 'partial-inspection';
97
- else if (!isDeepStrictEqual(findingMethod(head, qualityOnly), findingMethod(base, qualityOnly)))
98
- reason = 'analysis-changed';
99
- else
100
- added = newFindings(base.findings, head.findings);
101
- return { added, reason };
102
- }
103
- function incompleteAnalysis(report, qualityOnly) {
104
- return report.scope.parsed < report.scope.files || report.diagnostics.some(({ operation }) => operation !== 'lcov/import' && operation !== 'git/churn'
105
- && !(qualityOnly && /^findings\/(security|dependency|secret|infrastructure)\//.test(operation)));
49
+ function changedCoverage(options, input) {
50
+ if (input === null)
51
+ return { imported: false, covered: 0, total: 0, percent: null, uncovered: [], unmapped: [], gate: null };
52
+ const { minimumPercent = coverageDefaults.minimumPercent, minimumLines = coverageDefaults.minimumLines } = options;
53
+ if (!Number.isFinite(minimumPercent) || minimumPercent < 0 || minimumPercent > 100) {
54
+ throw new Error('Minimum changed-line coverage must be a percentage from 0 to 100');
55
+ }
56
+ if (!Number.isSafeInteger(minimumLines) || minimumLines < 0)
57
+ throw new Error('Minimum changed lines must be a non-negative integer');
58
+ const { covered, total, percent, gaps } = input.report;
59
+ const status = total < minimumLines || percent === null ? 'not-applicable'
60
+ : percent + Number.EPSILON * 100 >= minimumPercent ? 'passed' : 'failed';
61
+ return { imported: true, covered, total, percent, uncovered: input.uncovered.flatMap(({ path, lines }) => ranges(path, lines)),
62
+ unmapped: gaps, gate: { minimumPercent, minimumLines, status } };
106
63
  }
107
- function newFindings(base, head) {
108
- const remaining = new Map();
109
- const key = ({ category, path, tool, rule, message }) => JSON.stringify([category, path, tool, rule, message]);
110
- for (const finding of base) {
111
- const id = key(finding);
112
- remaining.set(id, (remaining.get(id) ?? 0) + 1);
64
+ function ranges(path, lines) {
65
+ const merged = [];
66
+ for (const line of [...lines].sort((left, right) => left - right)) {
67
+ const last = merged.at(-1);
68
+ if (last && line <= last.last + 1)
69
+ last.last = Math.max(last.last, line);
70
+ else
71
+ merged.push({ path, first: line, last: line });
113
72
  }
114
- return head.filter(finding => {
115
- const id = key(finding);
116
- const count = remaining.get(id) ?? 0;
117
- if (count === 0)
118
- return true;
119
- remaining.set(id, count - 1);
120
- return false;
121
- });
73
+ return merged;
122
74
  }
123
- function findingMethod(report, qualityOnly) {
124
- const { coverage, findingImports, churn, churnWindow, plugins, operations, ...settings } = report.appliedConfig;
125
- const exclude = (entries, key, value) => Array.isArray(entries) ? entries.filter(entry => !isRecord(entry) || entry[key] !== value) : entries;
126
- const imported = findingImportMethods(findingImports).filter(({ category }) => !qualityOnly || !isSensitiveFinding(category));
127
- return { ...settings, imported, plugins: exclude(plugins, 'id', 'lcov'), operations: exclude(operations, 'key', 'lcov/import') };
75
+ /** Failures on the head only leave the check unmeasured. Failures on both sides, and skipped large files, are notes. */
76
+ function diagnose({ base, head, changes }) {
77
+ const changed = new Set(changes.files.flatMap(file => file.path === null ? [] : [file.path]));
78
+ const failing = (diagnostic) => diagnostic.state === 'failed' || diagnostic.state === 'blocked';
79
+ const failedOnBase = new Set(base.diagnostics.filter(failing).map(({ operation }) => operation));
80
+ const unmeasured = [];
81
+ const notes = [];
82
+ const brokenPaths = new Set(head.diagnostics.filter(item => item.state === 'failed' && item.path !== undefined).map(item => item.path));
83
+ // An operation blocked by a failure on the same file adds nothing to that failure.
84
+ const reported = head.diagnostics.filter(item => item.state !== 'blocked' || item.path === undefined || !brokenPaths.has(item.path));
85
+ for (const diagnostic of reported) {
86
+ const reason = { operation: diagnostic.operation, ...diagnostic.path === undefined ? {} : { path: diagnostic.path },
87
+ message: diagnostic.message };
88
+ if (diagnostic.operation === 'source/claims') {
89
+ if (diagnostic.path !== undefined && changed.has(diagnostic.path))
90
+ notes.push(reason);
91
+ }
92
+ else if (ignoredOperations.has(diagnostic.operation) || !failing(diagnostic)) {
93
+ continue;
94
+ }
95
+ else if (failedOnBase.has(diagnostic.operation) && (diagnostic.path === undefined || !changed.has(diagnostic.path))) {
96
+ notes.push(reason);
97
+ }
98
+ else {
99
+ unmeasured.push(reason);
100
+ }
101
+ }
102
+ return { unmeasured, notes };
128
103
  }
129
104
  //# sourceMappingURL=review.js.map
@@ -9,9 +9,9 @@ export type { AnalysisExecutor, AnalysisInput, InspectionPorts, InspectRequest }
9
9
  export { diffCoverageSchema, measureDiffCoverage } from './compose/diff-coverage.js';
10
10
  export type { DiffCoverageReport, DiffCoverageRequest } from './compose/diff-coverage.js';
11
11
  export type { DiffCoveragePorts, DiffCoverageSource } from './core/usecases/diff-coverage.js';
12
- export { reviewPull, reviewExitCode } from './compose/review.js';
12
+ export { reviewExitCode } from './compose/review.js';
13
13
  export type { ReviewRequest } from './compose/review.js';
14
- export type { ReviewPorts } from './core/usecases/review.js';
14
+ export type { ReviewOptions } from './core/usecases/review.js';
15
15
  export { compareInspections, comparisonSchema } from './core/usecases/compare.js';
16
16
  export { compareInspections as compare } from './core/usecases/compare.js';
17
17
  export { measureDiffCoverage as diffCoverage } from './compose/diff-coverage.js';
@@ -32,5 +32,6 @@ export { coverageGrade, qualitySummary } from './core/model/quality-summary.js';
32
32
  export type { Grade, QualitySummary } from './core/model/quality-summary.js';
33
33
  export { pullReviewSchema } from './core/model/pull-review.js';
34
34
  export { pullReviewsSchema } from './report/json/wire/pull-review-model.js';
35
- export type { PullReview, PullReviews } from './report/json/wire/pull-review-model.js';
35
+ export type { IssueEffect, PullReview, ReviewedIssue, ReviewReason } from './core/model/pull-review.js';
36
+ export type { PullReviews } from './report/json/wire/pull-review-model.js';
36
37
  export type { Subject } from './core/model/snapshot.js';
@@ -3,7 +3,7 @@ export { plan } from './core/engine/plan.js';
3
3
  export { execute } from './core/engine/execute.js';
4
4
  export { analyzeSnapshot, inspect } from './compose/inspect.js';
5
5
  export { diffCoverageSchema, measureDiffCoverage } from './compose/diff-coverage.js';
6
- export { reviewPull, reviewExitCode } from './compose/review.js';
6
+ export { reviewExitCode } from './compose/review.js';
7
7
  export { compareInspections, comparisonSchema } from './core/usecases/compare.js';
8
8
  export { compareInspections as compare } from './core/usecases/compare.js';
9
9
  export { measureDiffCoverage as diffCoverage } from './compose/diff-coverage.js';
@@ -61,7 +61,7 @@ function detectClones(sources) {
61
61
  const effortMinutes = fresh.slice(1).reduce((total, occurrence) => total + occurrence.codeLines, 0) * duplicationSettings.minutesPerRepeatedLine;
62
62
  findings.push({ tool: 'repometry', rule, category: 'duplication', level: 'medium',
63
63
  message: `${identical ? 'Identical' : 'Similar'} code in ${fresh.length} locations`, ...location(first),
64
- related: fresh.slice(1).map(location), effortMinutes });
64
+ related: fresh.slice(1).map(location), effortMinutes, value: fresh.length, anchor: first.similar });
65
65
  }
66
66
  return {
67
67
  findings,
@@ -8,6 +8,7 @@ import { physicalLines, sourceFile, utf8 } from '../../core/model/snapshot.js';
8
8
  import { cloneCandidates } from './clone-candidates.js';
9
9
  import { classifyLines } from './code-lines.js';
10
10
  import { functionFacts } from './function-facts.js';
11
+ import { qualifiedNames } from './qualified-names.js';
11
12
  import { structuralObservations } from './structural-observations.js';
12
13
  import { jsTsExtensions } from './extensions.js';
13
14
  const require = createRequire(import.meta.url);
@@ -43,8 +44,9 @@ export const babelProvider = {
43
44
  const ast = parse(source, { ...parserDefaults, sourceType, plugins });
44
45
  const lines = physicalLines(source);
45
46
  const { code, comments } = classifyLines(source, ast, lines);
46
- return { path: file.path, lines, commentLines: comments, ...functionFacts(ast),
47
- ...structuralObservations(ast), clones: cloneCandidates(file.path, ast, code) };
47
+ const names = qualifiedNames(ast);
48
+ return { path: file.path, lines, commentLines: comments, ...functionFacts(ast, names),
49
+ ...structuralObservations(ast, names), clones: cloneCandidates(file.path, ast, code) };
48
50
  },
49
51
  }],
50
52
  };
@@ -1,9 +1,9 @@
1
- import type { Function as BabelFunction, Node } from '@babel/types';
1
+ import type { Node } from '@babel/types';
2
2
  import type { FunctionComplexity } from '../../core/model/code-structure.js';
3
- export declare function functionFacts(ast: Node): {
3
+ import type { FunctionNaming } from './qualified-names.js';
4
+ export declare function functionFacts(ast: Node, names: ReadonlyMap<Node, FunctionNaming>): {
4
5
  functions: number;
5
6
  cyclomaticFunctions: FunctionComplexity[];
6
7
  functionBodies: [number, number][];
7
8
  };
8
9
  export declare function children(node: Node): Iterable<Node>;
9
- export declare function functionName(node: BabelFunction): string | undefined;
@@ -1,7 +1,7 @@
1
- import { VISITOR_KEYS, isBlockStatement, isFunction, isIdentifier, isStringLiteral } from '@babel/types';
1
+ import { VISITOR_KEYS, isBlockStatement, isFunction } from '@babel/types';
2
2
  const decisionNodes = new Set(['IfStatement', 'ConditionalExpression', 'ForStatement', 'ForInStatement', 'ForOfStatement',
3
3
  'WhileStatement', 'DoWhileStatement', 'CatchClause', 'LogicalExpression']);
4
- export function functionFacts(ast) {
4
+ export function functionFacts(ast, names) {
5
5
  let functions = 0;
6
6
  const bodyRanges = [];
7
7
  walk(ast, node => {
@@ -24,7 +24,7 @@ export function functionFacts(ast) {
24
24
  visit(parameter, undefined);
25
25
  const start = node.loc?.start;
26
26
  cyclomaticFunctions.push({ line: start?.line,
27
- column: start === undefined ? undefined : start.column + 1, name: functionName(node), value: own.value });
27
+ column: start === undefined ? undefined : start.column + 1, name: names.get(node)?.name, value: own.value });
28
28
  return;
29
29
  }
30
30
  if (frame && (decisionNodes.has(node.type) || (node.type === 'SwitchCase' && node.test !== null)))
@@ -71,16 +71,4 @@ function walk(node, visit) {
71
71
  for (const child of children(node))
72
72
  walk(child, visit);
73
73
  }
74
- export function functionName(node) {
75
- if ('id' in node && node.id && isIdentifier(node.id))
76
- return node.id.name;
77
- if ('key' in node) {
78
- if (isIdentifier(node.key))
79
- return node.key.name;
80
- if (isStringLiteral(node.key))
81
- return node.key.value;
82
- if (node.key.type === 'PrivateName')
83
- return `#${node.key.id.name}`;
84
- }
85
- }
86
74
  //# sourceMappingURL=function-facts.js.map
@@ -0,0 +1,11 @@
1
+ import type { Node } from '@babel/types';
2
+ /** A function's qualified name, absent when the function has none, and the anchor its observations carry. */
3
+ export interface FunctionNaming {
4
+ readonly name?: string;
5
+ readonly anchor: string;
6
+ }
7
+ /**
8
+ * Names every function by the classes, object literals and functions around it, joined with dots, as in
9
+ * `commands.review.run`. A function without a name of its own is `(anonymous)` in the anchors of it and its contents.
10
+ */
11
+ export declare function qualifiedNames(ast: Node): ReadonlyMap<Node, FunctionNaming>;
@@ -0,0 +1,63 @@
1
+ import { isClass, isFunction, isIdentifier, isMemberExpression, isObjectExpression, isStringLiteral } from '@babel/types';
2
+ import { children } from './function-facts.js';
3
+ /**
4
+ * Names every function by the classes, object literals and functions around it, joined with dots, as in
5
+ * `commands.review.run`. A function without a name of its own is `(anonymous)` in the anchors of it and its contents.
6
+ */
7
+ export function qualifiedNames(ast) {
8
+ const names = new Map();
9
+ const scope = [];
10
+ visit(ast, undefined);
11
+ return names;
12
+ function visit(node, parent) {
13
+ const own = segment(node, parent);
14
+ const opens = own !== undefined || isFunction(node);
15
+ if (isFunction(node)) {
16
+ const anchor = [...scope, own ?? '(anonymous)'].join('.');
17
+ names.set(node, own === undefined ? { anchor } : { name: anchor, anchor });
18
+ }
19
+ if (opens)
20
+ scope.push(own ?? '(anonymous)');
21
+ for (const child of children(node))
22
+ visit(child, node);
23
+ if (opens)
24
+ scope.pop();
25
+ }
26
+ }
27
+ function segment(node, parent) {
28
+ if (isFunction(node))
29
+ return ('id' in node && node.id ? node.id.name : 'key' in node ? keyName(node.key) : undefined)
30
+ ?? binding(node, parent);
31
+ if (isClass(node))
32
+ return node.id?.name ?? binding(node, parent);
33
+ return isObjectExpression(node) ? binding(node, parent) : undefined;
34
+ }
35
+ /** The name a value takes from the declaration, property or assignment that holds it. */
36
+ function binding(node, parent) {
37
+ switch (parent?.type) {
38
+ case 'VariableDeclarator':
39
+ return parent.init === node && isIdentifier(parent.id) ? parent.id.name : undefined;
40
+ case 'ObjectProperty':
41
+ case 'ClassProperty':
42
+ case 'ClassPrivateProperty':
43
+ return parent.value === node ? keyName(parent.key) : undefined;
44
+ case 'AssignmentExpression': {
45
+ if (parent.right !== node)
46
+ return undefined;
47
+ const target = parent.left;
48
+ if (isIdentifier(target))
49
+ return target.name;
50
+ return isMemberExpression(target) && !target.computed && isIdentifier(target.property) ? target.property.name : undefined;
51
+ }
52
+ default:
53
+ return undefined;
54
+ }
55
+ }
56
+ function keyName(key) {
57
+ if (isIdentifier(key))
58
+ return key.name;
59
+ if (isStringLiteral(key))
60
+ return key.value;
61
+ return key.type === 'PrivateName' ? `#${key.id.name}` : undefined;
62
+ }
63
+ //# sourceMappingURL=qualified-names.js.map
@@ -1,6 +1,7 @@
1
1
  import type { Node } from '@babel/types';
2
2
  import type { FunctionComplexity, StructuralObservation } from '../../core/model/code-structure.js';
3
- export declare function structuralObservations(ast: Node): {
3
+ import type { FunctionNaming } from './qualified-names.js';
4
+ export declare function structuralObservations(ast: Node, names: ReadonlyMap<Node, FunctionNaming>): {
4
5
  observations: StructuralObservation[];
5
6
  cognitiveFunctions: FunctionComplexity[];
6
7
  cognitiveComplexity: number;