repometry 0.9.0 → 0.10.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.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/target/main/resources/report/json/config-v1.schema.json +84 -2
  4. package/target/main/ts/api/cache/root.d.ts +3 -0
  5. package/target/main/ts/api/cache/root.js +21 -0
  6. package/target/main/ts/api/git/blob-batch.js +2 -1
  7. package/target/main/ts/api/git/blob-history.d.ts +20 -0
  8. package/target/main/ts/api/git/blob-history.js +54 -0
  9. package/target/main/ts/api/git/git-churn.js +38 -37
  10. package/target/main/ts/api/git/git-executable.d.ts +1 -0
  11. package/target/main/ts/api/git/git-executable.js +31 -0
  12. package/target/main/ts/api/git/git.d.ts +8 -1
  13. package/target/main/ts/api/git/git.js +58 -61
  14. package/target/main/ts/api/git/inspection-source.d.ts +2 -1
  15. package/target/main/ts/api/git/inspection-source.js +3 -2
  16. package/target/main/ts/api/git/local-sources.js +3 -2
  17. package/target/main/ts/api/git/source-cache.d.ts +0 -2
  18. package/target/main/ts/api/git/source-cache.js +1 -16
  19. package/target/main/ts/api/process/go-parser-cache.d.ts +1 -0
  20. package/target/main/ts/api/process/go-parser-cache.js +71 -0
  21. package/target/main/ts/api/process/go-parser-files.d.ts +5 -0
  22. package/target/main/ts/api/process/go-parser-files.js +65 -0
  23. package/target/main/ts/api/process/host-language-runner.d.ts +3 -5
  24. package/target/main/ts/api/process/host-language-runner.js +21 -66
  25. package/target/main/ts/api/process/host-tool.d.ts +22 -0
  26. package/target/main/ts/api/process/host-tool.js +87 -0
  27. package/target/main/ts/cli/config.d.ts +13 -0
  28. package/target/main/ts/cli/config.js +7 -4
  29. package/target/main/ts/cli/main.js +24 -81
  30. package/target/main/ts/cli/range-inspection.d.ts +28 -0
  31. package/target/main/ts/cli/range-inspection.js +41 -0
  32. package/target/main/ts/cli/range-jobs.d.ts +22 -0
  33. package/target/main/ts/cli/range-jobs.js +152 -0
  34. package/target/main/ts/cli/range-worker.d.ts +1 -0
  35. package/target/main/ts/cli/range-worker.js +36 -0
  36. package/target/main/ts/compose/analysis-report.js +4 -3
  37. package/target/main/ts/compose/diff-coverage.js +1 -1
  38. package/target/main/ts/compose/history-cache.d.ts +2 -0
  39. package/target/main/ts/compose/history-cache.js +2 -0
  40. package/target/main/ts/compose/inspect.js +3 -3
  41. package/target/main/ts/compose/native-language-plugins.js +7 -6
  42. package/target/main/ts/compose/review.js +3 -1
  43. package/target/main/ts/report/json/projections/commit-summary.js +5 -7
  44. package/target/main/ts/report/json/projections/metric-values.d.ts +5 -0
  45. package/target/main/ts/report/json/projections/metric-values.js +9 -6
  46. package/target/main/ts/report/markdown/pull-review.js +11 -1
@@ -1,15 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { lstat, readFile, realpath, writeFile } from 'node:fs/promises';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
3
  import { join, relative, resolve, sep } from 'node:path';
4
4
  import { firstParentRange, gitRoot, resolveGitCommit } from '../api/git/git.js';
5
5
  import { gitReportObjects } from '../api/git/git-reader.js';
6
6
  import { resolveGitBranch } from '../api/git/commit-metadata.js';
7
- import { clearSourceCache, sourceCacheRoot } from '../api/git/source-cache.js';
7
+ import { cacheRoot, clearCaches } from '../api/cache/root.js';
8
8
  import { gitHubPullRequest, writeGitHubDiffCoverage, writeGitHubResult, writeGitHubReview } from '../api/gh/github.js';
9
- import { remoteExecutor } from '../api/worker/remote-executor.js';
10
9
  import { serveWorker } from '../api/worker/worker.js';
11
10
  import { workerToken } from '../api/worker/worker-protocol.js';
12
- import { HistoryCache } from '../compose/history-cache.js';
13
11
  import { defaultLanguages, languageRegistry } from '../compose/languages.js';
14
12
  import { analyzeSnapshot, attachFindings, inspect } from '../compose/inspect.js';
15
13
  import { measureDiffCoverage } from '../compose/diff-coverage.js';
@@ -21,12 +19,13 @@ import { sourceExclusionMatcher } from '../core/profile/exclusions.js';
21
19
  import { compareInspections } from '../core/usecases/compare.js';
22
20
  import { exportProjects } from '../report/html/site/projects.js';
