repometry 0.6.2 → 0.8.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 (153) hide show
  1. package/README.md +3 -0
  2. package/package.json +1 -1
  3. package/target/main/resources/config/process-plugins-v1.schema.json +79 -0
  4. package/target/main/resources/languages/go/parser.go +602 -0
  5. package/target/main/resources/languages/python/parser.py +312 -0
  6. package/target/main/resources/report/json/report-v2.schema.json +21 -1
  7. package/target/main/resources/report/json/repository-summary-v1.schema.json +9 -0
  8. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +12 -3
  9. package/target/main/resources/viewer/files.css +7 -0
  10. package/target/main/resources/viewer/index.html +1 -1
  11. package/target/main/resources/viewer/styles.css +1 -0
  12. package/target/main/ts/api/git/git-reader.d.ts +10 -2
  13. package/target/main/ts/api/git/git-reader.js +74 -35
  14. package/target/main/ts/api/git/git.d.ts +19 -1
  15. package/target/main/ts/api/git/git.js +97 -7
  16. package/target/main/ts/api/import/go-cover.d.ts +13 -0
  17. package/target/main/ts/api/import/go-cover.js +150 -0
  18. package/target/main/ts/api/import/lcov-files.d.ts +6 -1
  19. package/target/main/ts/api/import/lcov-files.js +27 -7
  20. package/target/main/ts/api/process/docker-tool-runner.js +5 -21
  21. package/target/main/ts/api/process/host-language-runner.d.ts +13 -0
  22. package/target/main/ts/api/process/host-language-runner.js +176 -0
  23. package/target/main/ts/api/process/plugin.d.ts +4 -1
  24. package/target/main/ts/api/process/plugin.js +7 -3
  25. package/target/main/ts/api/process/tool-snapshot.d.ts +3 -0
  26. package/target/main/ts/api/process/tool-snapshot.js +26 -0
  27. package/target/main/ts/cli/config.d.ts +1 -0
  28. package/target/main/ts/cli/config.js +3 -2
  29. package/target/main/ts/cli/imports.d.ts +1 -0
  30. package/target/main/ts/cli/imports.js +5 -2
  31. package/target/main/ts/cli/main.js +76 -27
  32. package/target/main/ts/cli/reporting.js +3 -3
  33. package/target/main/ts/compose/analysis-files.d.ts +3 -1
  34. package/target/main/ts/compose/analysis-files.js +46 -12
  35. package/target/main/ts/compose/analysis-imports.js +4 -2
  36. package/target/main/ts/compose/analysis-report.d.ts +1 -0
  37. package/target/main/ts/compose/analysis-report.js +20 -15
  38. package/target/main/ts/compose/analysis-repository.d.ts +2 -1
  39. package/target/main/ts/compose/analysis-repository.js +42 -4
  40. package/target/main/ts/compose/analysis-results.d.ts +4 -1
  41. package/target/main/ts/compose/analysis-results.js +3 -0
  42. package/target/main/ts/compose/analysis-sources.d.ts +5 -0
  43. package/target/main/ts/compose/analysis-sources.js +11 -3
  44. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -1
  45. package/target/main/ts/compose/analyze-snapshot.js +5 -3
  46. package/target/main/ts/compose/diff-coverage.d.ts +2 -1
  47. package/target/main/ts/compose/diff-coverage.js +8 -6
  48. package/target/main/ts/compose/history-cache.d.ts +29 -0
  49. package/target/main/ts/compose/history-cache.js +57 -0
  50. package/target/main/ts/compose/inspect.d.ts +6 -1
  51. package/target/main/ts/compose/inspect.js +10 -10
  52. package/target/main/ts/compose/inspection-coverage.d.ts +9 -0
  53. package/target/main/ts/compose/inspection-coverage.js +9 -0
  54. package/target/main/ts/compose/languages.d.ts +6 -1
  55. package/target/main/ts/compose/languages.js +23 -7
  56. package/target/main/ts/compose/native-language-plugins.d.ts +6 -0
  57. package/target/main/ts/compose/native-language-plugins.js +40 -0
  58. package/target/main/ts/compose/plugin-list.d.ts +7 -3
  59. package/target/main/ts/compose/plugin-list.js +13 -3
  60. package/target/main/ts/compose/prepare-metabranch.js +1 -1
  61. package/target/main/ts/compose/process-plugins.d.ts +2 -0
  62. package/target/main/ts/compose/process-plugins.js +64 -0
  63. package/target/main/ts/compose/review.d.ts +1 -2
  64. package/target/main/ts/compose/review.js +2 -2
  65. package/target/main/ts/compose/structure-measures.d.ts +5 -0
  66. package/target/main/ts/compose/structure-measures.js +57 -0
  67. package/target/main/ts/core/engine/manifest.js +5 -1
  68. package/target/main/ts/core/engine/plan.js +5 -6
  69. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  70. package/target/main/ts/core/model/clone-source.js +0 -1
  71. package/target/main/ts/core/model/code-structure.d.ts +14 -9
  72. package/target/main/ts/core/model/code-structure.js +23 -10
  73. package/target/main/ts/core/model/file-types.d.ts +1 -0
  74. package/target/main/ts/core/model/file-types.js +14 -3
  75. package/target/main/ts/core/model/language.d.ts +2 -0
  76. package/target/main/ts/core/model/plugin-data.d.ts +2 -0
  77. package/target/main/ts/core/model/quality-summary.d.ts +4 -0
  78. package/target/main/ts/core/model/quality-summary.js +55 -29
  79. package/target/main/ts/core/model/report.d.ts +6 -0
  80. package/target/main/ts/core/model/source.d.ts +2 -0
  81. package/target/main/ts/core/usecases/inspect.d.ts +1 -1
  82. package/target/main/ts/core/usecases/inspect.js +1 -1
  83. package/target/main/ts/plugin.d.ts +1 -1
  84. package/target/main/ts/plugins/coverage/coverage.d.ts +2 -1
  85. package/target/main/ts/plugins/coverage/coverage.js +40 -30
  86. package/target/main/ts/plugins/language-js/function-facts.d.ts +1 -1
  87. package/target/main/ts/plugins/language-js/function-facts.js +0 -1
  88. package/target/main/ts/plugins/language-js/js-security.js +25 -37
  89. package/target/main/ts/plugins/language-js/structural-observations.js +5 -4
  90. package/target/main/ts/plugins/maintainability/maintainability.d.ts +1 -1
  91. package/target/main/ts/plugins/maintainability/maintainability.js +9 -8
  92. package/target/main/ts/plugins/security/dockerfile.js +51 -52
  93. package/target/main/ts/plugins/structure/structure.js +2 -2
  94. package/target/main/ts/report/html/app/viewer-code-map.js +6 -5
  95. package/target/main/ts/report/html/app/viewer-columns.d.ts +2 -0
  96. package/target/main/ts/report/html/app/viewer-columns.js +9 -4
  97. package/target/main/ts/report/html/app/viewer-data.d.ts +2 -1
  98. package/target/main/ts/report/html/app/viewer-data.js +1 -1
  99. package/target/main/ts/report/html/app/viewer-file-aside.d.ts +5 -9
  100. package/target/main/ts/report/html/app/viewer-file-aside.js +18 -8
  101. package/target/main/ts/report/html/app/viewer-file-figures.d.ts +2 -0
  102. package/target/main/ts/report/html/app/viewer-file-figures.js +6 -1
  103. package/target/main/ts/report/html/app/viewer-hotspots.js +7 -5
  104. package/target/main/ts/report/html/app/viewer-inspection.js +1 -1
  105. package/target/main/ts/report/html/app/viewer-issue-group.js +2 -2
  106. package/target/main/ts/report/html/app/viewer-language-bar.d.ts +2 -0
  107. package/target/main/ts/report/html/app/viewer-language-bar.js +5 -1
  108. package/target/main/ts/report/html/app/viewer-languages.d.ts +3 -2
  109. package/target/main/ts/report/html/app/viewer-languages.js +14 -7
  110. package/target/main/ts/report/html/app/viewer-line-coverage.d.ts +4 -4
  111. package/target/main/ts/report/html/app/viewer-line-coverage.js +11 -24
  112. package/target/main/ts/report/html/app/viewer-map-scale.d.ts +1 -1
  113. package/target/main/ts/report/html/app/viewer-map-scale.js +1 -1
  114. package/target/main/ts/report/html/app/viewer-map-shape.d.ts +2 -2
  115. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +0 -3
  116. package/target/main/ts/report/html/app/viewer-metric-registry.js +0 -9
  117. package/target/main/ts/report/html/app/viewer-metrics-view.js +1 -4
  118. package/target/main/ts/report/html/app/viewer-metrics.d.ts +2 -0
  119. package/target/main/ts/report/html/app/viewer-metrics.js +5 -0
  120. package/target/main/ts/report/html/app/viewer-overview-cards.js +4 -1
  121. package/target/main/ts/report/html/app/viewer-overview-hotspots.js +2 -2
  122. package/target/main/ts/report/html/app/viewer-profile.js +22 -1
  123. package/target/main/ts/report/html/app/viewer-source-view.js +7 -6
  124. package/target/main/ts/report/html/app/viewer-table-cells.js +8 -2
  125. package/target/main/ts/report/html/app/viewer-table-rows.d.ts +2 -0
  126. package/target/main/ts/report/html/app/viewer-table-rows.js +7 -5
  127. package/target/main/ts/report/html/app/viewer-tokenizer.d.ts +2 -5
  128. package/target/main/ts/report/html/app/viewer-tokenizer.js +9 -12
  129. package/target/main/ts/report/html/app/viewer-totals.d.ts +6 -0
  130. package/target/main/ts/report/html/app/viewer-totals.js +11 -0
  131. package/target/main/ts/report/html/app/viewer-trend-data.d.ts +1 -1
  132. package/target/main/ts/report/html/app/viewer-trend-data.js +1 -1
  133. package/target/main/ts/report/html/app/viewer-trend-nav.js +3 -2
  134. package/target/main/ts/report/html/app/viewer.js +1 -7
  135. package/target/main/ts/report/json/projections/commit-summary.d.ts +1 -0
  136. package/target/main/ts/report/json/projections/commit-summary.js +10 -0
  137. package/target/main/ts/report/json/projections/file-metrics.js +56 -45
  138. package/target/main/ts/report/json/projections/inspection-details.js +33 -14
  139. package/target/main/ts/report/json/projections/metric-values.d.ts +1 -0
  140. package/target/main/ts/report/json/projections/metric-values.js +36 -3
  141. package/target/main/ts/report/json/store/directory.d.ts +3 -0
  142. package/target/main/ts/report/json/store/directory.js +19 -0
  143. package/target/main/ts/report/json/store/local-store.d.ts +14 -2
  144. package/target/main/ts/report/json/store/local-store.js +74 -60
  145. package/target/main/ts/report/json/store/object-store.d.ts +14 -0
  146. package/target/main/ts/report/json/store/object-store.js +73 -0
  147. package/target/main/ts/report/json/store/report-tree.d.ts +46 -0
  148. package/target/main/ts/report/json/store/report-tree.js +290 -0
  149. package/target/main/ts/report/json/store/store-check.d.ts +32 -0
  150. package/target/main/ts/report/json/store/store-check.js +144 -0
  151. package/target/main/ts/report/json/validation/report.d.ts +6 -1
  152. package/target/main/ts/report/json/validation/report.js +10 -4
  153. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +9 -1
