repometry 0.10.0 → 0.11.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 (174) hide show
  1. package/README.md +5 -3
  2. package/package.json +1 -1
  3. package/target/main/resources/config/process-plugins-v1.schema.json +22 -0
  4. package/target/main/resources/report/json/config-v1.schema.json +125 -2
  5. package/target/main/resources/report/json/file-metrics-v1.schema.json +23 -1
  6. package/target/main/resources/report/json/pull-review-v2.schema.json +100 -0
  7. package/target/main/ts/api/cache/root.d.ts +3 -0
  8. package/target/main/ts/api/cache/root.js +21 -0
  9. package/target/main/ts/api/gh/github.d.ts +0 -4
  10. package/target/main/ts/api/gh/github.js +3 -33
  11. package/target/main/ts/api/git/blob-batch.js +2 -1
  12. package/target/main/ts/api/git/blob-history.d.ts +20 -0
  13. package/target/main/ts/api/git/blob-history.js +54 -0
  14. package/target/main/ts/api/git/commit-metadata.d.ts +0 -1
  15. package/target/main/ts/api/git/commit-metadata.js +1 -10
  16. package/target/main/ts/api/git/git-executable.d.ts +1 -0
  17. package/target/main/ts/api/git/git-executable.js +31 -0
  18. package/target/main/ts/api/git/git.d.ts +8 -1
  19. package/target/main/ts/api/git/git.js +58 -61
  20. package/target/main/ts/api/git/inspection-source.d.ts +2 -1
  21. package/target/main/ts/api/git/inspection-source.js +3 -2
  22. package/target/main/ts/api/git/local-sources.js +3 -2
  23. package/target/main/ts/api/git/source-cache.d.ts +0 -2
  24. package/target/main/ts/api/git/source-cache.js +1 -16
  25. package/target/main/ts/api/import/cobertura.d.ts +2 -0
  26. package/target/main/ts/api/import/cobertura.js +160 -0
  27. package/target/main/ts/api/import/coverage-xml.d.ts +7 -0
  28. package/target/main/ts/api/import/coverage-xml.js +135 -0
  29. package/target/main/ts/api/import/lcov-files.d.ts +3 -1
  30. package/target/main/ts/api/import/lcov-files.js +23 -4
  31. package/target/main/ts/api/process/go-parser-cache.d.ts +1 -0
  32. package/target/main/ts/api/process/go-parser-cache.js +71 -0
  33. package/target/main/ts/api/process/go-parser-files.d.ts +5 -0
  34. package/target/main/ts/api/process/go-parser-files.js +65 -0
  35. package/target/main/ts/api/process/host-language-runner.d.ts +3 -5
  36. package/target/main/ts/api/process/host-language-runner.js +21 -66
  37. package/target/main/ts/api/process/host-tool.d.ts +22 -0
  38. package/target/main/ts/api/process/host-tool.js +87 -0
  39. package/target/main/ts/cli/arguments.js +2 -4
  40. package/target/main/ts/cli/config.d.ts +20 -3
  41. package/target/main/ts/cli/config.js +43 -10
  42. package/target/main/ts/cli/imports.d.ts +1 -0
  43. package/target/main/ts/cli/imports.js +6 -2
  44. package/target/main/ts/cli/main.js +66 -215
  45. package/target/main/ts/cli/range-inspection.d.ts +25 -0
  46. package/target/main/ts/cli/range-inspection.js +29 -0
  47. package/target/main/ts/cli/range-jobs.d.ts +22 -0
  48. package/target/main/ts/cli/range-jobs.js +150 -0
  49. package/target/main/ts/cli/range-worker.d.ts +1 -0
  50. package/target/main/ts/cli/range-worker.js +36 -0
  51. package/target/main/ts/cli/reporting.d.ts +2 -7
  52. package/target/main/ts/cli/reporting.js +23 -37
  53. package/target/main/ts/compose/analysis-report.d.ts +1 -1
  54. package/target/main/ts/compose/analysis-report.js +8 -8
  55. package/target/main/ts/compose/analysis-results.d.ts +1 -1
  56. package/target/main/ts/compose/analysis-results.js +4 -6
  57. package/target/main/ts/compose/analysis-steps.d.ts +23 -0
  58. package/target/main/ts/compose/analysis-steps.js +215 -0
  59. package/target/main/ts/compose/analyze-snapshot.d.ts +1 -1
  60. package/target/main/ts/compose/analyze-snapshot.js +8 -12
  61. package/target/main/ts/compose/built-ins.d.ts +3 -0
  62. package/target/main/ts/compose/built-ins.js +5 -0
  63. package/target/main/ts/compose/diff-coverage.d.ts +2 -4
  64. package/target/main/ts/compose/diff-coverage.js +16 -13
  65. package/target/main/ts/compose/history-cache.d.ts +3 -1
  66. package/target/main/ts/compose/history-cache.js +2 -0
  67. package/target/main/ts/compose/inspect.d.ts +6 -9
  68. package/target/main/ts/compose/inspect.js +11 -12
  69. package/target/main/ts/compose/languages.d.ts +4 -1
  70. package/target/main/ts/compose/languages.js +9 -6
  71. package/target/main/ts/compose/native-language-plugins.d.ts +0 -1
  72. package/target/main/ts/compose/native-language-plugins.js +11 -17
  73. package/target/main/ts/compose/phases.d.ts +126 -0
  74. package/target/main/ts/compose/phases.js +154 -0
  75. package/target/main/ts/compose/plugin-list.d.ts +8 -2
  76. package/target/main/ts/compose/plugin-list.js +4 -13
  77. package/target/main/ts/compose/process-plugins.js +1 -1
  78. package/target/main/ts/compose/review.d.ts +2 -4
  79. package/target/main/ts/compose/review.js +10 -9
  80. package/target/main/ts/compose/sources.d.ts +1 -2
  81. package/target/main/ts/compose/sources.js +7 -7
  82. package/target/main/ts/core/engine/execute.d.ts +4 -1
  83. package/target/main/ts/core/engine/execute.js +1 -1
  84. package/target/main/ts/core/engine/manifest.d.ts +0 -1
  85. package/target/main/ts/core/engine/manifest.js +9 -13
  86. package/target/main/ts/core/engine/plugin.d.ts +1 -1
  87. package/target/main/ts/core/engine/report-products.js +3 -2
  88. package/target/main/ts/core/model/changes.d.ts +2 -0
  89. package/target/main/ts/core/model/changes.js +5 -1
  90. package/target/main/ts/core/model/clone-source.d.ts +2 -0
  91. package/target/main/ts/core/model/clone-source.js +4 -0
  92. package/target/main/ts/core/model/code-structure.d.ts +4 -1
  93. package/target/main/ts/core/model/code-structure.js +3 -1
  94. package/target/main/ts/core/model/coverage-input.d.ts +12 -0
  95. package/target/main/ts/core/model/coverage-input.js +11 -0
  96. package/target/main/ts/core/model/diff-coverage.d.ts +2 -0
  97. package/target/main/ts/core/model/diff-coverage.js +9 -1
  98. package/target/main/ts/core/model/language.d.ts +28 -0
  99. package/target/main/ts/core/model/language.js +25 -1
  100. package/target/main/ts/core/model/quality-summary.js +1 -1
  101. package/target/main/ts/core/model/report.d.ts +0 -2
  102. package/target/main/ts/core/model/report.js +0 -20
  103. package/target/main/ts/core/ports/tool-runner.d.ts +13 -0
  104. package/target/main/ts/core/usecases/inspect.d.ts +1 -2
  105. package/target/main/ts/core/usecases/review.js +11 -3
  106. package/target/main/ts/index.d.ts +6 -33
  107. package/target/main/ts/index.js +3 -18
  108. package/target/main/ts/plugin.d.ts +7 -3
  109. package/target/main/ts/plugin.js +3 -0
  110. package/target/main/ts/plugins/built-in.d.ts +6 -0
  111. package/target/main/ts/plugins/built-in.js +39 -0
  112. package/target/main/ts/plugins/coverage/coverage.d.ts +3 -24
  113. package/target/main/ts/plugins/coverage/coverage.js +8 -11
  114. package/target/main/ts/plugins/coverage/diff-coverage.d.ts +1 -5
  115. package/target/main/ts/plugins/coverage/diff-coverage.js +5 -14
  116. package/target/main/ts/plugins/duplication/duplication.d.ts +1 -3
  117. package/target/main/ts/plugins/duplication/duplication.js +2 -6
  118. package/target/main/ts/plugins/language-js/babel-provider.js +3 -2
  119. package/target/main/ts/plugins/language-js/structural-observations.js +1 -1
  120. package/target/main/ts/plugins/language-js/syntax.d.ts +2 -0
  121. package/target/main/ts/plugins/language-js/syntax.js +11 -0
  122. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -8
  123. package/target/main/ts/plugins/maintainability/maintainability.js +4 -10
  124. package/target/main/ts/plugins/source/forges.js +1 -1
  125. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -1
  126. package/target/main/ts/report/html/app/viewer-languages.js +11 -1
  127. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -1
  128. package/target/main/ts/report/html/app/viewer-source-view.js +2 -2
  129. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +7 -6
  130. package/target/main/ts/report/html/app/viewer-tokenizer.js +72 -71
  131. package/target/main/ts/report/html/site/export-site.d.ts +1 -5
  132. package/target/main/ts/report/html/site/export-site.js +2 -6
  133. package/target/main/ts/report/html/site/projects.d.ts +1 -3
  134. package/target/main/ts/report/html/site/projects.js +2 -4
  135. package/target/main/ts/report/json/projections/commit-summary.js +5 -7
  136. package/target/main/ts/report/json/projections/file-metrics.js +1 -1
  137. package/target/main/ts/report/json/projections/inspection-context.d.ts +1 -0
  138. package/target/main/ts/report/json/projections/inspection-context.js +19 -1
  139. package/target/main/ts/report/json/projections/inspection-details.js +7 -2
  140. package/target/main/ts/report/json/projections/metric-values.d.ts +5 -0
  141. package/target/main/ts/report/json/projections/metric-values.js +9 -6
  142. package/target/main/ts/report/json/store/local-store.js +2 -0
  143. package/target/main/ts/report/json/store/replace-file.d.ts +1 -1
  144. package/target/main/ts/report/json/store/replace-file.js +24 -3
  145. package/target/main/ts/report/json/store/store-check.js +10 -1
  146. package/target/main/ts/report/json/validation/metabranch.d.ts +1 -1
  147. package/target/main/ts/report/json/validation/metabranch.js +6 -3
  148. package/target/main/ts/report/json/wire/file-metrics-model.d.ts +3 -1
  149. package/target/main/ts/report.d.ts +13 -1
  150. package/target/main/ts/report.js +7 -1
  151. package/target/main/ts/api/git/metabranch-worktree.d.ts +0 -1
  152. package/target/main/ts/api/git/metabranch-worktree.js +0 -35
  153. package/target/main/ts/api/worker/remote-executor.d.ts +0 -2
  154. package/target/main/ts/api/worker/remote-executor.js +0 -46
  155. package/target/main/ts/api/worker/worker-protocol.d.ts +0 -7
  156. package/target/main/ts/api/worker/worker-protocol.js +0 -127
  157. package/target/main/ts/api/worker/worker.d.ts +0 -5
  158. package/target/main/ts/api/worker/worker.js +0 -86
  159. package/target/main/ts/compose/analysis-files.d.ts +0 -15
  160. package/target/main/ts/compose/analysis-files.js +0 -129
  161. package/target/main/ts/compose/analysis-imports.d.ts +0 -7
  162. package/target/main/ts/compose/analysis-imports.js +0 -36
  163. package/target/main/ts/compose/analysis-repository.d.ts +0 -7
  164. package/target/main/ts/compose/analysis-repository.js +0 -99
  165. package/target/main/ts/compose/analysis-sources.d.ts +0 -48
  166. package/target/main/ts/compose/analysis-sources.js +0 -54
  167. package/target/main/ts/compose/prepare-metabranch.d.ts +0 -9
  168. package/target/main/ts/compose/prepare-metabranch.js +0 -17
  169. package/target/main/ts/compose/security-plugins.d.ts +0 -1
  170. package/target/main/ts/compose/security-plugins.js +0 -7
  171. package/target/main/ts/core/usecases/compare.d.ts +0 -6
  172. package/target/main/ts/core/usecases/compare.js +0 -189
  173. package/target/main/ts/report/json/store/components.d.ts +0 -2
  174. package/target/main/ts/report/json/store/components.js +0 -32