23
21
  import { fileMetrics } from '../report/json/projections/file-metrics.js';
24
- import { LocalReportStore } from '../report/json/store/local-store.js';
25
22
  import { pullReviewMarkdown } from '../report/markdown/pull-review.js';
26
23
  import { LocalObjectStore } from '../report/json/store/object-store.js';
27
24
  import { checkStore } from '../report/json/store/store-check.js';
28
25
  import { dispatch, flag, option } from './arguments.js';
29
- import { configFile, readConfig } from './config.js';
26
+ import { configFile, parseConfig, readConfig, readConfigValue } from './config.js';
27
+ import { analyzeCommits, isSaved } from './range-jobs.js';
28
+ import { analysisExecutor } from './range-inspection.js';
30
29
  import { importerIds, readInputs } from './imports.js';
31
30
  import { outputReports, reporterIds, viewTarget } from './reporting.js';
32
31
  import { parseRange } from './revisions.js';
@@ -49,10 +48,11 @@ const commands = {
49
48
  description: 'Analyze and save one revision or a range of commits.', parameters: '[REVISION | BASE..[HEAD]]', max: 1,
50
49
  options: { ...configOptions, ...renderOptions, 'working-tree': flag('Analyze the working directory.'),
51
50
  'skip-saved': flag('Keep commits that already have a saved inspection.'),
51
+ concurrency: option('N', 'Maximum local analysis workers for a range. Defaults to the available cores.'),
52
52
  import: importOption, report: option('FORMAT[=PATH]', 'Generate a report after inspection. Repeatable.', { multiple: true }),
53
53
  exclude: excludeOption, 'import-root': option('DIR', 'Resolve scanner locations relative to this directory.'),
54
54
  worker: option('URL', 'Run analysis on a Repometry worker.'), ci: ciOption },
55
- run: analyze,
55
+ run: runAnalysis,
56
56
  },
57
57
  show: {
58
58
  description: 'Print a saved report.', parameters: 'REVISION|DIGEST', min: 1, max: 1,
@@ -135,10 +135,9 @@ const commands = {
135
135
  throw new Error('Use cache path or cache clear');
136
136
  if (action === 'path' && input.flag('sources'))
137
137
  throw new Error('--sources requires cache clear');
138
- const path = sourceCacheRoot();
139
- if (action === 'clear')
140
- await clearSourceCache(path);
141
- print({ schema: 'urn:repometry:schema:cache-result:1', path, ...(action === 'clear' ? { cleared: ['sources'] } : {}) });
138
+ const path = cacheRoot();
139
+ const cleared = action === 'clear' ? await clearCaches(path, input.flag('sources')) : undefined;
140
+ print({ schema: 'urn:repometry:schema:cache-result:1', path, cleared });
142
141
  },
143
142
  },