@@ -1,5 +1,5 @@
1
1
  import { realpath } from 'node:fs/promises';
2
- import { execFile, spawnSync } from 'node:child_process';
2
+ import { execFile, spawn, spawnSync } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
4
  import { comparePaths, isExcludedDirectory, textLineCount, utf8 } from '../../core/model/snapshot.js';
5
5
  import { isClaimedText, maxClaimedFileBytes } from '../../core/model/source.js';
@@ -89,11 +89,100 @@ export async function gitTreeFiles(directory, commit, prefix, includeSize = fals
89
89
  }
90
90
  return entries;
91
91
  }
92
- export async function gitBlobText(directory, oid) {
93
- if (!oidPattern.test(oid))
94
- throw new Error('A full blob object ID is required');
95
- const result = await git('git', ['--no-replace-objects', 'cat-file', 'blob', oid], { cwd: directory, env, encoding: 'buffer', maxBuffer });
96
- return utf8(result.stdout);
92
+ /**
93
+ * Reads blobs named like `<tree>:<path>` through one long-lived `git cat-file --batch`: requests stream in and answers
94
+ * come back in order. A name Git cannot find reads as undefined. The process keeps Node alive only while it owes answers.
95
+ */
96
+ export class GitBlobReader {
97
+ directory;
98
+ child;
99
+ pending = [];
100
+ chunks = [];
101
+ constructor(directory) {
102
+ this.directory = directory;
103
+ }
104
+ read(names) {
105
+ return Promise.all(names.map(name => this.request(name, 'blob')));
106
+ }
107
+ /** The ID of the object a name resolves to, such as the tree of `<revision>^{tree}`. */
108
+ id(name) {
109
+ return this.request(name, 'id');
110
+ }
111
+ request(name, want) {
112
+ return new Promise((resolve, reject) => {
113
+ if (/[\r\n]/.test(name))
114
+ throw new Error('Invalid Git object name');
115
+ const child = this.child ?? this.start();
116
+ if (this.pending.length === 0)
117
+ setHeld(child, true);
118
+ this.pending.push({ name, want, resolve, reject });
119
+ child.stdin.write(`${name}\n`);
120
+ });
121
+ }
122
+ start() {
123
+ const child = spawn('git', ['--no-replace-objects', 'cat-file', '--batch'], { cwd: this.directory, env });
124
+ const errors = [];
125
+ child.stdout.on('data', (chunk) => this.receive(chunk));
126
+ child.stderr.on('data', (chunk) => errors.push(chunk));
127
+ const stop = (error) => this.stop(child, error);
128
+ child.on('error', stop);
129
+ child.stdin.on('error', stop);
130
+ child.on('close', () => stop(new Error(`git cat-file stopped: ${Buffer.concat(errors).toString('utf8').trim()}`)));
131
+ setHeld(child, false);
132
+ this.child = child;
133
+ return child;
134
+ }
135
+ receive(chunk) {
136
+ this.chunks.push(chunk);
137
+ let buffer = this.chunks.length === 1 ? chunk : Buffer.concat(this.chunks);
138
+ for (let request = this.pending[0]; request; request = this.pending[0]) {
139
+ const end = buffer.indexOf(10);
140
+ if (end < 0)
141
+ break;
142
+ const header = buffer.toString('utf8', 0, end);
143
+ if (header === `${request.name} missing`) {
144
+ buffer = buffer.subarray(end + 1);
145
+ this.answer(undefined);
146
+ continue;
147
+ }
148
+ const [, id, type, length] = /^([a-f0-9]+) ([a-z]+) (\d+)$/.exec(header) ?? [];
149
+ const size = Number(length);
150
+ if (!Number.isSafeInteger(size) || (request.want === 'blob' && type !== 'blob')) {
151
+ this.stop(this.child, new Error(`Unexpected Git object: ${request.name}`));
152
+ return;
153
+ }
154
+ if (buffer.length < end + size + 2)
155
+ break;
156
+ const blob = Buffer.from(buffer.subarray(end + 1, end + 1 + size));
157
+ buffer = buffer.subarray(end + size + 2);
158
+ this.answer(request.want === 'blob' ? blob : id);
159
+ }
160
+ this.chunks = buffer.length ? [buffer] : [];
161
+ }
162
+ answer(value) {
163
+ const request = this.pending.shift();
164
+ if (this.pending.length === 0 && this.child)
165
+ setHeld(this.child, false);
166
+ request.resolve(value);
167
+ }
168
+ stop(child, error) {
169
+ if (this.child !== child)
170
+ return;
171
+ this.child = undefined;
172
+ this.chunks = [];
173
+ for (const request of this.pending.splice(0))
174
+ request.reject(error);
175
+ child.kill();
176
+ }
177
+ }
178
+ /** A reader with nothing to answer must not keep the process running. */
179
+ function setHeld(child, held) {
180
+ for (const handle of [child, child.stdout, child.stdin, child.stderr]) {
181
+ if (held)
182
+ handle.ref();
183
+ else
184
+ handle.unref();
185
+ }
97
186
  }
98
187
  export async function readGitCommit(directory, revision, excludes, isSource, claims) {
99
188
  const id = await resolveGitCommit(directory, revision);
@@ -123,7 +212,8 @@ export async function readGitCommit(directory, revision, excludes, isSource, cla
123
212
  }
124
213
  files.sort((left, right) => comparePaths(left.path, right.path));
125
214
  const inventory = tracked.filter(({ path }) => !generated.has(path)).map(({ path, oid, size }) => ({ path, lines: counts.get(oid) ?? null, ...(size === undefined ? {} : { bytes: size }) }));
126
- return { subject: { kind: 'commit', id }, files, inventory, generatedExcluded: [...generated].sort(comparePaths),
215
+ const blobIds = new Map(tracked.map(({ path, oid }) => [path, oid]));
216
+ return { subject: { kind: 'commit', id }, files, blobIds, inventory, generatedExcluded: [...generated].sort(comparePaths),
127
217
  ...(oversized.size ? { oversizedClaims: [...oversized].sort(comparePaths) } : {}) };
128
218
  }
129
219
  function inventoryLineCounts(directory, entries, sources, capture) {
@@ -0,0 +1,13 @@
1
+ import type { SourceSnapshot } from '../../core/model/source.js';
2
+ export interface CoverageSource {
3
+ readonly root: string;
4
+ readonly snapshot: SourceSnapshot;
5
+ readonly readCommittedManifest?: (path: string) => Promise<string>;
6
+ }
7
+ interface GoSource {
8
+ readonly lines: ReadonlyMap<string, number>;
9
+ path(input: string): string;
10
+ }
11
+ export declare function goCoverSource(source: CoverageSource): Promise<GoSource>;
12
+ export declare function goCoverToLcov(text: string, input: string, source: GoSource): string;
13
+ export {};
@@ -0,0 +1,150 @@
1
+ import { lstat, readFile } from 'node:fs/promises';
2
+ import { join, posix, win32 } from 'node:path';
3
+ import { comparePaths, sourceLineCounts } from '../../core/model/snapshot.js';
4
+ export async function goCoverSource(source) {
5
+ const { root, snapshot } = source;
6
+ const lines = sourceLineCounts(snapshot.files.filter(({ path }) => path.endsWith('.go')));
7
+ const known = new Set([...lines.keys(), ...(snapshot.generatedExcluded ?? []),
8
+ ...(snapshot.inventory?.map(({ path }) => path) ?? [])]);
9
+ const modules = await goModules(source, known);
10
+ const platform = win32.isAbsolute(root) && !posix.isAbsolute(root) ? win32 : posix;
11
+ return {
12
+ lines,
13
+ path(input) {
14
+ const path = platform === win32 ? input.replaceAll('\\', '/') : input;
15
+ if (platform.isAbsolute(path)) {
16
+ const relative = platform.relative(root, path) || '.';
17
+ return platform === win32 ? relative.replaceAll('\\', '/') : relative;
18
+ }
19
+ const relative = posix.normalize(path);
20
+ if (path.startsWith('./') || relative.startsWith('../') || win32.isAbsolute(path))
21
+ return relative;
22
+ const candidates = new Set(modules.flatMap(({ directory, module }) => relative.startsWith(`${module}/`)
23
+ ? [posix.join(directory, relative.slice(module.length + 1))] : []));
24
+ const matches = [...new Set([relative, ...candidates])].filter(candidate => known.has(candidate));
25
+ if (matches.length > 1)
26
+ throw new Error(`Ambiguous Go coverprofile source ${JSON.stringify(input)}: ${matches.sort(comparePaths).join(', ')}`);
27
+ // Keep an unresolved import path so the normal coverage pipeline can report the missing source.
28
+ return matches[0] ?? (candidates.size === 1 ? [...candidates][0] : relative);
29
+ },
30
+ };
31
+ }
32
+ async function goModules({ root, snapshot, readCommittedManifest }, known) {
33
+ const { subject } = snapshot;
34
+ const manifests = new Set();
35
+ if (subject.kind === 'commit') {
36
+ for (const path of known)
37
+ if (posix.basename(path) === 'go.mod')
38
+ manifests.add(path);
39
+ }
40
+ else {
41
+ manifests.add('go.mod');
42
+ for (const path of known) {
43
+ if (!path.endsWith('.go'))
44
+ continue;
45
+ for (let directory = posix.dirname(path); directory !== '.'; directory = posix.dirname(directory)) {
46
+ const manifest = posix.join(directory, 'go.mod');
47
+ if (manifests.has(manifest))
48
+ break;
49
+ manifests.add(manifest);
50
+ }
51
+ }
52
+ }
53
+ const modules = await Promise.all([...manifests].map(async (path) => {
54
+ const text = subject.kind === 'commit'
55
+ ? await readCommittedManifest?.(path) ?? '' : await workingManifest(join(root, path));
56
+ return { directory: posix.dirname(path), module: modulePath(text) };
57
+ }));
58
+ return modules.flatMap(({ directory, module }) => module === undefined ? [] : [{ directory, module }]);
59
+ }
60
+ async function workingManifest(path) {
61
+ try {
62
+ return (await lstat(path)).isFile() ? await readFile(path, 'utf8') : '';
63
+ }
64
+ catch (error) {
65
+ if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))
66
+ return '';
67
+ throw error;
68
+ }
69
+ }
70
+ function modulePath(text) {
71
+ let grouped = false;
72
+ for (const raw of text.split(/\r?\n/)) {
73
+ const line = raw.replace(/\/\/.*$/, '').trim();
74
+ if (line === '')
75
+ continue;
76
+ const value = grouped ? line : /^module[ \t]+(.+)$/.exec(line)?.[1];
77
+ if (value === undefined)
78
+ continue;
79
+ if (value === '(') {
80
+ grouped = true;
81
+ continue;
82
+ }
83
+ const path = value.replace(/^"([^"]*)"$|^`([^`]*)`$/, '$1$2');
84
+ if (/^[A-Za-z0-9_.~-]+(?:\/[A-Za-z0-9_.~-]+)*$/.test(path) && !path.split('/').some(part => part === '.' || part === '..')) {
85
+ return path;
86
+ }
87
+ return undefined;
88
+ }
89
+ }
90
+ export function goCoverToLcov(text, input, source) {
91
+ const [header, ...records] = text.split(/\r?\n/);
92
+ const mode = /^mode: (set|count|atomic)$/.exec(header ?? '')?.[1];
93
+ if (!mode)
94
+ throw new Error(`Invalid Go coverprofile ${input} at line 1: expected mode: set, count, or atomic`);
95
+ const files = new Map();
96
+ const paths = new Map();
97
+ for (const [index, record] of records.entries()) {
98
+ if (record === '' && index === records.length - 1)
99
+ break;
100
+ const invalid = (reason) => new Error(`Invalid Go coverprofile ${input} at line ${index + 2}: ${reason}`);
101
+ const match = /^([^\0]+):(\d+)\.(\d+),(\d+)\.(\d+) (\d+) (\d+)$/.exec(record);
102
+ if (!match)
103
+ throw invalid('expected file:startLine.startColumn,endLine.endColumn statements hits');
104
+ const [first, startColumn, end, endColumn, statements, count] = match.slice(2).map(Number);
105
+ if (![first, startColumn, end, endColumn, statements, count].every(Number.isSafeInteger)
106
+ || first < 1 || startColumn < 1 || endColumn < 1 || end < first || (end === first && endColumn < startColumn)) {
107
+ throw invalid('invalid block coordinates or counts');
108
+ }
109
+ const raw = match[1];
110
+ const path = paths.get(raw) ?? source.path(raw);
111
+ paths.set(raw, path);
112
+ const blocks = files.get(path) ?? new Map();
113
+ files.set(path, blocks);
114
+ const key = `${first}.${startColumn},${end}.${endColumn}`;
115
+ const previous = blocks.get(key);
116
+ if (previous && previous.statements !== statements)
117
+ throw invalid('conflicting statement counts for the same block');
118
+ const hits = mode === 'set' ? Number((previous?.hits ?? 0) > 0 || count > 0) : (previous?.hits ?? 0) + count;
119
+ if (!Number.isSafeInteger(hits))
120
+ throw invalid('hit count exceeds the supported integer range');
121
+ // Go's end column is exclusive. A block ending at column 1 never touches that source line.
122
+ const last = end - Number(endColumn === 1);
123
+ blocks.set(key, { first, last: end === first && endColumn === startColumn ? first - 1 : last, statements, hits });
124
+ }
125
+ return renderLcov(files, source.lines);
126
+ }
127
+ function renderLcov(files, sourceLines) {
128
+ const output = [];
129
+ for (const [path, blocks] of [...files].sort(([left], [right]) => comparePaths(left, right))) {
130
+ output.push(`SF:${path}`);
131
+ const lines = new Map();
132
+ const length = sourceLines.get(path);
133
+ if (length !== undefined) {
134
+ for (const { first, last, statements, hits } of blocks.values()) {
135
+ if (statements === 0 || first > last)
136
+ continue;
137
+ // Include a single out-of-range line to let LCOV flag stale coverage without expanding arbitrary coordinates.
138
+ for (let line = Math.min(first, length + 1); line <= Math.min(last, length + 1); line++) {
139
+ // Separate blocks on one line can observe the same execution.
140
+ lines.set(line, Math.max(lines.get(line) ?? 0, hits));
141
+ }
142
+ }
143
+ }
144
+ for (const [line, hits] of [...lines].sort(([left], [right]) => left - right))
145
+ output.push(`DA:${line},${hits}`);
146
+ output.push('end_of_record');
147
+ }
148
+ return output.join('\n');
149
+ }
150
+ //# sourceMappingURL=go-cover.js.map
@@ -1,5 +1,10 @@
1
+ import type { CoverageSource } from './go-cover.js';
1
2
  export type LcovFiles = string | readonly string[];