@@ -0,0 +1,71 @@
1
+ import { mkdir, rmdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { cacheRoot, goParserCacheDirectory } from '../cache/root.js';
5
+ import { errorCode, privateDirectory, publishParser, readCachedParser } from './go-parser-files.js';
6
+ const staleLockMs = 120_000;
7
+ export async function cachedGoParser(key, deadline, compile, root = cacheRoot()) {
8
+ const cache = join(root, goParserCacheDirectory);
9
+ try {
10
+ await mkdir(cache, { recursive: true, mode: 0o700 });
11
+ await privateDirectory(cache);
12
+ return await readOrBuild(cache, key, deadline, compile);
13
+ }
14
+ catch (error) {
15
+ const reason = error instanceof Error ? error.message : String(error);
16
+ throw new Error(`Go parser cache ${cache}: ${reason}`, { cause: error });
17
+ }
18
+ }
19
+ async function readOrBuild(cache, key, deadline, compile) {
20
+ const destination = join(cache, key);
21
+ const lock = destination + '.lock';
22
+ for (;;) {
23
+ const parser = await readCachedParser(destination);
24
+ if (parser)
25
+ return parser;
26
+ if (await acquireLock(lock))
27
+ return buildWithLock(cache, destination, lock, compile);
28
+ const remaining = Math.ceil(deadline - performance.now());
29
+ if (remaining <= 0)
30
+ throw new Error('Tool timed out');
31
+ await delay(Math.min(50, remaining));
32
+ }
33
+ }
34
+ async function acquireLock(lock) {
35
+ try {
36
+ await mkdir(lock, { mode: 0o700 });
37
+ return true;
38
+ }
39
+ catch (error) {
40
+ if (errorCode(error) !== 'EEXIST')
41
+ throw error;
42
+ await removeStaleLock(lock);
43
+ return false;
44
+ }
45
+ }
46
+ async function removeStaleLock(lock) {
47
+ try {
48
+ const info = await privateDirectory(lock);
49
+ if (Date.now() - info.mtimeMs > staleLockMs)
50
+ await rmdir(lock);
51
+ }
52
+ catch (error) {
53
+ if (errorCode(error) !== 'ENOENT')
54
+ throw error;
55
+ }
56
+ }
57
+ async function buildWithLock(cache, destination, lock, compile) {
58
+ try {
59
+ return await readCachedParser(destination) ?? await publishParser(cache, destination, await compile());
60
+ }
61
+ finally {
62
+ try {
63
+ await rmdir(lock);
64
+ }
65
+ catch (error) {
66
+ if (errorCode(error) !== 'ENOENT')
67
+ throw error;
68
+ }
69
+ }
70
+ }
71
+ //# sourceMappingURL=go-parser-cache.js.map
@@ -0,0 +1,5 @@
1
+ import type { Stats } from 'node:fs';
2
+ export declare function errorCode(error: unknown): unknown;
3
+ export declare function privateDirectory(directory: string): Promise<Stats>;
4
+ export declare function readCachedParser(directory: string): Promise<string | undefined>;
5
+ export declare function publishParser(cache: string, destination: string, local: string): Promise<string>;
@@ -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
@@ -8,11 +8,9 @@ export function flag(description, short) {
8
8
  const globals = {
9
9
  help: flag('Show command help.', 'h'),
10
10
  version: flag('Show the installed version.', 'V'),
11
- repo: option('DIR', 'Run in the given repository.', { short: 'C' }),
12
- store: option('PATH|git:REF', 'Select a report store.'),
13
11
  };
14
12
  export async function dispatch(commands, input, version) {
15
- const [name, ...rest] = placeGlobalOptions(input);
13
+ const [name, ...rest] = placeLeadingOptions(input);
16
14
  if (name === '--version' || name === '-V') {
17
15
  process.stdout.write(version + '\n');
18
16
  return 0;
@@ -59,7 +57,7 @@ export async function dispatch(commands, input, version) {
59
57
  });
60
58
  return result ?? 0;
61
59
  }
62
- function placeGlobalOptions(input) {
60
+ function placeLeadingOptions(input) {
63
61
  const leading = [];
64
62
  let index = 0;
65
63
  while (index < input.length) {
@@ -1,4 +1,18 @@
1
+ import type { Component } from '../report/json/wire/component-model.js';
1
2
  import type { Invocation } from './arguments.js';
3
+ export declare function parseConfig(value: unknown): {
4
+ exclude: readonly string[];
5
+ ignore: readonly import("../index.js").FindingIgnoreRule[];
6
+ plugins: readonly import("../core/engine/plugin.js").Plugin[];
7
+ imports: readonly string[];
8
+ reports: readonly string[];
9
+ sources: string | undefined;
10
+ branch: string | undefined;
11
+ components: readonly Component[];
12
+ minCoverage: number | undefined;
13
+ minLines: number | undefined;
14
+ maxNewIssues: number | undefined;
15
+ };
2
16
  /** The configuration file in effect, or undefined under --no-config. */
3
17
  export declare function configFile(root: string, input: Invocation): string | undefined;
4
18
  export declare function readConfig(root: string, input: Invocation): Promise<{
@@ -9,7 +23,10 @@ export declare function readConfig(root: string, input: Invocation): Promise<{
9
23
  reports: readonly string[];
10
24
  sources: string | undefined;
11
25
  branch: string | undefined;
12
- minCoverage: string | undefined;
13
- minLines: string | undefined;
14
- maxNewIssues: string | undefined;
26
+ components: readonly Component[];
27
+ minCoverage: number | undefined;
28
+ minLines: number | undefined;
29
+ maxNewIssues: number | undefined;
15
30
  }>;
31
+ export declare function readConfigValue(root: string, input: Invocation): Promise<unknown>;
32
+ export declare function listOption(input: Invocation, name: string, configured: readonly string[]): readonly string[];
@@ -5,15 +5,16 @@ import { normalizeProfile } from '../core/profile/profile.js';
5
5
  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
- 'minCoverage', 'minLines', 'maxNewIssues', 'plugins']);
9
- function parseConfig(value) {
8
+ 'minCoverage', 'minLines', 'maxNewIssues', 'plugins', 'components']);
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');
13
13
  const profile = normalizeProfile({ exclude: value.exclude, ignore: value.ignore });
14
14
  return { ...profile, plugins: readProcessPlugins(value.plugins), imports: list(value.imports, 'imports'), reports: list(value.reports, 'reports'),
15
15
  sources: string(value.sources, 'sources'), branch: string(value.branch, 'branch'),
16
- minCoverage: number(value.minCoverage, 'minCoverage'), minLines: number(value.minLines, 'minLines'),
16
+ components: parseComponents(value.components),
17
+ minCoverage: number(value.minCoverage, 'minCoverage', 100), minLines: number(value.minLines, 'minLines'),
17
18
  maxNewIssues: number(value.maxNewIssues, 'maxNewIssues') };
18
19
  }
19
20
  /** The configuration file in effect, or undefined under --no-config. */
@@ -27,20 +28,27 @@ export function configFile(root, input) {
27
28
  return explicit === undefined ? resolve(root, 'repometry.config.json') : resolve(invocationDirectory(input), explicit);
28
29
  }
29
30
  export async function readConfig(root, input) {
31
+ return parseConfig(await readConfigValue(root, input));
32
+ }
33
+ export async function readConfigValue(root, input) {
30
34
  const explicit = input.text('config');
31
35
  const file = configFile(root, input);
32
36
  if (file === undefined)
33
- return parseConfig({});
37
+ return {};
34
38
  let json;
35
39
  try {
36
40
  json = await readFile(file, 'utf8');
37
41
  }
38
42
  catch (error) {
39
43
  if (explicit === undefined && error instanceof Error && 'code' in error && error.code === 'ENOENT')
40
- return parseConfig({});
44
+ return {};
41
45
  throw error;
42
46
  }
43
- return parseConfig(JSON.parse(json));
47
+ return JSON.parse(json);
48
+ }
49
+ export function listOption(input, name, configured) {
50
+ const typed = input.many(name);
51
+ return typed.length ? typed : configured;
44
52
  }
45
53
  function list(value, key) {
46
54
  if (value === undefined)
@@ -56,11 +64,36 @@ function string(value, key) {
56
64
  throw new Error(`Config ${key} must be a nonempty string`);
57
65
  return value;
58
66
  }
59
- function number(value, key) {
67
+ function number(value, key, max) {
60
68
  if (value === undefined)
61
69
  return undefined;
62
- if (typeof value !== 'number' || !Number.isFinite(value))
63
- throw new Error(`Config ${key} must be a number`);
64
- return String(value);
70
+ if (typeof value !== 'number' || value < 0 || (max === undefined
71
+ ? !Number.isSafeInteger(value) : !Number.isFinite(value) || value > max)) {
72
+ throw new Error('Invalid config ' + key + (max === undefined ? ': expected a non-negative integer' : ': expected a number from 0 to ' + max));
73
+ }
74
+ return value;
75
+ }
76
+ function parseComponents(config) {
77
+ if (config === undefined)
78
+ return [];
79
+ if (!Array.isArray(config))
80
+ throw new Error('Expected an array of component definitions');
81
+ const names = new Set();
82
+ return config.map((entry) => {
83
+ if (!isRecord(entry) || typeof entry.name !== 'string' || !entry.name.trim() || entry.name.length > 100
84
+ || !Array.isArray(entry.pathGlobs) || entry.pathGlobs.length === 0 || !entry.pathGlobs.every(validPattern)
85
+ || (entry.description !== undefined && typeof entry.description !== 'string')) {
86
+ throw new Error('Each component requires a name and one or more root-relative pathGlobs');
87
+ }
88
+ const name = entry.name.trim();
89
+ if (names.has(name))
90
+ throw new Error(`Duplicate component name: ${name}`);
91
+ names.add(name);
92
+ return { name, pathGlobs: [...new Set(entry.pathGlobs)], description: entry.description };
93
+ });
94
+ }
95
+ function validPattern(pattern) {
96
+ return typeof pattern === 'string' && !/^[A-Za-z]:|[\\\0]/.test(pattern)
97
+ && pattern.split('/').every(part => part !== '' && part !== '.' && part !== '..');
65
98
  }
66
99
  //# sourceMappingURL=config.js.map
@@ -4,5 +4,6 @@ export declare const importerIds: string[];
4
4
  export declare function readInputs(base: string, inputs: readonly string[]): {
5
5
  lcov: string[] | undefined;
6
6
  goCover: string[] | undefined;
7
+ cobertura: string[] | undefined;
7
8
  findings: FindingInput[];
8
9
  };
@@ -6,11 +6,12 @@ const scanners = {
6
6
  eslint: { format: 'eslint', category: 'lint' },
7
7
  osv: { format: 'osv', category: 'dependency' },
8
8
  };
9
- export const importerIds = ['lcov', 'go-cover', ...Object.keys(scanners)];
9
+ export const importerIds = ['lcov', 'go-cover', 'cobertura', ...Object.keys(scanners)];
10
10
  /** Typed imports resolve against the invocation directory, imports from the config against the repository root. */
11
11
  export function readInputs(base, inputs) {
12
12
  const lcov = [];
13
13
  const goCover = [];
14
+ const cobertura = [];
14
15
  const findings = [];
15
16
  for (const value of inputs) {
16
17
  const equal = value.indexOf('=');
@@ -22,12 +23,15 @@ export function readInputs(base, inputs) {
22
23
  lcov.push(resolve(base, file));
23
24
  else if (format === 'go-cover')
24
25
  goCover.push(resolve(base, file));
26
+ else if (format === 'cobertura')
27
+ cobertura.push(resolve(base, file));
25
28
  else {
26
29
  if (!Object.hasOwn(scanners, format))
27
30
  throw new Error(`Unknown import format: ${format}. Choose ${importerIds.join(', ')}.`);
28
31
  findings.push({ ...scanners[format], file: resolve(base, file) });
29
32
  }
30
33
  }
31
- return { lcov: lcov.length ? lcov : undefined, goCover: goCover.length ? goCover : undefined, findings };
34
+ return { lcov: lcov.length ? lcov : undefined, goCover: goCover.length ? goCover : undefined,
35
+ cobertura: cobertura.length ? cobertura : undefined, findings };
32
36
  }
33
37
  //# sourceMappingURL=imports.js.map