repometry 0.6.2 → 0.7.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 (91) hide show
  1. package/package.json +1 -1
  2. package/target/main/resources/config/process-plugins-v1.schema.json +75 -0
  3. package/target/main/resources/report/json/report-v2.schema.json +21 -1
  4. package/target/main/resources/report/json/repository-summary-v1.schema.json +9 -0
  5. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +11 -3
  6. package/target/main/resources/viewer/files.css +6 -0
  7. package/target/main/resources/viewer/index.html +1 -1
  8. package/target/main/resources/viewer/styles.css +1 -0
  9. package/target/main/ts/cli/config.d.ts +1 -0
  10. package/target/main/ts/cli/config.js +3 -2
  11. package/target/main/ts/cli/main.js +37 -19
  12. package/target/main/ts/cli/reporting.js +3 -3
  13. package/target/main/ts/compose/analysis-files.d.ts +1 -0
  14. package/target/main/ts/compose/analysis-files.js +27 -7
  15. package/target/main/ts/compose/analysis-imports.js +2 -1
  16. package/target/main/ts/compose/analysis-report.js +7 -3
  17. package/target/main/ts/compose/analysis-results.d.ts +4 -1
  18. package/target/main/ts/compose/analysis-results.js +3 -0
  19. package/target/main/ts/compose/analysis-sources.js +2 -1
  20. package/target/main/ts/compose/languages.js +4 -1
  21. package/target/main/ts/compose/plugin-list.d.ts +11 -2
  22. package/target/main/ts/compose/plugin-list.js +4 -1
  23. package/target/main/ts/compose/process-plugins.d.ts +2 -0
  24. package/target/main/ts/compose/process-plugins.js +63 -0
  25. package/target/main/ts/compose/structure-measures.d.ts +5 -0
  26. package/target/main/ts/compose/structure-measures.js +57 -0
  27. package/target/main/ts/core/engine/manifest.js +5 -1
  28. package/target/main/ts/core/model/clone-source.js +0 -1
  29. package/target/main/ts/core/model/code-structure.d.ts +14 -9
  30. package/target/main/ts/core/model/code-structure.js +23 -10
  31. package/target/main/ts/core/model/language.d.ts +2 -0
  32. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  33. package/target/main/ts/core/model/quality-summary.d.ts +4 -0
  34. package/target/main/ts/core/model/quality-summary.js +53 -29
  35. package/target/main/ts/core/model/report.d.ts +6 -0
  36. package/target/main/ts/plugin.d.ts +1 -1
  37. package/target/main/ts/plugins/coverage/coverage.d.ts +2 -1
  38. package/target/main/ts/plugins/coverage/coverage.js +40 -30
  39. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -1
  40. package/target/main/ts/plugins/language-js/function-facts.js +0 -1
  41. package/target/main/ts/plugins/language-js/js-security.js +25 -37
  42. package/target/main/ts/plugins/language-js/structural-observations.js +5 -4
  43. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -1
  44. package/target/main/ts/plugins/maintainability/maintainability.js +9 -8
  45. package/target/main/ts/plugins/security/dockerfile.js +45 -37
  46. package/target/main/ts/plugins/structure/structure.js +2 -2
  47. package/target/main/ts/report/html/app/viewer-code-map.js +6 -5
  48. package/target/main/ts/report/html/app/viewer-columns.d.ts +2 -0
  49. package/target/main/ts/report/html/app/viewer-columns.js +9 -4
  50. package/target/main/ts/report/html/app/viewer-data.d.ts +2 -1
  51. package/target/main/ts/report/html/app/viewer-data.js +1 -1
  52. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +5 -9
  53. package/target/main/ts/report/html/app/viewer-file-aside.js +18 -8
  54. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +2 -0
  55. package/target/main/ts/report/html/app/viewer-file-figures.js +6 -1
  56. package/target/main/ts/report/html/app/viewer-hotspots.js +7 -5
  57. package/target/main/ts/report/html/app/viewer-inspection.js +1 -1
  58. package/target/main/ts/report/html/app/viewer-issue-group.js +2 -2
  59. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -2
  60. package/target/main/ts/report/html/app/viewer-languages.js +14 -7
  61. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +4 -4
  62. package/target/main/ts/report/html/app/viewer-line-coverage.js +11 -24
  63. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +1 -1
  64. package/target/main/ts/report/html/app/viewer-map-scale.js +1 -1
  65. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +2 -2
  66. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -3
  67. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -9
  68. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -4
  69. package/target/main/ts/report/html/app/viewer-metrics.d.ts +2 -0
  70. package/target/main/ts/report/html/app/viewer-metrics.js +5 -0
  71. package/target/main/ts/report/html/app/viewer-overview-cards.js +4 -1
  72. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +2 -2
  73. package/target/main/ts/report/html/app/viewer-profile.js +15 -1
  74. package/target/main/ts/report/html/app/viewer-source-view.js +7 -6
  75. package/target/main/ts/report/html/app/viewer-table-cells.js +8 -2
  76. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +2 -0
  77. package/target/main/ts/report/html/app/viewer-table-rows.js +7 -5
  78. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +2 -5
  79. package/target/main/ts/report/html/app/viewer-tokenizer.js +9 -12
  80. package/target/main/ts/report/html/app/viewer-totals.d.ts +6 -0
  81. package/target/main/ts/report/html/app/viewer-totals.js +11 -0
  82. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +1 -1
  83. package/target/main/ts/report/html/app/viewer-trend-data.js +1 -1
  84. package/target/main/ts/report/html/app/viewer-trend-nav.js +3 -2
  85. package/target/main/ts/report/html/app/viewer.js +1 -7
  86. package/target/main/ts/report/json/projections/commit-summary.js +5 -0
  87. package/target/main/ts/report/json/projections/file-metrics.js +20 -4
  88. package/target/main/ts/report/json/projections/inspection-details.js +32 -14
  89. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  90. package/target/main/ts/report/json/projections/metric-values.js +36 -3
  91. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +8 -1
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from '../core/engine/plugin.js';
2
+ export declare function readProcessPlugins(value: unknown): readonly Plugin[];
@@ -0,0 +1,63 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import schema from '../../resources/config/process-plugins-v1.schema.json' with { type: 'json' };
3
+ import { DockerToolRunner } from '../api/process/docker-tool-runner.js';
4
+ import { processPlugin } from '../api/process/plugin.js';
5
+ import { pluginApi } from '../core/engine/plugin.js';
6
+ import { codeStructure, codeStructures } from '../core/model/code-structure.js';
7
+ import { sourceFile, sourceFiles } from '../core/model/snapshot.js';
8
+ import { languageRegistry } from './languages.js';
9
+ import { builtInPlugins } from './plugin-list.js';
10
+ let check;
11
+ export function readProcessPlugins(value) {
12
+ if (value === undefined)
13
+ return [];
14
+ const validate = check ??= new Ajv2020().compile(schema);
15
+ if (!validate(value)) {
16
+ const error = validate.errors?.[0];
17
+ throw new Error(`Config plugins${error?.instancePath ?? ''} ${error?.message ?? 'is invalid'}`);
18
+ }
19
+ const ids = new Set(builtInPlugins.map(({ id }) => id));
20
+ const plugins = value.map((definition, index) => {
21
+ if (ids.has(definition.id))
22
+ throw new Error(`Config plugins/${index}/id duplicates plugin ${definition.id}`);
23
+ ids.add(definition.id);
24
+ return configuredPlugin(definition, index);
25
+ });
26
+ languageRegistry(plugins);
27
+ return plugins;
28
+ }
29
+ function configuredPlugin({ id, version, image, command, scope, claims, limits = {}, tools, settings, providesLanguages }, index) {
30
+ const base = `Config plugins/${index}`;
31
+ if (!command[0]?.trim())
32
+ throw new Error(`${base}/command/0 must name an executable`);
33
+ const languages = providesLanguages.map((language, languageIndex) => {
34
+ const selectors = providesLanguages.length === 1 ? { ...claims, ...language } : language;
35
+ if (!selectors.extensions?.length && !selectors.globs?.length) {
36
+ throw new Error(`${base}/providesLanguages/${languageIndex} must claim an extension or glob`);
37
+ }
38
+ return selectors;
39
+ });
40
+ const effective = effectiveClaims(languages, claims, base);
41
+ const repository = scope === 'repository';
42
+ const output = repository ? codeStructures : codeStructure;
43
+ return processPlugin({ id, version, api: pluginApi, kinds: ['language'], tools, claims: effective, providesLanguages: languages,
44
+ ...(settings === undefined ? {} : { settings }),
45
+ produces: [{ contract: output.id, persistence: 'transient' }],
46
+ operations: [{ id: 'parse', role: 'provider', scope, inputs: repository ? { files: sourceFiles } : { source: sourceFile },
47
+ output, argv: command, timeoutMs: limits.timeoutMs ?? 30_000, maxOutputBytes: limits.maxOutputBytes ?? 8 * 1024 * 1024 }],
48
+ }, new DockerToolRunner(image, { memoryBytes: limits.memoryBytes ?? 512 * 1024 * 1024, pidsLimit: limits.pidsLimit ?? 128 }));
49
+ }
50
+ function effectiveClaims(languages, declared, base) {
51
+ const selectors = {};
52
+ for (const key of ['extensions', 'globs']) {
53
+ const union = new Set(languages.flatMap(language => language[key] ?? []));
54
+ const expected = declared?.[key];
55
+ if (expected !== undefined && (expected.length !== union.size || expected.some(value => !union.has(value)))) {
56
+ throw new Error(`${base}/claims/${key} must match the claims of its languages`);
57
+ }
58
+ if (union.size)
59
+ selectors[key] = [...union];
60
+ }
61
+ return selectors;
62
+ }
63
+ //# sourceMappingURL=process-plugins.js.map
@@ -0,0 +1,5 @@
1
+ import type { Operation } from '../core/engine/plugin.js';
2
+ import type { CodeStructure, StructureMeasure } from '../core/model/code-structure.js';
3
+ import type { ProvidedLanguage } from '../core/model/language.js';
4
+ export declare function restrictStructureMeasures(operation: Operation, declared: readonly ProvidedLanguage[], language: (path: string) => string | undefined): Operation;
5
+ export declare function unmeasuredStructure(facts: CodeStructure): readonly StructureMeasure[];
@@ -0,0 +1,57 @@
1
+ import { codeStructure, codeStructures, structureCodeLines } from '../core/model/code-structure.js';
2
+ import { digest } from '../core/model/snapshot.js';
3
+ export function restrictStructureMeasures(operation, declared, language) {
4
+ const measured = new Map(declared.flatMap(entry => entry.measures === undefined ? [] : [[entry.id, entry.measures]]));
5
+ if (!measured.size)
6
+ return operation;
7
+ const implementation = digest(JSON.stringify([operation.implementation ?? operation.execute.toString(), [...measured]]));
8
+ return { ...operation, implementation, async execute(inputs) {
9
+ const value = await operation.execute(inputs);
10
+ if (operation.scope === 'repository')
11
+ return codeStructures.accepts(value) ? value.map(project) : value;
12
+ return codeStructure.accepts(value) ? project(value) : value;
13
+ } };
14
+ function project(facts) {
15
+ const id = language(facts.path);
16
+ const measures = id === undefined ? undefined : measured.get(id);
17
+ return measures === undefined ? facts : selectMeasures(facts, measures);
18
+ }
19
+ }
20
+ function selectMeasures(facts, measures) {
21
+ const selected = { ...facts };
22
+ if (!measures.includes('functions'))
23
+ delete selected.functions;
24
+ if (!measures.includes('cyclomaticComplexity'))
25
+ delete selected.cyclomaticFunctions;
26
+ if (!measures.includes('cognitiveComplexity')) {
27
+ delete selected.cognitiveComplexity;
28
+ delete selected.cognitiveFunctions;
29
+ }
30
+ if (!measures.includes('classes'))
31
+ delete selected.classes;
32
+ if (!measures.includes('commentLines'))
33
+ delete selected.commentLines;
34
+ if (measures.includes('codeLines'))
35
+ selected.codeLines = structureCodeLines(facts);
36
+ else
37
+ delete selected.codeLines;
38
+ if (!measures.includes('duplication'))
39
+ delete selected.clones;
40
+ if (!measures.includes('structuralRules'))
41
+ delete selected.observations;
42
+ return selected;
43
+ }
44
+ export function unmeasuredStructure(facts) {
45
+ const values = {
46
+ functions: facts.functions,
47
+ cyclomaticComplexity: facts.cyclomaticFunctions,
48
+ cognitiveComplexity: facts.cognitiveComplexity,
49
+ classes: facts.classes,
50
+ commentLines: facts.commentLines,
51
+ codeLines: structureCodeLines(facts),
52
+ duplication: facts.clones,
53
+ structuralRules: facts.observations,
54
+ };
55
+ return Object.keys(values).filter(key => values[key] === undefined);
56
+ }
57
+ //# sourceMappingURL=structure-measures.js.map
@@ -1,5 +1,6 @@
1
1
  import { isRecord } from './plugin.js';
