repometry 0.10.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 (43) 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-executable.d.ts +1 -0
  10. package/target/main/ts/api/git/git-executable.js +31 -0
  11. package/target/main/ts/api/git/git.d.ts +8 -1
  12. package/target/main/ts/api/git/git.js +58 -61
  13. package/target/main/ts/api/git/inspection-source.d.ts +2 -1
  14. package/target/main/ts/api/git/inspection-source.js +3 -2
  15. package/target/main/ts/api/git/local-sources.js +3 -2
  16. package/target/main/ts/api/git/source-cache.d.ts +0 -2
  17. package/target/main/ts/api/git/source-cache.js +1 -16
  18. package/target/main/ts/api/process/go-parser-cache.d.ts +1 -0
  19. package/target/main/ts/api/process/go-parser-cache.js +71 -0
  20. package/target/main/ts/api/process/go-parser-files.d.ts +5 -0
  21. package/target/main/ts/api/process/go-parser-files.js +65 -0
  22. package/target/main/ts/api/process/host-language-runner.d.ts +3 -5
  23. package/target/main/ts/api/process/host-language-runner.js +21 -66
  24. package/target/main/ts/api/process/host-tool.d.ts +22 -0
  25. package/target/main/ts/api/process/host-tool.js +87 -0
  26. package/target/main/ts/cli/config.d.ts +13 -0
  27. package/target/main/ts/cli/config.js +7 -4
  28. package/target/main/ts/cli/main.js +24 -81
  29. package/target/main/ts/cli/range-inspection.d.ts +28 -0
  30. package/target/main/ts/cli/range-inspection.js +41 -0
  31. package/target/main/ts/cli/range-jobs.d.ts +22 -0
  32. package/target/main/ts/cli/range-jobs.js +152 -0
  33. package/target/main/ts/cli/range-worker.d.ts +1 -0
  34. package/target/main/ts/cli/range-worker.js +36 -0
  35. package/target/main/ts/compose/analysis-report.js +4 -3
  36. package/target/main/ts/compose/diff-coverage.js +1 -1
  37. package/target/main/ts/compose/history-cache.d.ts +2 -0
  38. package/target/main/ts/compose/history-cache.js +2 -0
  39. package/target/main/ts/compose/inspect.js +3 -3
  40. package/target/main/ts/compose/native-language-plugins.js +7 -6
  41. package/target/main/ts/report/json/projections/commit-summary.js +5 -7
  42. package/target/main/ts/report/json/projections/metric-values.d.ts +5 -0
  43. package/target/main/ts/report/json/projections/metric-values.js +9 -6
@@ -0,0 +1,65 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, chmod, copyFile, lstat, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { digest } from '../../core/model/snapshot.js';
5
+ const executableName = process.platform === 'win32' ? 'parser.exe' : 'parser';
6
+ export function errorCode(error) {
7
+ return error instanceof Error && 'code' in error ? error.code : undefined;
8
+ }
9
+ export async function privateDirectory(directory) {
10
+ const info = await lstat(directory);
11
+ if (!info.isDirectory() || !owned(info)) {
12
+ throw new Error(`Expected a directory owned by the current user: ${directory}`);
13
+ }
14
+ return info;
15
+ }
16
+ function owned(info) {
17
+ const user = process.getuid?.();
18
+ return user === undefined || (info.uid === user && (info.mode & 0o022) === 0);
19
+ }
20
+ export async function readCachedParser(directory) {
21
+ const executable = join(directory, executableName);
22
+ try {
23
+ await privateDirectory(directory);
24
+ const info = await lstat(executable);
25
+ if (!info.isFile() || !owned(info))
26
+ throw new Error(`Expected a parser owned by the current user: ${executable}`);
27
+ await access(executable, constants.X_OK);
28
+ const [contents, checksum] = await Promise.all([readFile(executable), readFile(join(directory, 'sha256'), 'utf8')]);
29
+ if (digest(contents) === checksum)
30
+ return executable;
31
+ }
32
+ catch (error) {
33
+ if (errorCode(error) !== 'ENOENT')
34
+ throw error;
35
+ }
36
+ }
37
+ export async function publishParser(cache, destination, local) {
38
+ const staging = await mkdtemp(join(cache, 'build-'));
39
+ try {
40
+ const binary = join(staging, executableName);
41
+ await copyFile(local, binary);
42
+ await chmod(binary, 0o700);
43
+ await writeFile(join(staging, 'sha256'), digest(await readFile(binary)), { mode: 0o600, flag: 'wx' });
44
+ return await installParser(staging, destination);
45
+ }
46
+ finally {
47
+ await rm(staging, { recursive: true, force: true });
48
+ }
49
+ }
50
+ async function installParser(staging, destination) {
51
+ try {
52
+ await rename(staging, destination);
53
+ }
54
+ catch (error) {
55
+ if (!['EEXIST', 'ENOTEMPTY'].includes(String(errorCode(error))))
56
+ throw error;
57
+ const published = await readCachedParser(destination);
58
+ if (published)
59
+ return published;
60
+ await rm(destination, { recursive: true, force: true });
61
+ await rename(staging, destination);
62
+ }
63
+ return join(destination, executableName);
64
+ }
65
+ //# sourceMappingURL=go-parser-files.js.map
@@ -1,13 +1,11 @@
1
1
  import type { ToolInvocation, ToolResult } from '../../core/ports/tool-runner.js';