2
- export declare function readLcovFiles(input: LcovFiles): Promise<{
3
+ export interface CoverageInputs {
4
+ readonly lcov?: LcovFiles;
5
+ readonly goCover?: LcovFiles;
6
+ }
7
+ export declare function readCoverageFiles({ lcov, goCover }: CoverageInputs, source: CoverageSource): Promise<{
3
8
  text: string;
4
9
  inputDigests: string[];
5
10
  }>;
@@ -1,14 +1,34 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { comparePaths, digest, utf8 } from '../../core/model/snapshot.js';
3
- export async function readLcovFiles(input) {
4
- const paths = typeof input === 'string' ? [input] : input;
5
- if (paths.length === 0)
3
+ import { goCoverSource, goCoverToLcov } from './go-cover.js';
4
+ export async function readCoverageFiles({ lcov, goCover }, source) {
5
+ const lcovPaths = paths(lcov);
6
+ const goPaths = paths(goCover);
7
+ if (lcov !== undefined && lcovPaths.length === 0)
6
8
  throw new Error('Provide at least one LCOV file');
7
- const sources = await Promise.all(paths.map(async (path) => {
8
- const text = utf8(await readFile(path));
9
- return { text, digest: digest(text) };
10
- }));
9
+ if (goCover !== undefined && goPaths.length === 0)
10
+ throw new Error('Provide at least one Go coverprofile');
11
+ if (lcovPaths.length === 0 && goPaths.length === 0)
12
+ throw new Error('Provide at least one coverage input');
13
+ const [lcovSources, goSources] = await Promise.all([
14
+ Promise.all(lcovPaths.map(readInput)),
15
+ readGoCoverFiles(goPaths, source),
16
+ ]);
17
+ const sources = [...lcovSources, ...goSources];
11
18
  sources.sort((a, b) => comparePaths(a.digest, b.digest));
12
19
  return { text: sources.map(source => source.text).join('\n'), inputDigests: sources.map(source => source.digest) };
13
20
  }
21
+ function paths(input) {
22
+ return typeof input === 'string' ? [input] : input ?? [];
23
+ }
24
+ async function readGoCoverFiles(files, source) {
25
+ if (files.length === 0)
26
+ return [];
27
+ const [goSource, inputs] = await Promise.all([goCoverSource(source), Promise.all(files.map(readInput))]);
28
+ return inputs.map((input, index) => ({ ...input, text: goCoverToLcov(input.text, files[index], goSource) }));
29
+ }
30
+ async function readInput(path) {
31
+ const text = utf8(await readFile(path));
32
+ return { text, digest: digest(text) };
33
+ }
14
34
  //# sourceMappingURL=lcov-files.js.map
@@ -1,11 +1,11 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { mkdtemp, rm } from 'node:fs/promises';
4
4
  import { tmpdir } from 'node:os';
5
- import { dirname, join } from 'node:path';
5
+ import { join } from 'node:path';
6
6
  import { promisify } from 'node:util';
7
- import { isSourcePathname } from '../../core/ports/source-provider.js';
8
7
  import { toolFailure } from './failure.js';
8
+ import { validateToolInvocation, writeToolSnapshot } from './tool-snapshot.js';
9
9
  const docker = promisify(execFile);
10
10
  const proxyOverrides = ['HTTP_PROXY', 'HTTPS_PROXY', 'FTP_PROXY', 'ALL_PROXY', 'NO_PROXY']
11
11
  .flatMap(name => ['--env', `${name}=`, '--env', `${name.toLowerCase()}=`]);
@@ -26,28 +26,12 @@ export class DockerToolRunner {
26
26
  this.implementation = JSON.stringify(['docker-tool-runner/v2', image, this.limits]);
27
27
  }
28
28
  async run(invocation) {
29
+ validateToolInvocation(invocation);
29
30
  const [command, ...args] = invocation.argv;
30
- if (!command || invocation.argv.some(arg => arg.includes('\0')))
31
- throw new Error('A tool command and valid arguments are required');
32
- if (!Number.isSafeInteger(invocation.timeoutMs) || invocation.timeoutMs < 1 || invocation.timeoutMs > 2_147_483_647) {
33
- throw new Error('Invalid tool timeout');
34
- }
35
- if (!Number.isSafeInteger(invocation.maxOutputBytes) || invocation.maxOutputBytes < 1)
36
- throw new Error('Invalid tool output limit');
37
- const paths = new Set();
38
- for (const { path } of invocation.files) {
39
- if (!isSourcePathname(path) || paths.has(path))
40
- throw new Error(`Invalid or duplicate snapshot path: ${path}`);
41
- paths.add(path);
42
- }
43
31
  const directory = await mkdtemp(join(tmpdir(), 'repometry-tool-'));
44
32
  const container = `repometry-tool-${randomUUID()}`;
45
33
  try {
46
- for (const file of invocation.files) {
47
- const path = join(directory, file.path);
48
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
49
- await writeFile(path, file.bytes, { mode: 0o600, flag: 'wx' });
50
- }
34
+ await writeToolSnapshot(directory, invocation.files);
51
35
  const mount = `type=bind,"source=${directory.replaceAll('"', '""')}",target=/snapshot,readonly`;
52
36
  const uid = process.getuid?.();
53
37
  const gid = process.getgid?.();
@@ -0,0 +1,13 @@
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;
4
+ export declare class HostLanguageRunner {
5
+ private readonly path;
6
+ private readonly script;
7
+ private readonly goVersion?;
8
+ readonly implementation = "host-language-runner/v1";
9
+ private goCompiler?;
10
+ constructor(path: string, script: string, goVersion?: string | undefined);
11
+ run(invocation: ToolInvocation): Promise<ToolResult>;
12
+ private goParser;
13
+ }
@@ -0,0 +1,176 @@
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';
4
+ import { tmpdir } from 'node:os';
5
+ import { delimiter, isAbsolute, join } from 'node:path';
6
+ import { digest } from '../../core/model/snapshot.js';
7
+ import { validateToolInvocation, writeToolSnapshot } from './tool-snapshot.js';
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
+ }
25
+ export class HostLanguageRunner {
26
+ path;
27
+ script;
28
+ goVersion;
29
+ implementation = 'host-language-runner/v1';
30
+ goCompiler;
31
+ constructor(path, script, goVersion) {
32
+ this.path = path;
33
+ this.script = script;
34
+ this.goVersion = goVersion;
35
+ }
36
+ async run(invocation) {
37
+ validateToolInvocation(invocation);
38
+ const home = await mkdtemp(join(tmpdir(), 'repometry-language-'));
39
+ try {
40
+ const cwd = join(home, 'snapshot');
41
+ await mkdir(cwd);
42
+ await writeToolSnapshot(cwd, invocation.files);
43
+ const env = toolEnvironment(this.path, home);
44
+ const [binary, ...args] = invocation.argv;
45
+ if (binary !== 'go' || args.length !== 1 || args[0] !== 'run') {
46
+ return await runTool(invocation, binary, [...args, this.script], cwd, env);
47
+ }
48
+ const deadline = performance.now() + invocation.timeoutMs;
49
+ const parser = await withinDeadline(this.goParser(invocation, deadline), deadline);
50
+ return await runTool({ ...invocation, timeoutMs: timeLeft(deadline) }, parser, [], cwd, env);
51
+ }
52
+ finally {
53
+ await rm(home, { recursive: true, force: true });
54
+ }
55
+ }
56
+ 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);
64
+ if (existing)
65
+ return existing;
66
+ const pending = compileGoParser(compiler.binary, this.path, source, invocation.maxOutputBytes, deadline).catch(error => {
67
+ goParsers.delete(key);
68
+ throw error;
69
+ });
70
+ goParsers.set(key, pending);
71
+ return pending;
72
+ }
73
+ }
74
+ const goParsers = new Map();
75
+ let goHome;
76
+ function goProcessHome() {
77
+ if (goHome !== undefined)
78
+ return goHome;
79
+ const home = mkdtempSync(join(tmpdir(), 'repometry-go-parser-'));
80
+ goHome = home;
81
+ process.once('exit', () => {
82
+ try {
83
+ rmSync(home, { recursive: true, force: true });
84
+ }
85
+ catch { /* Cleanup must not change the process exit status. */ }
86
+ });
87
+ return home;
88
+ }
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
+ async function compileGoParser(binary, path, source, maxOutputBytes, deadline) {
116
+ const home = goProcessHome();
117
+ const directory = await mkdtemp(join(home, 'build-'));
118
+ const script = join(directory, 'parser.go');
119
+ const parser = join(directory, process.platform === 'win32' ? 'parser.exe' : 'parser');
120
+ try {
121
+ await writeFile(script, source, { mode: 0o600, flag: 'wx' });
122
+ const result = await runTool({ timeoutMs: timeLeft(deadline), maxOutputBytes }, binary, ['build', '-o', parser, script], directory, toolEnvironment(path, home));
123
+ if (result.exitCode !== 0)
124
+ throw new Error(toolFailure('Could not compile the host Go parser', result.stderr));
125
+ await access(parser, constants.X_OK);
126
+ return parser;
127
+ }
128
+ catch (error) {
129
+ await rm(directory, { recursive: true, force: true });
130
+ throw error;
131
+ }
132
+ }
133
+ function timeLeft(deadline) {
134
+ const timeout = Math.ceil(deadline - performance.now());
135
+ if (timeout <= 0)
136
+ throw new Error('Tool timed out');
137
+ return timeout;
138
+ }
139
+ async function withinDeadline(result, deadline) {
140
+ let timer;
141
+ try {
142
+ const expiration = new Promise((_, reject) => {
143
+ timer = setTimeout(() => reject(new Error('Tool timed out')), timeLeft(deadline));
144
+ });
145
+ return await Promise.race([result, expiration]);
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ }
150
+ }
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
+ function runTool({ stdin, timeoutMs, maxOutputBytes }, binary, args, cwd, env) {
156
+ return new Promise((resolve, reject) => {
157
+ const child = execFile(binary, args, { cwd, env, timeout: timeoutMs, maxBuffer: maxOutputBytes,
158
+ killSignal: 'SIGKILL', encoding: 'buffer', windowsHide: true }, (error, stdout, stderr) => {
159
+ if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' || stdout.length + stderr.length > maxOutputBytes) {
160
+ reject(new Error('Tool exceeded the output limit'));
161
+ }
162
+ else if (error?.killed) {
163
+ reject(new Error('Tool timed out'));
164
+ }
165
+ else if (error && typeof error.code !== 'number') {
166
+ reject(new Error('Could not run the host language parser', { cause: error }));
167
+ }
168
+ else {
169
+ resolve({ exitCode: typeof error?.code === 'number' ? error.code : 0, stdout, stderr });
170
+ }
171
+ });
172
+ child.stdin?.on('error', () => { });
173
+ child.stdin?.end(stdin);
174
+ });
175
+ }
176
+ //# sourceMappingURL=host-language-runner.js.map
@@ -7,4 +7,7 @@ export interface ProcessPluginManifest extends Omit<Plugin, 'operations' | 'tool
7
7
  readonly operations: readonly ProcessOperation[];