144
143
  store: {
@@ -176,10 +175,15 @@ async function context(input) {
176
175
  const root = await findRepository(directory) ?? directory;
177
176
  return { directory, root, store: selectStore(root, input.text('store'), directory) };
178
177
  }
179
- async function analyze(input) {
178
+ function runAnalysis(input) {
180
179
  const range = input.args[0] === undefined ? undefined : parseRange(input.args[0]);
181
180
  if (range)
182
181
  return analyzeRange(input, range);
182
+ if (input.text('concurrency') !== undefined)
183
+ throw new Error('--concurrency requires a revision range');
184
+ return analyze(input);
185
+ }
186
+ async function analyze(input) {
183
187
  const { directory, root, store } = await context(input);
184
188
  const output = writableStore(store);
185
189
  if (input.flag('working-tree') && input.args.length)
@@ -195,7 +199,7 @@ async function analyze(input) {
195
199
  const importRoot = input.text('import-root');
196
200
  if (importRoot && findings.length === 0)
197
201
  throw new Error('--import-root requires a scanner report');
198
- const executor = analysisExecutor(input, config.plugins);
202
+ const executor = analysisExecutor(input.text('worker'), config.plugins);
199
203
  const savedId = input.flag('skip-saved') ? await resolveGitCommit(root, revision) : undefined;
200
204
  const skipped = savedId !== undefined && await isSaved(output, savedId);
201
205
  const report = skipped ? await store.reader.read({ kind: 'commit', id: savedId })
@@ -221,85 +225,24 @@ async function analyzeRange(input, range) {
221
225
  throw new Error('--import-root requires a scanner report');
222
226
  if (useGitHub(input))
223
227
  throw new Error('--ci github needs a single revision');
224
- const config = await readConfig(root, input);
228
+ const concurrency = count(input.text('concurrency'), '--concurrency', 1);
229
+ const configValue = await readConfigValue(root, input);
230
+ const config = parseConfig(configValue);
225
231
  if (config.imports.length)
226
232
  process.stderr.write('Imports from the config describe one checkout and are skipped for a range.\n');
227
233
  const { base, head, commits } = await firstParentRange(root, range.base, range.head);
228
234
  if (!commits.length)
229
235
  process.stderr.write(`No commits in ${range.base}..${range.head}.\n`);
230
- const executor = analysisExecutor(input, config.plugins);
231
- const exclude = [...config.exclude, ...input.many('exclude')];
232
- const { plugins, ...profile } = config;
233
- const history = executor === undefined ? new HistoryCache(profile) : undefined;
234
- const inspectCommit = (id) => inspect({ directory, output, source: { revision: id }, exclude,
235
- ignore: config.ignore, plugins }, executor, { history, deferSummary: true });
236
- const skip = input.flag('skip-saved') ? (id) => isSaved(output, id) : undefined;
237
- const { interrupted, ...results } = await analyzeCommits(commits, inspectCommit, skip);
238
- if (results.analyzed.length || results.skipped.length) {
239
- await new LocalReportStore(await realpath(output)).refreshSummary();
240
- }
236
+ const inspection = { directory, output, exclude: input.many('exclude'), worker: input.text('worker') };
237
+ const { interrupted, ...results } = await analyzeCommits(commits, {
238
+ inspection, config, configValue, concurrency, skipSaved: input.flag('skip-saved'),
239
+ });
241
240
  const requested = input.many('report');
242
241
  const reports = interrupted ? [] : await outputReports(root, store, requested.length ? requested : config.reports, input, config);
243
242
  print({ schema: 'urn:repometry:schema:analyze-range:1', range: `${base}..${head}`,
244
243
  ...results, store: output, reports });
245
244
  return interrupted ? 130 : results.failed.length || results.partial.length ? 2 : 0;
246
245
  }
247
- async function analyzeCommits(commits, inspectCommit, skip) {
248
- const analyzed = [], partial = [], skipped = [];
249
- const failed = [];
250
- let interrupted = false;
251
- const stop = () => { interrupted = true; process.stderr.write('Stopping after the current commit.\n'); };
252
- process.once('SIGINT', stop);
253
- const width = String(commits.length).length;
254
- const progress = (index, id, state) => process.stderr.write(`[${String(index + 1).padStart(width)}/${commits.length}] ${id.slice(0, 7)} ${state}\n`);
255
- try {
256
- for (const [index, id] of commits.entries()) {
257
- if (interrupted)
258
- break;
259
- if (skip !== undefined && await skip(id)) {
260
- skipped.push(id);
261
- progress(index, id, 'skipped');
262
- continue;
263
- }
264
- try {
265
- const report = await inspectCommit(id);
266
- analyzed.push(id);
267
- if (report.status === 'partial')
268
- partial.push(id);
269
- progress(index, id, report.status === 'partial' ? 'partial' : 'analyzed');
270
- }
271
- catch (error) {
272
- if (interrupted)
273
- break;
274
- const message = error instanceof Error ? error.message : String(error);
275
- failed.push({ commit: id, error: message });
276
- progress(index, id, `failed: ${message}`);
277
- }
278
- }
279
- }
280
- finally {
281
- process.removeListener('SIGINT', stop);
282
- }
283
- return { analyzed, partial, skipped, failed, interrupted };
284
- }
285
- function analysisExecutor(input, plugins) {
286
- const worker = input.text('worker');
287
- if (worker === undefined)
288
- return undefined;
289
- if (plugins.length)
290
- throw new Error('Configured process plugins require local analysis. Use --no-config with --worker.');
291
- return remoteExecutor(worker, workerToken(), languageRegistry([]).isSource);
292
- }
293
- async function isSaved(store, id) {
294
- try {
295
- return (await lstat(join(store, 'commits', id, 'report.json'))).isFile();
296
- }
297
- catch (error) {
298
- if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))
299
- return false;
300
- throw error;
301
- }
302
- }
303
246
  async function show(input) {
304
247
  const { root, store } = await context(input);
305
248
  const ref = input.args[0];
@@ -0,0 +1,28 @@
1
+ import type { Plugin } from '../core/engine/plugin.js';
2
+ import type { Report } from '../core/model/report.js';
3
+ import type { parseConfig } from './config.js';
4
+ export interface RangeInspection {
5
+ readonly directory: string;
6
+ readonly output: string;
7
+ readonly exclude: readonly string[];
8
+ readonly worker?: string;
9
+ }
10
+ export type CommitOutcome = {
11
+ readonly commit: string;
12
+ readonly state: 'analyzed' | 'partial';
13
+ } | {
14
+ readonly commit: string;
15
+ readonly state: 'failed';
16
+ readonly error: string;
17
+ };
18
+ export type RangeMessage = {
19
+ readonly kind: 'start';
20
+ readonly commits: readonly string[];
21
+ readonly inspection: RangeInspection;
22
+ readonly config: unknown;
23
+ } | {
24
+ readonly kind: 'stop';
25
+ };
26
+ export declare function analysisExecutor(worker: string | undefined, plugins: readonly Plugin[]): import("../compose/inspect.js").AnalysisExecutor | undefined;
27
+ export declare function rangeInspector(inspection: RangeInspection, config: ReturnType<typeof parseConfig>): (revision: string) => Promise<Report>;
28
+ export declare function inspectCommits(commits: readonly string[], inspectCommit: (id: string) => Promise<Report>, stopped: () => boolean, report: (outcome: CommitOutcome) => void | Promise<void>): Promise<void>;
@@ -0,0 +1,41 @@
1
+ import { remoteExecutor } from '../api/worker/remote-executor.js';
2
+ import { workerToken } from '../api/worker/worker-protocol.js';
3
+ import { HistoryCache } from '../compose/history-cache.js';
4
+ import { inspect } from '../compose/inspect.js';
5
+ import { languageRegistry } from '../compose/languages.js';
6
+ export function analysisExecutor(worker, plugins) {
7
+ if (worker === undefined)
8
+ return undefined;
9
+ if (plugins.length)
10
+ throw new Error('Configured process plugins require local analysis. Use --no-config with --worker.');
11
+ return remoteExecutor(worker, workerToken(), languageRegistry([]).isSource);
12
+ }
13
+ export function rangeInspector(inspection, config) {
14
+ const { plugins, ...profile } = config;
15
+ const executor = analysisExecutor(inspection.worker, plugins);
16
+ const history = executor === undefined ? new HistoryCache(profile) : undefined;
17
+ const { directory, output } = inspection;
18
+ const exclude = [...config.exclude, ...inspection.exclude];
19
+ return (revision) => inspect({ directory, output, source: { revision }, exclude,
20
+ ignore: config.ignore, plugins }, executor, { history, deferSummary: true });
21
+ }
22
+ export async function inspectCommits(commits, inspectCommit, stopped, report) {
23
+ for (const commit of commits) {
24
+ if (stopped())
25
+ break;
26
+ const outcome = await inspectOne(commit, inspectCommit);
27
+ if (outcome.state === 'failed' && stopped())
28
+ break;
29
+ await report(outcome);
30
+ }
31
+ }
32
+ async function inspectOne(commit, inspectCommit) {
33
+ try {
34
+ const report = await inspectCommit(commit);
35
+ return { commit, state: report.status === 'partial' ? 'partial' : 'analyzed' };
36
+ }
37
+ catch (error) {
38
+ return { commit, state: 'failed', error: error instanceof Error ? error.message : String(error) };
39
+ }
40
+ }
41
+ //# sourceMappingURL=range-inspection.js.map
@@ -0,0 +1,22 @@
1
+ import type { RangeInspection } from './range-inspection.js';
2
+ import type { parseConfig } from './config.js';
3
+ export declare function historyChunks(commits: readonly string[], concurrency: number, memory: number): readonly (readonly string[])[];
4
+ interface RangeOptions {
5
+ readonly inspection: RangeInspection;
6
+ readonly config: ReturnType<typeof parseConfig>;
7
+ readonly configValue: unknown;
8
+ readonly concurrency?: number;
9
+ readonly skipSaved: boolean;
10
+ }
11
+ export declare function analyzeCommits(commits: readonly string[], options: RangeOptions): Promise<{
12
+ interrupted: boolean;
13
+ analyzed: string[];
14
+ partial: string[];
15
+ skipped: string[];
16
+ failed: {
17
+ commit: string;
18
+ error: string;
19
+ }[];
20
+ }>;
21
+ export declare function isSaved(store: string, id: string): Promise<boolean>;
22
+ export {};
@@ -0,0 +1,152 @@
1
+ import { fork } from 'node:child_process';
2
+ import { lstat, realpath } from 'node:fs/promises';
3
+ import { availableParallelism } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { LocalReportStore } from '../report/json/store/local-store.js';
6
+ import { inspectCommits, rangeInspector } from './range-inspection.js';
7
+ const minimumChunkSize = 25;
8
+ const workerMemoryBytes = 512 * 1024 * 1024;
9
+ export function historyChunks(commits, concurrency, memory) {
10
+ if (commits.length === 0)
11
+ return [];
12
+ const workers = Math.max(1, Math.min(concurrency, Math.floor(memory / workerMemoryBytes), Math.floor(commits.length / minimumChunkSize)));
13
+ const size = Math.floor(commits.length / workers);
14
+ const remainder = commits.length % workers;
15
+ return Array.from({ length: workers }, (_, index) => {
16
+ const start = index * size + Math.min(index, remainder);
17
+ return commits.slice(start, start + size + Number(index < remainder));
18
+ });
19
+ }
20
+ export async function analyzeCommits(commits, options) {
21
+ const { inspection, config, configValue, concurrency, skipSaved } = options;
22
+ const inspectCommit = rangeInspector(inspection, config);
23
+ const outcomes = new Map();
24
+ const control = new AbortController();
25
+ const { signal } = control;
26
+ const stop = () => {
27
+ if (signal.aborted)
28
+ return;
29
+ control.abort();
30
+ process.stderr.write('Stopping after the current commit in each worker.\n');
31
+ };
32
+ process.on('SIGINT', stop);
33
+ const width = String(commits.length).length;
34
+ const record = (outcome) => {
35
+ outcomes.set(outcome.commit, outcome);
36
+ const state = outcome.state === 'failed' ? `failed: ${outcome.error}` : outcome.state;
37
+ process.stderr.write(`[${String(outcomes.size).padStart(width)}/${commits.length}] ${outcome.commit.slice(0, 7)} ${state}\n`);
38
+ };
39
+ try {
40
+ const pending = await pendingCommits(commits, inspection.output, skipSaved, signal, record);
41
+ // The remote worker accepts one request at a time.
42
+ const workers = inspection.worker === undefined ? concurrency ?? availableParallelism() : 1;
43
+ const chunks = historyChunks(pending, workers, process.availableMemory());
44
+ if (!signal.aborted && chunks.length === 1) {
45
+ await inspectCommits(chunks[0], inspectCommit, () => signal.aborted, record);
46
+ }
47
+ else if (!signal.aborted) {
48
+ await Promise.all(chunks.map(chunk => runChunk(chunk, inspection, configValue, signal, record)));
49
+ }
50
+ const results = collectOutcomes(commits, outcomes);
51
+ if (results.analyzed.length || results.skipped.length) {
52
+ await new LocalReportStore(await realpath(inspection.output)).refreshSummary();
53
+ }
54
+ return { ...results, interrupted: signal.aborted };
55
+ }
56
+ finally {
57
+ process.removeListener('SIGINT', stop);
58
+ }
59
+ }
60
+ async function pendingCommits(commits, store, skipSaved, signal, record) {
61
+ if (!skipSaved)
62
+ return commits;
63
+ const pending = [];
64
+ for (const commit of commits) {
65
+ if (signal.aborted)
66
+ break;
67
+ if (await isSaved(store, commit))
68
+ record({ commit, state: 'skipped' });
69
+ else
70
+ pending.push(commit);
71
+ }
72
+ return pending;
73
+ }
74
+ export async function isSaved(store, id) {
75
+ try {
76
+ return (await lstat(join(store, 'commits', id, 'report.json'))).isFile();
77
+ }
78
+ catch (error) {
79
+ if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))
80
+ return false;
81
+ throw error;
82
+ }
83
+ }
84
+ function collectOutcomes(commits, outcomes) {
85
+ const analyzed = [], partial = [], skipped = [];
86
+ const failed = [];
87
+ for (const commit of commits) {
88
+ const outcome = outcomes.get(commit);
89
+ switch (outcome?.state) {
90
+ case 'partial': partial.push(commit);
91
+ // Partial analysis still leaves a saved report.
92
+ case 'analyzed':
93
+ analyzed.push(commit);
94
+ break;
95
+ case 'skipped':
96
+ skipped.push(commit);
97
+ break;
98
+ case 'failed':
99
+ failed.push({ commit, error: outcome.error });
100
+ break;
101
+ }
102
+ }
103
+ return { analyzed, partial, skipped, failed };
104
+ }
105
+ async function runChunk(commits, inspection, config, signal, record) {
106
+ const pending = new Set(commits);
107
+ try {
108
+ // A terminal interrupt reaches the coordinator. Workers finish their current Git and analyzer subprocesses.
109
+ const worker = fork(new URL('./range-worker.js', import.meta.url), [], {
110
+ detached: process.platform !== 'win32', execArgv: [], stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
111
+ });
112
+ const message = { kind: 'start', commits, inspection, config };
113
+ await runWorker(worker, message, signal, outcome => {
114
+ if (pending.delete(outcome.commit))
115
+ record(outcome);
116
+ });
117
+ failPending('Range worker exited before reporting the remaining commits');
118
+ }
119
+ catch (error) {
120
+ failPending(error instanceof Error ? error.message : String(error));
121
+ }
122
+ function failPending(error) {
123
+ if (!signal.aborted)
124
+ for (const commit of pending)
125
+ record({ commit, state: 'failed', error });
126
+ }
127
+ }
128
+ function runWorker(worker, message, signal, record) {
129
+ return new Promise((resolve, reject) => {
130
+ const stop = () => {
131
+ const interrupt = { kind: 'stop' };
132
+ if (worker.connected)
133
+ worker.send(interrupt, () => { });
134
+ };
135
+ worker.on('message', record);
136
+ worker.once('error', reject);
137
+ worker.once('close', (code, cause) => {
138
+ signal.removeEventListener('abort', stop);
139
+ if (code === 0 || signal.aborted)
140
+ resolve();
141
+ else
142
+ reject(new Error(`Range worker exited with ${cause ?? code}`));
143
+ });
144
+ worker.send(message, error => { if (error && !signal.aborted)
145
+ reject(error); });
146
+ if (signal.aborted)
147
+ stop();
148
+ else
149
+ signal.addEventListener('abort', stop, { once: true });
150
+ });
151
+ }
152
+ //# sourceMappingURL=range-jobs.js.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ import { parseConfig } from './config.js';
2
+ import { inspectCommits, rangeInspector } from './range-inspection.js';
3
+ let stopped = false;
4
+ let started = false;
5
+ const stop = () => { stopped = true; };
6
+ process.on('SIGINT', stop);
7
+ process.on('disconnect', stop);
8
+ process.on('message', (message) => {
9
+ if (message.kind === 'stop')
10
+ stop();
11
+ else if (!started) {
12
+ started = true;
13
+ void run(message);
14
+ }
15
+ });
16
+ async function run({ commits, inspection, config }) {
17
+ try {
18
+ await inspectCommits(commits, rangeInspector(inspection, parseConfig(config)), () => stopped, send);
19
+ }
20
+ catch (error) {
21
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
22
+ process.exitCode = 1;
23
+ }
24
+ finally {
25
+ if (process.connected)
26
+ process.disconnect();
27
+ }
28
+ }
29
+ function send(outcome) {
30
+ if (!process.connected)
31
+ return Promise.resolve();
32
+ return new Promise((resolve, reject) => {
33
+ process.send(outcome, error => error ? reject(error) : resolve());
34
+ });
35
+ }
36
+ //# sourceMappingURL=range-worker.js.map
@@ -1,3 +1,4 @@
1
+ import { structureMeasures } from '../core/model/code-structure.js';
1
2
  import { definitions } from '../core/model/measurement.js';
2
3
  import { debtModel } from '../core/model/quality-summary.js';
3
4
  import { reportSchema } from '../core/model/report.js';
@@ -21,7 +22,7 @@ const measurementDefinitions = {
21
22
  export function assembleAnalysisReport(input, sources, results) {
22
23
  const pluginData = results.pluginData();
23
24
  const { snapshot } = input;
24
- const fileCount = sources.sourceFiles.length;
25
+ const fileCount = sources.sourceFiles.length + sources.unavailableFiles.size;
25
26
  return {
26
27
  schema: reportSchema,
27
28
  subject: snapshot.subject,
@@ -30,7 +31,7 @@ export function assembleAnalysisReport(input, sources, results) {
30
31
  definitions: { ...Object.fromEntries((pluginData?.metrics ?? []).map(metric => [metric.id, metric.description ?? metric.label])),
31
32
  ...measurementDefinitions },
32
33
  scope: { files: fileCount, parsed: results.parsed.size },
33
- status: inspectionStatus(fileCount > 0 || sources.unavailableFiles.size > 0, results),
34
+ status: inspectionStatus(fileCount > 0, results),
34
35
  measurements: results.measurements,
35
36
  diagnostics: results.diagnostics,
36
37
  findings: results.findings,
@@ -74,7 +75,7 @@ function reportInventory(snapshot, sources, results) {
74
75
  }
75
76
  return [...inventory].sort(([left], [right]) => comparePaths(left, right)).map(([path, { lines, bytes }]) => {
76
77
  const provider = sources.providersByPath.get(path);
77
- const unmeasured = results.unmeasured.get(path);
78
+ const unmeasured = sources.unavailableFiles.has(path) ? structureMeasures : results.unmeasured.get(path);
78
79
  return { path, lines, ...(bytes === undefined ? {} : { bytes }), language: provider?.language(path) ?? fileTypeId(path),
79
80
  analysed: results.parsed.has(path) || results.inspected.has(path), ...(provider === undefined ? {} : { provider: provider.key }),
80
81
  ...(unmeasured === undefined ? {} : { unmeasured }) };
@@ -44,7 +44,7 @@ async function readInputs(request, excludedPaths, excludes) {
44
44
  ]);
45
45
  const base = await findMergeBase(root, requestedBase, head);
46
46
  const { isSource, extensions, globs } = languageRegistry(request.plugins ?? []);
47
- const snapshot = await readGitCommit(root, head, excludes, isSource);
47
+ const snapshot = await readGitCommit(root, head, { excludes, isSource });
48
48
  const [lcov, changes] = await Promise.all([
49
49
  readInspectionCoverage(request, { root, snapshot }),
50
50
  readChanges(root, base, snapshot, sourceExclusionMatcher(excludedPaths, snapshot.generatedExcluded), isSource),
@@ -1,3 +1,4 @@
1
+ import { GitBlobHistory } from '../api/git/blob-history.js';
1
2
  import type { Outcome } from '../core/engine/execute.js';
2
3
  import type { CodeStructure } from '../core/model/code-structure.js';
3
4
  import type { SourceSnapshot } from '../core/model/source.js';
@@ -20,6 +21,7 @@ export declare class HistoryFiles {
20
21
  /** One range keeps at most two adjacent snapshots' results during inspection. */
21
22
  export declare class HistoryCache {
22
23
  private readonly configuration?;
24
+ readonly blobs: GitBlobHistory;
23
25
  private previous?;
24
26
  constructor(configuration?: unknown);
25
27
  begin(snapshot: SourceSnapshot, profile: string): HistoryFiles | undefined;
@@ -1,3 +1,4 @@
1
+ import { GitBlobHistory } from '../api/git/blob-history.js';
1
2
  import { debtModel } from '../core/model/quality-summary.js';
2
3
  import { digest, sourceDirectoriesExcluded } from '../core/model/snapshot.js';
3
4
  import { defaultSourceExclusions, generatedSourcePolicy } from '../core/profile/exclusions.js';
@@ -24,6 +25,7 @@ export class HistoryFiles {
24
25
  /** One range keeps at most two adjacent snapshots' results during inspection. */
25
26
  export class HistoryCache {
26
27
  configuration;
28
+ blobs = new GitBlobHistory();
27
29
  previous;
28
30
  constructor(configuration) {
29
31
  this.configuration = configuration;
@@ -20,7 +20,7 @@ export async function inspect(request, overrides, { history, deferSummary = fals
20
20
  const claims = inspectionFileMatcher(plugins, languages);
21
21
  const { isSource } = languages;
22
22
  const ports = {
23
- readSource: excludes => readSource(request, excludes, isSource, claims, deferSummary),
23
+ readSource: excludes => readSource(request, { excludes, isSource, claims, history: history?.blobs }, deferSummary),
24
24
  analyze: input => analyzeSnapshot(input, plugins, operationCache, history),
25
25
  ...(lcov === undefined && goCover === undefined ? {} : { readCoverage: source => readInspectionCoverage({ lcov, goCover }, source) }),
26
26
  ...(findingInputs.length === 0 ? {} : { importFindings: (report, root, excludes) => attachFindings(report, findingInputs, root, request.findingRoot === undefined ? root : resolve(request.findingRoot), excludes) }),
@@ -29,8 +29,8 @@ export async function inspect(request, overrides, { history, deferSummary = fals
29
29
  };
30
30
  return executeInspection(request, ports);
31
31
  }
32
- async function readSource(request, excludes, isSource, claims, deferSummary) {
33
- const source = await readInspectionSource(request, excludes, isSource, claims);
32
+ async function readSource(request, selection, deferSummary) {
33
+ const source = await readInspectionSource(request, selection);
34
34
  const store = new LocalReportStore(source.output);
35
35
  return { ...source, save: (report) => store.save(report, { deferSummary }) };
36
36
  }
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { fileURLToPath } from 'node:url';
3
- import { HostLanguageRunner, hostToolPath, hostToolVersion } from '../api/process/host-language-runner.js';
3
+ import { hostToolPath, probeHostTool } from '../api/process/host-tool.js';
4
+ import { HostLanguageRunner } from '../api/process/host-language-runner.js';
4
5
  import { bindProcessPlugin } from '../api/process/plugin.js';
5
6
  import { pluginApi } from '../core/engine/plugin.js';
6
7
  import { codeStructures } from '../core/model/code-structure.js';
@@ -27,14 +28,14 @@ function createPlugin({ id, language, binary, args, versionArgs, script, measure
27
28
  const manifest = { id, version: '1.1.0', api: pluginApi, kinds: ['language'],
28
29
  settings: { duplication: duplicationSettings },
29
30
  providesLanguages: [declaration], produces: [{ contract: codeStructures.id, persistence: 'transient' }] };
30
- const version = hostToolVersion(binary, versionArgs, path)?.match(/\b(?:go|Python\s+)(\d+(?:\.\d+)+(?:[a-z][\w.-]*)?)/i)?.[1];
31
- if (version === undefined) {
32
- return { ...manifest, operations: [], unavailableReason: `${binary} not found on PATH` };
31
+ const tool = probeHostTool(binary, versionArgs, path);
32
+ if ('unavailableReason' in tool) {
33
+ return { ...manifest, operations: [], unavailableReason: tool.unavailableReason };
33
34
  }
34
35
  const parser = fileURLToPath(new URL(`../resources/languages/${script}`, import.meta.resolve('repometry/plugin')));
35
- return bindProcessPlugin({ ...manifest, tools: { [binary]: version }, operations: [{ id: 'parse', role: 'provider',
36
+ return bindProcessPlugin({ ...manifest, tools: { [binary]: tool.version }, operations: [{ id: 'parse', role: 'provider',
36
37
  scope: 'repository', fileIndependent: true, inputs: { files: sourceFiles }, output: codeStructures,
37
38
  argv: [binary, ...args], timeoutMs: 90_000, maxOutputBytes: 16 * 1024 * 1024, implementation: digest(readFileSync(parser)),
38
- }] }, new HostLanguageRunner(path, parser));
39
+ }] }, new HostLanguageRunner(path, parser, tool));
39
40
  }
40
41
  //# sourceMappingURL=native-language-plugins.js.map
@@ -26,7 +26,7 @@ export async function review(request) {
26
26
  try {
27
27
  const history = new HistoryCache(request.settings);
28
28
  const inspectCommit = (id, coverage) => inspect({ directory, output, source: { revision: id }, exclude, ignore, plugins,
29
- ...coverage ? { lcov, goCover } : {} }, undefined, { history, deferSummary: true });
29
+ ...coverage ? { lcov, goCover } : {} }, noChurn, { history, deferSummary: true });
30
30
  const base = await inspectCommit(mergeBase, false);
31
31
  const headReport = await inspectCommit(head, true);
32
32
  const changes = await readLineChanges(directory, mergeBase, head);
@@ -41,6 +41,8 @@ export async function review(request) {
41
41
  await rm(output, { recursive: true, force: true });
42
42
  }
43
43
  }
44
+ /** A review compares findings, not file activity: it skips the walk over Git history that churn needs. */
45
+ const noChurn = { recordChurn: undefined };
44
46
  /** The text of one side's changed files, which scope and matching read line by line. */
45
47
  async function sourceLines(directory, commit, changes, side) {
46
48
  const paths = changes.files.flatMap(file => file[side] === null || file.whole ? [] : [file[side]]);
@@ -5,7 +5,7 @@ import { securityCounts } from './security-summary.js';
5
5
  import { compareHistoryEntries } from '../wire/public-history-model.js';
6
6
  import { inspectionProfileDigest } from './inspection-context.js';
7
7
  import { reportRevision } from '../validation/report.js';
8
- import { canonicalMetricDescriptor, metricProjection } from './metric-values.js';
8
+ import { canonicalMetricDescriptor, metricProjection, unavailableStructureMetrics } from './metric-values.js';
9
9
  import { summarySchema } from '../wire/summary-model.js';
10
10
  export function commitSummary(report) {
11
11
  const history = historyEntry(report);
@@ -111,17 +111,15 @@ export function historyEntry(report) {
111
111
  lineCoverage = { covered: item.covered, total: item.total };
112
112
  }
113
113
  }
114
- const unmeasured = new Set(report.pluginData?.inventory?.flatMap(file => file.unmeasured ?? []));
115
- if (unmeasured.has('functions'))
116
- functions = null;
117
- if (unmeasured.has('cyclomaticComplexity'))
118
- maxComplexity = null;
114
+ const unmeasured = new Set(report.pluginData?.inventory?.flatMap(unavailableStructureMetrics));
115
+ const measured = (id, value) => unmeasured.has(id) ? null : value;
119
116
  const window = report.appliedConfig.churnWindow;
120
117
  const endingAt = isRecord(window) && typeof window.endingAt === 'string' ? window.endingAt : '';
121
118
  const committedAt = Date.parse(report.committedAt ?? endingAt);
122
119
  const generatedAt = Date.parse(report.generatedAt);
123
120
  return { sha: report.subject.id, generatedAt: Number.isFinite(generatedAt) ? new Date(generatedAt).toISOString() : '',
124
121
  ...(Number.isFinite(committedAt) ? { committedAt: new Date(committedAt).toISOString() } : {}), status: report.status,
125
- files: report.scope.files, parsed: report.scope.parsed, lines, functions, maxComplexity, lineCoverage };
122
+ files: report.scope.files, parsed: report.scope.parsed, lines: measured(definitions.lines, lines),
123
+ functions: measured(definitions.functions, functions), maxComplexity: measured(definitions.complexity, maxComplexity), lineCoverage };
126
124
  }
127
125
  //# sourceMappingURL=commit-summary.js.map
@@ -1,4 +1,5 @@
1
1
  import type { MetricDescriptor, MetricValues } from '../wire/summary-model.js';
2
+ import type { StructureMeasure } from '../../../core/model/code-structure.js';
2
3
  import type { Report } from '../../../core/model/report.js';
3
4
  export declare function metricProjection(report: Report): {
4
5
  catalog: MetricDescriptor[];
@@ -6,4 +7,8 @@ export declare function metricProjection(report: Report): {
6
7
  values: (path?: string, directory?: boolean) => MetricValues;
7
8
  isAvailable: (id: string, path?: string, directory?: boolean) => boolean;
8
9
  } | undefined;
10
+ export declare function unavailableStructureMetrics({ analysed, unmeasured }: {
11
+ readonly analysed: boolean;
12
+ readonly unmeasured?: readonly StructureMeasure[];
13
+ }): string[];
9
14
  export declare function canonicalMetricDescriptor(metric: MetricDescriptor): MetricDescriptor;