2
2
  import { definitions } from '../model/measurement.js';
3
+ import { structureMeasures } from '../model/code-structure.js';
3
4
  import { isLanguageDisplay } from '../model/language.js';
4
5
  const kinds = new Set(['language', 'analysis', 'coverage', 'security', 'import', 'source']);
5
6
  const persistence = new Set(['report', 'cache', 'transient']);
@@ -86,11 +87,14 @@ function validLanguages(values) {
86
87
  for (const value of values) {
87
88
  if (!isRecord(value) || !isLanguageDisplay(value) || ids.has(value.id))
88
89
  return false;
89
- const { extensions, globs } = value;
90
+ const { extensions, globs, measures } = value;
90
91
  if (extensions !== undefined && (!strings(extensions) || !extensions.every(isExtension)))
91
92
  return false;
92
93
  if (globs !== undefined && !strings(globs))
93
94
  return false;
95
+ if (measures !== undefined && (!strings(measures) || measures.some(measure => !structureMeasures.includes(measure))
96
+ || measures.includes('duplication') && !measures.includes('codeLines')))
97
+ return false;
94
98
  if (!(Array.isArray(extensions) && extensions.length || Array.isArray(globs) && globs.length))
95
99
  return false;
96
100
  ids.add(value.id);
@@ -13,4 +13,3 @@ export function isCloneSource(value) {
13
13
  && value.codeLines.every((line, index, lines) => isCount(line) && line > (lines[index - 1] ?? 0))
14
14
  && Array.isArray(value.candidates) && value.candidates.every(isCandidate);
15
15
  }
16
- //# sourceMappingURL=clone-source.js.map
@@ -3,8 +3,11 @@ import type { CloneSource } from './clone-source.js';
3
3
  import type { SourceLineRange } from './source.js';
4
4
  export declare const structuralCheckIds: readonly ['function-parameters', 'return-statements', 'boolean-logic', 'nested-control-flow', 'function-complexity', 'file-complexity'];
5
5
  export type StructuralCheck = typeof structuralCheckIds[number];
6
+ export declare const structureMeasures: readonly ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'classes', 'commentLines', 'codeLines', 'duplication', 'structuralRules'];
7
+ export type StructureMeasure = typeof structureMeasures[number];
6
8
  export interface FunctionComplexity {
7
- readonly name: string;
9
+ /** Functions without a name omit this field. Reports display them as (anonymous). */
10
+ readonly name?: string;
8
11
  readonly line?: number;
9
12
  readonly column?: number;
10
13
  readonly value: number;
@@ -19,17 +22,19 @@ export interface StructuralObservation {
19
22
  export interface CodeStructure {
20
23
  readonly path: string;
21
24
  readonly lines: number;
22
- readonly functions: number;
23
- readonly classes: number;
24
- readonly cognitiveComplexity: number;
25
- readonly commentLines: number;
26
- readonly cyclomaticFunctions: readonly FunctionComplexity[];
27
- readonly cognitiveFunctions: readonly FunctionComplexity[];
25
+ readonly functions?: number;
26
+ readonly classes?: number;
27
+ readonly cognitiveComplexity?: number;
28
+ readonly commentLines?: number;
29
+ readonly cyclomaticFunctions?: readonly FunctionComplexity[];
30
+ readonly cognitiveFunctions?: readonly FunctionComplexity[];
28
31
  /** Sorted, merged lines containing code inside a function body. An empty list means the provider found none. */
29
32
  readonly functionBodies?: readonly SourceLineRange[];
30
- readonly observations: readonly StructuralObservation[];
31
- readonly clones: CloneSource;
33
+ readonly observations?: readonly StructuralObservation[];
34
+ readonly codeLines?: readonly number[];
35
+ readonly clones?: CloneSource;
32
36
  }
33
37
  export declare const codeStructure: DataContract<CodeStructure>;
38
+ export declare function structureCodeLines(value: CodeStructure): readonly number[] | undefined;
34
39
  /** A repository provider returns at most one structure per input path. */
35
40
  export declare const codeStructures: DataContract<readonly CodeStructure[]>;
@@ -5,6 +5,8 @@ export const structuralCheckIds = [
5
5
  'function-parameters', 'return-statements', 'boolean-logic', 'nested-control-flow',
6
6
  'function-complexity', 'file-complexity',
7
7
  ];
8
+ export const structureMeasures = ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'classes',
9
+ 'commentLines', 'codeLines', 'duplication', 'structuralRules'];
8
10
  const checkIds = new Set(structuralCheckIds);
9
11
  function isCount(value) {
10
12
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
@@ -13,7 +15,7 @@ function isPosition(value) {
13
15
  return value === undefined || (isCount(value) && value > 0);
14
16
  }
15
17
  function isFunctionComplexity(value) {
16
- return isRecord(value) && typeof value.name === 'string' && isCount(value.value)
18
+ return isRecord(value) && (value.name === undefined || typeof value.name === 'string') && isCount(value.value)
17
19
  && isPosition(value.line) && isPosition(value.column);
18
20
  }
19
21
  function isObservation(value) {
@@ -23,19 +25,30 @@ function isObservation(value) {
23
25
  export const codeStructure = {
24
26
  id: 'repometry.code-structure/v1',
25
27
  accepts: (value) => isRecord(value)
26
- && typeof value.path === 'string' && isCount(value.lines) && isCount(value.functions) && isCount(value.classes)
27
- && isCount(value.cognitiveComplexity) && isCount(value.commentLines)
28
- && Array.isArray(value.cyclomaticFunctions) && value.cyclomaticFunctions.every(isFunctionComplexity)
29
- && Array.isArray(value.cognitiveFunctions) && value.cognitiveFunctions.every(isFunctionComplexity)
30
- && (value.functionBodies === undefined
31
- || isMergedLineRanges(value.functionBodies) && (value.functionBodies.at(-1)?.[1] ?? 0) <= value.lines)
32
- && Array.isArray(value.observations) && value.observations.every(isObservation)
33
- && isCloneSource(value.clones) && value.clones.path === value.path,
28
+ && typeof value.path === 'string' && isCount(value.lines)
29
+ && [value.functions, value.classes, value.cognitiveComplexity, value.commentLines].every(count => count === undefined || isCount(count))
30
+ && (value.cyclomaticFunctions === undefined || Array.isArray(value.cyclomaticFunctions) && value.cyclomaticFunctions.every(isFunctionComplexity))
31
+ && (value.cognitiveFunctions === undefined || Array.isArray(value.cognitiveFunctions) && value.cognitiveFunctions.every(isFunctionComplexity))
32
+ && (value.functionBodies === undefined || isMergedLineRanges(value.functionBodies) && (value.functionBodies.at(-1)?.[1] ?? 0) <= value.lines)
33
+ && (value.observations === undefined || Array.isArray(value.observations) && value.observations.every(isObservation))
34
+ && (value.codeLines === undefined || Array.isArray(value.codeLines) && isCodeLines(value.codeLines, value.lines))
35
+ && (value.clones === undefined || isCloneSource(value.clones) && value.clones.path === value.path),
34
36
  };
37
+ function isCodeLines(lines, lastLine) {
38
+ let previous = 0;
39
+ for (const line of lines) {
40
+ if (!isCount(line) || line <= previous || line > lastLine)
41
+ return false;
42
+ previous = line;
43
+ }
44
+ return true;
45
+ }
46
+ export function structureCodeLines(value) {
47
+ return value.codeLines ?? value.clones?.codeLines;
48
+ }
35
49
  /** A repository provider returns at most one structure per input path. */
36
50
  export const codeStructures = {
37
51
  id: 'repometry.code-structures/v1',
38
52
  accepts: (value) => Array.isArray(value) && value.every(codeStructure.accepts)
39
53
  && new Set(value.map(({ path }) => path)).size === value.length,
40
54
  };
41
- //# sourceMappingURL=code-structure.js.map
@@ -1,3 +1,4 @@
1
+ import type { StructureMeasure } from './code-structure.js';
1
2
  export interface LanguageDisplay {
2
3
  readonly id: string;
3
4
  readonly label: string;
@@ -10,5 +11,6 @@ export interface LanguageLookup {
10
11
  export interface ProvidedLanguage extends LanguageDisplay {
11
12
  readonly extensions?: readonly string[];
12
13
  readonly globs?: readonly string[];
14
+ readonly measures?: readonly StructureMeasure[];
13
15
  }
14
16
  export declare function isLanguageDisplay(value: unknown): value is LanguageDisplay;
@@ -1,3 +1,4 @@
1
+ import type { StructureMeasure } from './code-structure.js';
1
2
  import type { MetricDescriptor, PluginConfigSchema, RuleDescriptor } from '../engine/plugin.js';
2
3
  import type { InventoryFile } from './source.js';
3
4
  import type { LanguageDisplay } from './language.js';
@@ -26,5 +27,6 @@ export interface PluginData {
26
27
  readonly language: string;
27
28
  readonly analysed: boolean;
28
29
  readonly provider?: string;
30
+ readonly unmeasured?: readonly StructureMeasure[];
29
31
  })[];
30
32
  }
@@ -15,6 +15,10 @@ export interface QualitySummary {
15
15
  readonly effortMinutes: number;
16
16
  readonly debtRatio: number | null;
17
17
  readonly grade: Grade | null;
18
+ readonly gradeCoverage?: {
19
+ readonly measuredFiles: number;
20
+ readonly totalFiles: number;
21
+ };
18
22
  } | null;
19
23
  }
20
24
  interface DebtModel {
@@ -2,39 +2,63 @@ import { isRecord } from './plugin-data.js';
2
2
  import { canonicalMetricId, definitions } from './measurement.js';
3
3
  export const debtModel = { name: 'basic-cocomo-organic', scale: 2.4, exponent: 1.05, minutesPerPersonMonth: 9600 };
4
4
  export function qualitySummary(report) {
5
- const totals = new Map();
6
- let codeMeasuredFiles = 0;
7
- let duplicationMeasuredFiles = 0;
8
- for (const item of report.measurements) {
9
- if (item.target !== 'file' || item.value === null || !Number.isSafeInteger(item.value) || item.value < 0)
10
- continue;
11
- const id = canonicalMetricId(item.definition);
12
- if (id === definitions.codeLines)
13
- codeMeasuredFiles++;
14
- if (id === definitions.duplicatedLines)
15
- duplicationMeasuredFiles++;
16
- totals.set(id, (totals.get(id) ?? 0) + item.value);
17
- }
18
- const codeLines = totals.get(definitions.codeLines) ?? null;
19
- const duplicatedLines = totals.get(definitions.duplicatedLines) ?? null;
20
- const smells = report.findings?.filter(finding => finding.category === 'duplication' || finding.category === 'structure');
21
- const effortMinutes = smells?.reduce((sum, finding) => sum + (finding.effortMinutes ?? 0), 0) ?? 0;
22
- const hasCompleteData = codeMeasuredFiles === report.scope.files && duplicationMeasuredFiles === report.scope.files;
23
- const savedConfig = report.appliedConfig.maintainability;
24
- const model = isRecord(savedConfig) ? readDebtModel(savedConfig.debtModel) : null;
25
- const debtRatio = !hasCompleteData || codeLines === null || model === null || smells?.some(finding => finding.effortMinutes === undefined)
26
- ? null : technicalDebtRatio(effortMinutes, codeLines, model);
5
+ const files = collectFileMeasures(report);
6
+ const totalFiles = report.scope.files;
7
+ const completeTotal = (id) => totalMeasured(files.get(id), totalFiles);
8
+ const codeLines = completeTotal(definitions.codeLines);
9
+ const duplicatedLines = completeTotal(definitions.duplicatedLines);
27
10
  return {
28
11
  codeLines,
29
- comments: totals.get(definitions.comments) ?? null,
30
- classes: totals.get(definitions.classes) ?? null,
31
- cognitiveComplexity: totals.get(definitions.cognitiveComplexity) ?? null,
32
- duplication: duplicatedLines === null || codeLines === null || codeMeasuredFiles !== duplicationMeasuredFiles
33
- ? null : { duplicatedLines, codeLines, ratio: codeLines === 0 || duplicatedLines > codeLines ? null : duplicatedLines / codeLines },
34
- maintainability: smells === undefined || codeLines === null ? null : { smells: smells.length, effortMinutes, debtRatio,
35
- grade: debtRatio === null ? null : maintainabilityGrade(debtRatio) },
12
+ comments: completeTotal(definitions.comments),
13
+ classes: completeTotal(definitions.classes),
14
+ cognitiveComplexity: completeTotal(definitions.cognitiveComplexity),
15
+ duplication: duplicatedLines === null || codeLines === null ? null
16
+ : { duplicatedLines, codeLines, ratio: codeLines === 0 || duplicatedLines > codeLines ? null : duplicatedLines / codeLines },
17
+ maintainability: gradeMeasuredFiles(report, files.get(definitions.codeLines), files.get(definitions.duplicatedLines)),
36
18
  };
37
19
  }
20
+ function collectFileMeasures(report) {
21
+ const files = new Map();
22
+ for (const { target, path, definition, value } of report.measurements) {
23
+ if (target !== 'file' || path === undefined || value === null || !Number.isSafeInteger(value) || value < 0)
24
+ continue;
25
+ const id = canonicalMetricId(definition);
26
+ let measured = files.get(id);
27
+ if (!measured)
28
+ files.set(id, measured = new Map());
29
+ measured.set(path, (measured.get(path) ?? 0) + value);
30
+ }
31
+ return files;
32
+ }
33
+ function totalMeasured(values, expected) {
34
+ if (values?.size !== expected)
35
+ return null;
36
+ let total = 0;
37
+ for (const value of values.values())
38
+ total += value;
39
+ return total;
40
+ }
41
+ function gradeMeasuredFiles(report, code, duplication) {
42
+ if (report.findings === undefined || code === undefined)
43
+ return null;
44
+ const skipped = new Set(report.ruleSkips?.filter(({ plugin }) => plugin === 'maintainability' || plugin === 'duplication')
45
+ .map(({ path }) => path));
46
+ const measured = new Map([...code].filter(([path]) => duplication?.has(path) && !skipped.has(path)));
47
+ const smells = report.findings.filter(finding => finding.category === 'duplication' || finding.category === 'structure');
48
+ const totalFiles = report.scope.files;
49
+ const complete = measured.size === totalFiles;
50
+ const eligible = complete ? smells : smells.filter(({ path }) => path !== undefined && measured.has(path));
51
+ const effortMinutes = eligible.reduce((sum, finding) => sum + (finding.effortMinutes ?? 0), 0);
52
+ const config = report.appliedConfig.maintainability;
53
+ const model = isRecord(config) ? readDebtModel(config.debtModel) : null;
54
+ const sized = totalMeasured(measured, measured.size);
55
+ const canGrade = complete || (report.scope.parsed === totalFiles
56
+ && measured.size + skipped.size === totalFiles);
57
+ const debtRatio = !canGrade || !sized || model === null || eligible.some(finding => finding.effortMinutes === undefined)
58
+ ? null : technicalDebtRatio(effortMinutes, sized, model);
59
+ return { smells: smells.length, effortMinutes, debtRatio, grade: debtRatio === null ? null : maintainabilityGrade(debtRatio),
60
+ ...(!complete && debtRatio !== null ? { gradeCoverage: { measuredFiles: measured.size, totalFiles } } : {}) };
61
+ }
38
62
  export function technicalDebtRatio(effortMinutes, codeLines, model = debtModel) {
39
63
  if (codeLines <= 0)
40
64
  return null;
@@ -33,6 +33,12 @@ export interface Report {
33
33
  readonly measurements: readonly Measurement[];
34
34
  readonly diagnostics: readonly Diagnostic[];
35
35
  readonly findings?: readonly Finding[];
36
+ readonly ruleSkips?: readonly {
37
+ readonly path: string;
38
+ readonly plugin: string;
39
+ readonly rules: readonly string[];
40
+ readonly reason: 'unmeasured';
41
+ }[];
36
42
  readonly ignoredFindings?: readonly IgnoredFinding[];
37
43
  readonly pluginData?: PluginData;
38
44
  }
@@ -3,7 +3,7 @@ export type { DataContract, InspectionInputs, Operation, Plugin, PluginConfigSch
3
3
  export type { FileClaims, MetricDescriptor, MetricScope, PluginKind, ProductDeclaration } from './core/engine/plugin.js';
4
4
  export type { OperationCache, OperationCacheOptions } from './core/engine/operation-cache.js';
5
5
  export { codeStructure, codeStructures } from './core/model/code-structure.js';
6
- export type { CodeStructure, FunctionComplexity, StructuralCheck, StructuralObservation } from './core/model/code-structure.js';
6
+ export type { CodeStructure, FunctionComplexity, StructureMeasure, StructuralCheck, StructuralObservation } from './core/model/code-structure.js';
7
7
  export type { LanguageDisplay, ProvidedLanguage } from './core/model/language.js';
8
8
  export type { Candidate, CloneSource } from './core/model/clone-source.js';
9
9
  export { sourceFile, sourceFiles } from './core/model/snapshot.js';
@@ -7,6 +7,7 @@ export interface CoverageInput {
7
7
  readonly root: string;
8
8
  readonly sourceLines: ReadonlyMap<string, number>;
9
9
  readonly codeLines?: ReadonlyMap<string, ReadonlySet<number>>;
10
+ readonly unclassified?: ReadonlySet<string>;
10
11
  readonly functionBodies?: ReadonlyMap<string, readonly SourceLineRange[]>;
11
12
  readonly excludes?: (path: string) => boolean;
12
13
  }
@@ -21,7 +22,7 @@ interface CoverageResult {
21
22
  export declare const lcovInput: DataContract<CoverageInput>;
22
23
  export declare const coverageResult: DataContract<CoverageResult>;
23
24
  export declare const coverage: Plugin;
24
- export declare function mapCoverage({ text, root, sourceLines, codeLines, excludes }: CoverageInput): {
25
+ export declare function mapCoverage({ text, root, sourceLines, codeLines, unclassified, excludes }: CoverageInput): {
25
26
  files: Map<string, Map<number, number>>;
26
27
  branches: Map<string, Map<string, number>>;
27
28
  functions: Map<string, Map<string, number>>;
@@ -9,6 +9,7 @@ export const lcovInput = {
9
9
  accepts: (value) => isRecord(value) && typeof value.text === 'string'
10
10
  && typeof value.root === 'string' && value.sourceLines instanceof Map
11
11
  && (value.codeLines === undefined || value.codeLines instanceof Map)
12
+ && (value.unclassified === undefined || value.unclassified instanceof Set)
12
13
  && (value.functionBodies === undefined || value.functionBodies instanceof Map)
13
14
  && (value.excludes === undefined || typeof value.excludes === 'function'),
14
15
  };
@@ -56,7 +57,7 @@ export const coverage = {
56
57
  execute: inputs => inputs.read('coverage', coverageResult).lineCoverage,
57
58
  }],
58
59
  };
59
- export function mapCoverage({ text, root, sourceLines, codeLines, excludes }) {
60
+ export function mapCoverage({ text, root, sourceLines, codeLines, unclassified, excludes }) {
60
61
  const files = new Map();
61
62
  // Branches by line, block and branch. Functions by name and its occurrence in the record: tools such as c8 repeat a
62
63
  // name for different functions and list FNDA in FN order.
@@ -86,29 +87,19 @@ export function mapCoverage({ text, root, sourceLines, codeLines, excludes }) {
86
87
  continue;
87
88
  if (!sourceLines.has(active))
88
89
  gaps.set(active, 'LCOV source is outside the inspected file set');
89
- else if (codeLines && !codeLines.has(active))
90
+ else if (codeLines && !codeLines.has(active) && !unclassified?.has(active)) {
90
91
  gaps.set(active, 'LCOV source has no classified code lines');
92
+ }
91
93
  else
92
94
  fileRecords(files, active);
93
95
  }
94
96
  else if (line.startsWith('DA:')) {
95
97
  if (active === undefined)
96
98
  throw new Error(`LCOV line data outside a source record at line ${index + 1}`);
97
- if (ignored)
98
- continue;
99
- const match = /^DA:([1-9]\d*),(\d+)(?:,[^,]+)?$/.exec(line);
100
- const number = Number(match?.[1]);
101
- const hits = Number(match?.[2]);
102
- if (!Number.isSafeInteger(number) || !Number.isSafeInteger(hits))
103
- throw new Error(`Invalid LCOV line data at line ${index + 1}`);
104
- const file = files.get(active);
105
- const limit = sourceLines.get(active);
106
- if (limit !== undefined && number > limit)
107
- gaps.set(active, 'LCOV refers to a line outside the inspected source');
108
- else if (file && (!codeLines || codeLines.get(active)?.has(number)))
109
- addHits(file, number, hits, index + 1);
99
+ if (!ignored)
100
+ readLine(active, line, index + 1);
110
101
  }
111
- else if (line.startsWith('BRDA:') || line.startsWith('FN:') || line.startsWith('FNDA:')) {
102
+ else if (/^(?:BRDA|FN|FNDA):/.test(line)) {
112
103
  if (active === undefined)
113
104
  throw new Error(`LCOV data outside a source record at line ${index + 1}`);
114
105
  if (ignored || !files.has(active))
@@ -125,21 +116,38 @@ export function mapCoverage({ text, root, sourceLines, codeLines, excludes }) {
125
116
  throw new Error('Unterminated LCOV source record');
126
117
  if (!sawSource && text.trim() !== '')
127
118
  throw new Error('LCOV contains no source records');
128
- // The declaration map can now hold the hit totals. Keep the declared lines for the gutter.
129
- const functionCalls = new Map();
130
- for (const [path, declarations] of functions) {
131
- const hits = called.get(path);
132
- const counts = [];
133
- for (const [key, first] of declarations) {
134
- const count = hits?.get(key);
135
- declarations.set(key, count ?? 0);
136
- if (count !== undefined && first <= sourceLines.get(path))
137
- counts.push([first, count]);
119
+ return { files, branches, functions, functionCalls: countFunctionCalls(), gaps };
120
+ function countFunctionCalls() {
121
+ // The declaration map can now hold hit totals. Keep the declared lines for the gutter.
122
+ const functionCalls = new Map();
123
+ for (const [path, declarations] of functions) {
124
+ const hits = called.get(path);
125
+ const counts = [];
126
+ for (const [key, first] of declarations) {
127
+ const count = hits?.get(key);
128
+ declarations.set(key, count ?? 0);
129
+ if (count !== undefined && first <= sourceLines.get(path))
130
+ counts.push([first, count]);
131
+ }
132
+ if (counts.length)
133
+ functionCalls.set(path, counts.sort(([left], [right]) => left - right));
138
134
  }
139
- if (counts.length)
140
- functionCalls.set(path, counts.sort(([left], [right]) => left - right));
135
+ return functionCalls;
136
+ }
137
+ function readLine(path, line, record) {
138
+ const match = /^DA:([1-9]\d*),(\d+)(?:,[^,]+)?$/.exec(line);
139
+ const number = Number(match?.[1]);
140
+ const hits = Number(match?.[2]);
141
+ if (!Number.isSafeInteger(number) || !Number.isSafeInteger(hits))
142
+ throw new Error(`Invalid LCOV line data at line ${record}`);
143
+ const file = files.get(path);
144
+ const limit = sourceLines.get(path);
145
+ const classified = codeLines?.get(path);
146
+ if (limit !== undefined && number > limit)
147
+ gaps.set(path, 'LCOV refers to a line outside the inspected source');
148
+ else if (file && (!classified || classified.has(number)))
149
+ addHits(file, number, hits, record);
141
150
  }
142
- return { files, branches, functions, functionCalls, gaps };
143
151
  function readDetails(path, line, record) {
144
152
  const branch = /^BRDA:([1-9]\d*),([^,]+),([^,]+),(\d+|-)$/.exec(line);
145
153
  if (branch) {
@@ -184,7 +192,9 @@ function importCoverage(input) {
184
192
  const hitLines = [], missedLines = [];
185
193
  for (const [line, hit] of hits)
186
194
  (hit ? hitLines : missedLines).push(line);
187
- const partialHits = partiallyCoveredLines(branches.get(path), input.sourceLines.get(path), input.codeLines?.get(path));
195
+ const lastLine = input.sourceLines.get(path);
196
+ const classified = input.codeLines?.get(path);
197
+ const partialHits = partiallyCoveredLines(branches.get(path), lastLine, classified);
188
198
  const partial = mergedRanges([...partialHits.keys()]);
189
199
  const calls = functionCalls.get(path);
190
200
  const bodies = input.functionBodies?.get(path);
@@ -6,4 +6,4 @@ export declare function functionFacts(ast: Node): {
6
6
  functionBodies: [number, number][];
7
7
  };
8
8
  export declare function children(node: Node): Iterable<Node>;
9
- export declare function functionName(node: BabelFunction): string;
9
+ export declare function functionName(node: BabelFunction): string | undefined;
@@ -82,6 +82,5 @@ export function functionName(node) {
82
82
  if (node.key.type === 'PrivateName')
83
83
  return `#${node.key.id.name}`;
84
84
  }
85
- return '(anonymous)';
86
85
  }
87
86
  //# sourceMappingURL=function-facts.js.map