8
8
  readonly tools: Readonly<Record<string, string>>;
9
9
  }
10
- export declare function processPlugin({ operations, ...manifest }: ProcessPluginManifest, runner: ToolRunner): Plugin;
10
+ type ProcessRunner = Pick<ToolRunner, 'run' | 'implementation'>;
11
+ export declare function processPlugin(manifest: ProcessPluginManifest, runner: ToolRunner): Plugin;
12
+ export declare function bindProcessPlugin({ operations, ...manifest }: ProcessPluginManifest, runner: ProcessRunner): Plugin;
13
+ export {};
@@ -3,9 +3,13 @@ import { isJsonValue } from '../../core/model/plugin-data.js';
3
3
  import { digest, sourceFile, sourceFiles, utf8 } from '../../core/model/snapshot.js';
4
4
  import { toolFailure } from './failure.js';
5
5
  export const processPluginProtocol = 'repometry.plugin-process/v1';
6
- export function processPlugin({ operations, ...manifest }, runner) {
6
+ export function processPlugin(manifest, runner) {
7
7
  if (runner.network !== 'none')
8
8
  throw new Error('Process plugins require a runner with networking disabled');
9
+ return bindProcessPlugin(manifest, runner);
10
+ }
11
+ // Only the packaged, first-party parsers use the host runner.
12
+ export function bindProcessPlugin({ operations, ...manifest }, runner) {
9
13
  const versions = Object.values(manifest.tools);
10
14
  if (versions.length === 0 || versions.some(version => typeof version !== 'string' || !version.trim())) {
11
15
  throw new Error('Process plugins must declare their tool versions');
@@ -13,9 +17,9 @@ export function processPlugin({ operations, ...manifest }, runner) {
13
17
  return { ...manifest, operations: operations.map(operation => bindOperation(manifest.id, manifest.settings ?? null, operation, runner)) };
14
18
  }
15
19
  function bindOperation(plugin, settings, operation, runner) {
16
- const { id, role, scope, inputs, output, argv, timeoutMs, maxOutputBytes } = operation;
20
+ const { id, role, scope, fileIndependent, inputs, output, argv, timeoutMs, maxOutputBytes } = operation;
17
21
  const implementation = digest(JSON.stringify([processPluginProtocol, operation.implementation, runner.implementation, argv, timeoutMs, maxOutputBytes]));
18
- return { id, role, scope, inputs, output, implementation, async execute(context) {
22
+ return { id, role, scope, ...(fileIndependent === undefined ? {} : { fileIndependent }), inputs, output, implementation, async execute(context) {
19
23
  const { files, stdin } = encodeRequest(`${plugin}/${id}`, settings, operation, context);
20
24
  const result = await runner.run({ argv, timeoutMs, maxOutputBytes, files, stdin });
21
25
  if (result.exitCode !== 0)
@@ -0,0 +1,3 @@
1
+ import type { ToolInvocation } from '../../core/ports/tool-runner.js';
2
+ export declare function validateToolInvocation(invocation: ToolInvocation): void;
3
+ export declare function writeToolSnapshot(directory: string, files: ToolInvocation['files']): Promise<void>;
@@ -0,0 +1,26 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { isSourcePathname } from '../../core/ports/source-provider.js';
4
+ export function validateToolInvocation(invocation) {
5
+ if (!invocation.argv[0] || invocation.argv.some(arg => arg.includes('\0')))
6
+ throw new Error('A tool command and valid arguments are required');
7
+ if (!Number.isSafeInteger(invocation.timeoutMs) || invocation.timeoutMs < 1 || invocation.timeoutMs > 2_147_483_647) {
8
+ throw new Error('Invalid tool timeout');
9
+ }
10
+ if (!Number.isSafeInteger(invocation.maxOutputBytes) || invocation.maxOutputBytes < 1)
11
+ throw new Error('Invalid tool output limit');
12
+ const paths = new Set();
13
+ for (const { path } of invocation.files) {
14
+ if (!isSourcePathname(path) || paths.has(path))
15
+ throw new Error(`Invalid or duplicate snapshot path: ${path}`);
16
+ paths.add(path);
17
+ }
18
+ }
19
+ export async function writeToolSnapshot(directory, files) {
20
+ for (const file of files) {
21
+ const path = join(directory, file.path);
22
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
23
+ await writeFile(path, file.bytes, { mode: 0o600, flag: 'wx' });
24
+ }
25
+ }
26
+ //# sourceMappingURL=tool-snapshot.js.map
@@ -2,6 +2,7 @@ import type { Invocation } from './arguments.js';
2
2
  export declare function readConfig(root: string, input: Invocation): Promise<{
3
3
  exclude: readonly string[];
4
4
  ignore: readonly import("../index.js").FindingIgnoreRule[];
5
+ plugins: readonly import("../core/engine/plugin.js").Plugin[];
5
6
  imports: readonly string[];
6
7
  reports: readonly string[];
7
8
  sources: string | undefined;