2
- export declare function hostToolPath(): string;
3
- export declare function hostToolVersion(binary: string, args: readonly string[], path: string): string | undefined;
2
+ import type { VersionedHostTool } from './host-tool.js';
4
3
  export declare class HostLanguageRunner {
5
4
  private readonly path;
6
5
  private readonly script;
7
- private readonly goVersion?;
6
+ private readonly tool;
8
7
  readonly implementation = "host-language-runner/v1";
9
- private goCompiler?;
10
- constructor(path: string, script: string, goVersion?: string | undefined);
8
+ constructor(path: string, script: string, tool: VersionedHostTool);
11
9
  run(invocation: ToolInvocation): Promise<ToolResult>;
12
10
  private goParser;
13
11
  }
@@ -1,37 +1,23 @@
1
- import { execFile, spawnSync } from 'node:child_process';
2
- import { constants, mkdtempSync, rmSync } from 'node:fs';
3
- import { access, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
1
+ import { execFile } from 'node:child_process';
2
+ import { constants, rmSync } from 'node:fs';
3
+ import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
- import { delimiter, isAbsolute, join } from 'node:path';
5
+ import { join } from 'node:path';
6
6
  import { digest } from '../../core/model/snapshot.js';
7
7
  import { validateToolInvocation, writeToolSnapshot } from './tool-snapshot.js';
8
8
  import { toolFailure } from './failure.js';
9
- export function hostToolPath() {
10
- return (process.env.PATH ?? '').split(delimiter).filter(isAbsolute).join(delimiter);
11
- }
12
- export function hostToolVersion(binary, args, path) {
13
- if (!path)
14
- return undefined;
15
- const home = mkdtempSync(join(tmpdir(), 'repometry-tool-version-'));
16
- try {
17
- const result = spawnSync(binary, args, { cwd: home, env: toolEnvironment(path, home), encoding: 'utf8',
18
- timeout: 5_000, maxBuffer: 4_096, killSignal: 'SIGKILL', windowsHide: true });
19
- return result.status === 0 ? (result.stdout.trim() || result.stderr.trim() || undefined) : undefined;
20
- }
21
- finally {
22
- rmSync(home, { recursive: true, force: true });
23
- }
24
- }
9
+ import { cacheRoot } from '../cache/root.js';
10
+ import { cachedGoParser } from './go-parser-cache.js';
11
+ import { createToolHome, toolEnvironment } from './host-tool.js';
25
12
  export class HostLanguageRunner {
26
13
  path;
27
14
  script;
28
- goVersion;
15
+ tool;
29
16
  implementation = 'host-language-runner/v1';
30
- goCompiler;
31
- constructor(path, script, goVersion) {
17
+ constructor(path, script, tool) {
32
18
  this.path = path;
33
19
  this.script = script;
34
- this.goVersion = goVersion;
20
+ this.tool = tool;
35
21
  }
36
22
  async run(invocation) {
37
23
  validateToolInvocation(invocation);
@@ -43,7 +29,7 @@ export class HostLanguageRunner {
43
29
  const env = toolEnvironment(this.path, home);
44
30
  const [binary, ...args] = invocation.argv;
45
31
  if (binary !== 'go' || args.length !== 1 || args[0] !== 'run') {
46
- return await runTool(invocation, binary, [...args, this.script], cwd, env);
32
+ return await runTool(invocation, this.tool.binary, [...args, this.script], cwd, env);
47
33
  }
48
34
  const deadline = performance.now() + invocation.timeoutMs;
49
35
  const parser = await withinDeadline(this.goParser(invocation, deadline), deadline);
@@ -54,20 +40,19 @@ export class HostLanguageRunner {
54
40
  }
55
41
  }
56
42
  async goParser(invocation, deadline) {
57
- this.goCompiler ??= findGoCompiler(this.path, this.goVersion).catch(error => {
58
- this.goCompiler = undefined;
59
- throw error;
60
- });
61
- const [compiler, source] = await Promise.all([this.goCompiler, readFile(this.script)]);
62
- const key = JSON.stringify([compiler.binary, compiler.resolved, compiler.version, digest(source)]);
63
- const existing = goParsers.get(key);
43
+ const compiler = this.tool;
44
+ const source = await readFile(this.script);
45
+ const key = digest(JSON.stringify([process.platform, process.arch, compiler, digest(source)]));
46
+ const root = cacheRoot();
47
+ const processKey = JSON.stringify([root, key]);
48
+ const existing = goParsers.get(processKey);
64
49
  if (existing)
65
50
  return existing;
66
- const pending = compileGoParser(compiler.binary, this.path, source, invocation.maxOutputBytes, deadline).catch(error => {
67
- goParsers.delete(key);
51
+ const pending = cachedGoParser(key, deadline, () => compileGoParser(compiler.binary, this.path, source, invocation.maxOutputBytes, deadline), root).catch(error => {
52
+ goParsers.delete(processKey);
68
53
  throw error;
69
54
  });
70
- goParsers.set(key, pending);
55
+ goParsers.set(processKey, pending);
71
56
  return pending;
72
57
  }
73
58
  }
@@ -76,7 +61,7 @@ let goHome;
76
61
  function goProcessHome() {
77
62
  if (goHome !== undefined)
78
63
  return goHome;
79
- const home = mkdtempSync(join(tmpdir(), 'repometry-go-parser-'));
64
+ const home = createToolHome('repometry-go-parser-');
80
65
  goHome = home;
81
66
  process.once('exit', () => {
82
67
  try {
@@ -86,32 +71,6 @@ function goProcessHome() {
86
71
  });
87
72
  return home;
88
73
  }
89
- async function findGoCompiler(path, version) {
90
- const name = process.platform === 'win32' ? 'go.exe' : 'go';
91
- for (const directory of path.split(delimiter).filter(isAbsolute)) {
92
- const binary = join(directory, name);
93
- let resolved;
94
- try {
95
- resolved = await realpath(binary);
96
- if (!(await stat(resolved)).isFile())
97
- continue;
98
- await access(resolved, constants.X_OK);
99
- }
100
- catch {
101
- continue;
102
- }
103
- return { binary, resolved, version: version ?? await probeGoVersion(binary, path) };
104
- }
105
- throw new Error('Could not find the host Go compiler');
106
- }
107
- async function probeGoVersion(binary, path) {
108
- const home = goProcessHome();
109
- const result = await runTool({ timeoutMs: 5_000, maxOutputBytes: 4_096 }, binary, ['version'], home, toolEnvironment(path, home));
110
- const output = Buffer.from(result.stdout).toString().trim() || Buffer.from(result.stderr).toString().trim();
111
- if (result.exitCode !== 0 || !output)
112
- throw new Error(toolFailure('Could not determine the host Go version', result.stderr));
113
- return output.match(/\bgo(\d+(?:\.\d+)+(?:[a-z][\w.-]*)?)/i)?.[1] ?? output;
114
- }
115
74
  async function compileGoParser(binary, path, source, maxOutputBytes, deadline) {
116
75
  const home = goProcessHome();
117
76
  const directory = await mkdtemp(join(home, 'build-'));
@@ -148,10 +107,6 @@ async function withinDeadline(result, deadline) {
148
107
  clearTimeout(timer);
149
108
  }
150
109
  }
151
- function toolEnvironment(PATH, HOME) {
152
- return { PATH, HOME, GOCACHE: join(HOME, 'go-cache'), GOENV: 'off', GO111MODULE: 'off',
153
- GOWORK: 'off', GOTOOLCHAIN: 'local', GOPROXY: 'off', GOSUMDB: 'off', CGO_ENABLED: '0' };
154
- }
155
110
  function runTool({ stdin, timeoutMs, maxOutputBytes }, binary, args, cwd, env) {
156
111
  return new Promise((resolve, reject) => {
157
112
  const child = execFile(binary, args, { cwd, env, timeout: timeoutMs, maxBuffer: maxOutputBytes,
@@ -0,0 +1,22 @@
1
+ interface HostTool {
2
+ readonly binary: string;
3
+ readonly resolved: string;
4
+ readonly bytes: number;
5
+ readonly modified: number;
6
+ }
7
+ export interface VersionedHostTool extends HostTool {
8
+ readonly version: string;
9
+ }
10
+ export declare function hostToolPath(): string;
11
+ export declare function probeHostTool(name: string, args: readonly string[], path: string): VersionedHostTool | {
12
+ readonly unavailableReason: string;
13
+ };
14
+ /**
15
+ * Creates a private home folder for a host tool, with go's telemetry off in it. With telemetry on, go leaves a process
16
+ * behind that writes to the home after the command ends, which makes the home's removal fail or brings the folder back.
17
+ * The mode file sits where go looks for its configuration on Linux and on macOS. On Windows go finds no configuration
18
+ * folder in this environment, which turns telemetry off as well.
19
+ */
20
+ export declare function createToolHome(prefix: string): string;
21
+ export declare function toolEnvironment(PATH: string, HOME: string): NodeJS.ProcessEnv;
22
+ export {};
@@ -0,0 +1,87 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { accessSync, constants, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { delimiter, isAbsolute, join } from 'node:path';
5
+ import { toolFailure } from './failure.js';
6
+ export function hostToolPath() {
7
+ return (process.env.PATH ?? '').split(delimiter).filter(isAbsolute).join(delimiter);
8
+ }
9
+ export function probeHostTool(name, args, path) {
10
+ const tool = findHostTool(name, path);
11
+ if (!tool)
12
+ return { unavailableReason: `${name} not found on PATH` };
13
+ const home = createToolHome('repometry-tool-version-');
14
+ try {
15
+ const result = spawnSync(tool.binary, args, { cwd: home, env: toolEnvironment(path, home), encoding: 'utf8',
16
+ timeout: 5_000, maxBuffer: 4_096, killSignal: 'SIGKILL', windowsHide: true });
17
+ const output = result.stdout?.trim() || result.stderr?.trim();
18
+ const version = result.status === 0 && !result.error
19
+ ? output?.match(/\b(?:go|Python\s+)(\d+(?:\.\d+)+(?:[a-z][\w.-]*)?)/i)?.[1] : undefined;
20
+ return version === undefined ? { unavailableReason: versionFailure(name, result) } : { ...tool, version };
21
+ }
22
+ finally {
23
+ rmSync(home, { recursive: true, force: true });
24
+ }
25
+ }
26
+ function findHostTool(name, path) {
27
+ const executable = process.platform === 'win32' ? name + '.exe' : name;
28
+ let inaccessible;
29
+ for (const directory of path.split(delimiter).filter(isAbsolute)) {
30
+ const tool = inspectExecutable(join(directory, executable));
31
+ if (!tool)
32
+ continue;
33
+ try {
34
+ accessSync(tool.resolved, constants.X_OK);
35
+ return tool;
36
+ }
37
+ catch {
38
+ inaccessible ??= tool;
39
+ }
40
+ }
41
+ return inaccessible;
42
+ }
43
+ function inspectExecutable(binary) {
44
+ try {
45
+ const resolved = realpathSync(binary);
46
+ const info = statSync(resolved);
47
+ if (info.isFile())
48
+ return { binary, resolved, bytes: info.size, modified: info.mtimeMs };
49
+ }
50
+ catch {
51
+ // Continue searching when this path entry does not contain the tool.
52
+ }
53
+ }
54
+ function versionFailure(name, result) {
55
+ const message = `${name} version check failed`;
56
+ if (result.error) {
57
+ const code = 'code' in result.error ? result.error.code : result.error.name;
58
+ return `${message}: ${String(code)}`;
59
+ }
60
+ const output = result.stderr?.trim() || result.stdout?.trim();
61
+ const firstLine = output?.split(/\r?\n/, 1)[0];
62
+ if (firstLine)
63
+ return toolFailure(message, Buffer.from(firstLine)).replace('\n', ': ');
64
+ if (result.signal)
65
+ return `${message}: terminated by ${result.signal}`;
66
+ return result.status === 0 ? `${message}: no version output` : `${message}: exit status ${result.status}`;
67
+ }
68
+ /**
69
+ * Creates a private home folder for a host tool, with go's telemetry off in it. With telemetry on, go leaves a process
70
+ * behind that writes to the home after the command ends, which makes the home's removal fail or brings the folder back.
71
+ * The mode file sits where go looks for its configuration on Linux and on macOS. On Windows go finds no configuration
72
+ * folder in this environment, which turns telemetry off as well.
73
+ */
74
+ export function createToolHome(prefix) {
75
+ const home = mkdtempSync(join(tmpdir(), prefix));
76
+ for (const configuration of ['.config', join('Library', 'Application Support')]) {
77
+ const telemetry = join(home, configuration, 'go', 'telemetry');
78
+ mkdirSync(telemetry, { recursive: true });
79
+ writeFileSync(join(telemetry, 'mode'), 'off');
80
+ }
81
+ return home;
82
+ }
83
+ export function toolEnvironment(PATH, HOME) {
84
+ return { PATH, HOME, GOCACHE: join(HOME, 'go-cache'), GOENV: 'off', GO111MODULE: 'off',
85
+ GOWORK: 'off', GOTOOLCHAIN: 'local', GOPROXY: 'off', GOSUMDB: 'off', CGO_ENABLED: '0' };
86
+ }
87
+ //# sourceMappingURL=host-tool.js.map
@@ -1,4 +1,16 @@
1
1
  import type { Invocation } from './arguments.js';
2
+ export declare function parseConfig(value: unknown): {
3
+ exclude: readonly string[];
4
+ ignore: readonly import("../index.js").FindingIgnoreRule[];
5
+ plugins: readonly import("../core/engine/plugin.js").Plugin[];
6
+ imports: readonly string[];
7
+ reports: readonly string[];
8
+ sources: string | undefined;
9
+ branch: string | undefined;
10
+ minCoverage: string | undefined;
11
+ minLines: string | undefined;
12
+ maxNewIssues: string | undefined;
13
+ };
2
14
  /** The configuration file in effect, or undefined under --no-config. */
3
15
  export declare function configFile(root: string, input: Invocation): string | undefined;
4
16
  export declare function readConfig(root: string, input: Invocation): Promise<{
@@ -13,3 +25,4 @@ export declare function readConfig(root: string, input: Invocation): Promise<{
13
25
  minLines: string | undefined;
14
26
  maxNewIssues: string | undefined;
15
27
  }>;
28
+ export declare function readConfigValue(root: string, input: Invocation): Promise<unknown>;
@@ -6,7 +6,7 @@ import { readProcessPlugins } from '../compose/process-plugins.js';
6
6
  import { invocationDirectory } from './store.js';
7
7
  const keys = new Set(['$schema', 'exclude', 'ignore', 'imports', 'reports', 'sources', 'branch',
8
8
  'minCoverage', 'minLines', 'maxNewIssues', 'plugins']);
9
- function parseConfig(value) {
9
+ export function parseConfig(value) {
10
10
  if (!isRecord(value) || Object.keys(value).some(key => !keys.has(key)))
11
11
  throw new Error('Invalid Repometry JSON configuration');
12
12
  string(value.$schema, '$schema');
@@ -27,20 +27,23 @@ export function configFile(root, input) {
27
27
  return explicit === undefined ? resolve(root, 'repometry.config.json') : resolve(invocationDirectory(input), explicit);
28
28
  }
29
29
  export async function readConfig(root, input) {
30
+ return parseConfig(await readConfigValue(root, input));
31
+ }
32
+ export async function readConfigValue(root, input) {
30
33
  const explicit = input.text('config');
31
34
  const file = configFile(root, input);
32
35
  if (file === undefined)
33
- return parseConfig({});
36
+ return {};
34
37
  let json;
35
38
  try {
36
39
  json = await readFile(file, 'utf8');
37
40
  }
38
41
  catch (error) {
39
42
  if (explicit === undefined && error instanceof Error && 'code' in error && error.code === 'ENOENT')
40
- return parseConfig({});
43
+ return {};
41
44
  throw error;
42
45
  }
43
- return parseConfig(JSON.parse(json));
46
+ return JSON.parse(json);
44
47
  }
45
48
  function list(value, key) {
46
49
  if (value === undefined)
@@ -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