repometry 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/target/main/resources/report/json/config-v1.schema.json +84 -2
  4. package/target/main/ts/api/cache/root.d.ts +3 -0
  5. package/target/main/ts/api/cache/root.js +21 -0
  6. package/target/main/ts/api/git/blob-batch.js +2 -1
  7. package/target/main/ts/api/git/blob-history.d.ts +20 -0
  8. package/target/main/ts/api/git/blob-history.js +54 -0
  9. package/target/main/ts/api/git/git-churn.js +38 -37
  10. package/target/main/ts/api/git/git-executable.d.ts +1 -0
  11. package/target/main/ts/api/git/git-executable.js +31 -0
  12. package/target/main/ts/api/git/git.d.ts +8 -1
  13. package/target/main/ts/api/git/git.js +58 -61
  14. package/target/main/ts/api/git/inspection-source.d.ts +2 -1
  15. package/target/main/ts/api/git/inspection-source.js +3 -2
  16. package/target/main/ts/api/git/local-sources.js +3 -2
  17. package/target/main/ts/api/git/source-cache.d.ts +0 -2
  18. package/target/main/ts/api/git/source-cache.js +1 -16
  19. package/target/main/ts/api/process/go-parser-cache.d.ts +1 -0
  20. package/target/main/ts/api/process/go-parser-cache.js +71 -0
  21. package/target/main/ts/api/process/go-parser-files.d.ts +5 -0
  22. package/target/main/ts/api/process/go-parser-files.js +65 -0
  23. package/target/main/ts/api/process/host-language-runner.d.ts +3 -5
  24. package/target/main/ts/api/process/host-language-runner.js +21 -66
  25. package/target/main/ts/api/process/host-tool.d.ts +22 -0
  26. package/target/main/ts/api/process/host-tool.js +87 -0
  27. package/target/main/ts/cli/config.d.ts +13 -0
  28. package/target/main/ts/cli/config.js +7 -4
  29. package/target/main/ts/cli/main.js +24 -81
  30. package/target/main/ts/cli/range-inspection.d.ts +28 -0
  31. package/target/main/ts/cli/range-inspection.js +41 -0
  32. package/target/main/ts/cli/range-jobs.d.ts +22 -0
  33. package/target/main/ts/cli/range-jobs.js +152 -0
  34. package/target/main/ts/cli/range-worker.d.ts +1 -0
  35. package/target/main/ts/cli/range-worker.js +36 -0
  36. package/target/main/ts/compose/analysis-report.js +4 -3
  37. package/target/main/ts/compose/diff-coverage.js +1 -1
  38. package/target/main/ts/compose/history-cache.d.ts +2 -0
  39. package/target/main/ts/compose/history-cache.js +2 -0
  40. package/target/main/ts/compose/inspect.js +3 -3
  41. package/target/main/ts/compose/native-language-plugins.js +7 -6
  42. package/target/main/ts/compose/review.js +3 -1
  43. package/target/main/ts/report/json/projections/commit-summary.js +5 -7
  44. package/target/main/ts/report/json/projections/metric-values.d.ts +5 -0
  45. package/target/main/ts/report/json/projections/metric-values.js +9 -6
  46. package/target/main/ts/report/markdown/pull-review.js +11 -1
package/README.md CHANGED
@@ -39,7 +39,7 @@ Run these commands in your repository. Without an install, start each with `npx`
39
39
  | Command | What it does |
40
40
  | --- | --- |
41
41
  | `repometry analyze` | Analyze HEAD and save its inspection under `.repometry/`. |
42
- | `repometry analyze HEAD~50..HEAD --skip-saved` | Build history for the last 50 commits, oldest first, skipping saved inspections. |
42
+ | `repometry analyze HEAD~50..HEAD --skip-saved` | Build history for the last 50 commits, oldest first, skipping saved inspections. A long range uses every core; `--concurrency N` sets a limit. |
43
43
  | `repometry analyze --import lcov=coverage/lcov.info --import sarif=results.sarif` | Import coverage and scanner results. Repeat `--import` for each file. |
44
44
  | `repometry view` | Open the report locally on a free port. Use `--port 3030` to choose a port. |
45
45
  | `repometry report html` | Export a static report to `.repometry/report/html`. Use `-o DIR` for another folder. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repometry",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "Track repository metrics without SaaS",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,8 +25,90 @@
25
25
  "branch": { "type": "string", "minLength": 1 },
26
26
  "minCoverage": { "type": "number", "minimum": 0, "maximum": 100 },
27
27
  "minLines": { "type": "integer", "minimum": 0 },
28
- "maxNewIssues": { "type": "integer", "minimum": 0 }
28
+ "maxNewIssues": { "type": "integer", "minimum": 0 },
29
+ "plugins": { "$ref": "urn:repometry:schema:process-plugins:1" }
29
30
  },
30
31
  "additionalProperties": false,
31
- "$defs": { "strings": { "type": "array", "items": { "type": "string", "minLength": 1 } } }
32
+ "$defs": {
33
+ "strings": { "type": "array", "items": { "type": "string", "minLength": 1 } },
34
+ "processPlugins": {
35
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
36
+ "$id": "urn:repometry:schema:process-plugins:1",
37
+ "title": "Repometry process plugins",
38
+ "type": "array",
39
+ "items": {
40
+ "type": "object",
41
+ "additionalProperties": false,
42
+ "required": ["id", "version", "image", "command", "scope", "tools", "providesLanguages"],
43
+ "properties": {
44
+ "id": { "$ref": "#/$defs/id" },
45
+ "version": { "$ref": "#/$defs/text" },
46
+ "image": {
47
+ "type": "string",
48
+ "pattern": "^(?:[a-z0-9][a-z0-9.:/_-]*@)?sha256:[a-f0-9]{64}$",
49
+ "description": "The full ID or distribution digest of a locally available Docker image."
50
+ },
51
+ "command": {
52
+ "type": "array",
53
+ "minItems": 1,
54
+ "items": { "type": "string", "pattern": "^[^\\u0000]*$" }
55
+ },
56
+ "scope": { "enum": ["file", "repository"] },
57
+ "fileIndependent": {
58
+ "type": "boolean",
59
+ "description": "Each file's results and diagnostics are independent of the other files supplied to a repository parser."
60
+ },
61
+ "claims": {
62
+ "type": "object",
63
+ "additionalProperties": false,
64
+ "properties": {
65
+ "extensions": { "$ref": "#/$defs/extensions" },
66
+ "globs": { "$ref": "#/$defs/globs" }
67
+ }
68
+ },
69
+ "limits": {
70
+ "type": "object",
71
+ "additionalProperties": false,
72
+ "properties": {
73
+ "timeoutMs": { "type": "integer", "minimum": 1, "maximum": 2147483647 },
74
+ "maxOutputBytes": { "$ref": "#/$defs/positiveInteger" },
75
+ "memoryBytes": { "$ref": "#/$defs/positiveInteger" },
76
+ "pidsLimit": { "$ref": "#/$defs/positiveInteger" }
77
+ }
78
+ },
79
+ "tools": { "type": "object", "minProperties": 1, "additionalProperties": { "$ref": "#/$defs/text" } },
80
+ "settings": true,
81
+ "providesLanguages": {
82
+ "type": "array",
83
+ "minItems": 1,
84
+ "items": {
85
+ "type": "object",
86
+ "additionalProperties": false,
87
+ "required": ["id", "label"],
88
+ "properties": {
89
+ "id": { "$ref": "#/$defs/id" },
90
+ "label": { "$ref": "#/$defs/text" },
91
+ "color": { "type": "string", "pattern": "^#[0-9A-Fa-f]{6}$" },
92
+ "extensions": { "$ref": "#/$defs/extensions" },
93
+ "globs": { "$ref": "#/$defs/globs" },
94
+ "measures": {
95
+ "type": "array",
96
+ "uniqueItems": true,
97
+ "items": { "enum": ["functions", "cyclomaticComplexity", "cognitiveComplexity", "classes",
98
+ "commentLines", "codeLines", "duplication", "structuralRules"] }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ }
104
+ },
105
+ "$defs": {
106
+ "id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" },
107
+ "text": { "type": "string", "pattern": "\\S" },
108
+ "positiveInteger": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 },
109
+ "extensions": { "type": "array", "uniqueItems": true, "items": { "type": "string", "pattern": "^\\.[\\w-]+$" } },
110
+ "globs": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/$defs/text" } }
111
+ }
112
+ }
113
+ }
32
114
  }
@@ -0,0 +1,3 @@
1
+ export declare function cacheRoot(env?: NodeJS.ProcessEnv, system?: NodeJS.Platform, home?: string): string;
2
+ export declare const goParserCacheDirectory = "go-parsers-v1";
3
+ export declare function clearCaches(root: string, sourcesOnly: boolean): Promise<readonly string[]>;
@@ -0,0 +1,21 @@
1
+ import { rm } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join, resolve } from 'node:path';
4
+ export function cacheRoot(env = process.env, system = process.platform, home = homedir()) {
5
+ if (env.REPOMETRY_CACHE_DIR)
6
+ return resolve(env.REPOMETRY_CACHE_DIR);
7
+ if (env.XDG_CACHE_HOME)
8
+ return resolve(env.XDG_CACHE_HOME, 'repometry');
9
+ if (system === 'darwin')
10
+ return join(home, 'Library', 'Caches', 'repometry');
11
+ if (system === 'win32' && env.LOCALAPPDATA)
12
+ return resolve(env.LOCALAPPDATA, 'repometry', 'cache');
13
+ return join(home, '.cache', 'repometry');
14
+ }
15
+ export const goParserCacheDirectory = 'go-parsers-v1';
16
+ export async function clearCaches(root, sourcesOnly) {
17
+ const directories = sourcesOnly ? ['sources'] : ['sources', goParserCacheDirectory];
18
+ await Promise.all(directories.map(directory => rm(join(root, directory), { recursive: true, force: true })));
19
+ return directories;
20
+ }
21
+ //# sourceMappingURL=root.js.map
@@ -1,5 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { validSubjectId } from '../../core/model/report.js';
3
+ import { gitExecutable } from './git-executable.js';
3
4
  const idleTimeout = 10_000;
4
5
  const maxBlobBytes = 64 * 1024 * 1024;
5
6
  export class GitBlobBatch {
@@ -47,7 +48,7 @@ class BlobSession {
47
48
  chunks;
48
49
  buffer = Buffer.alloc(0);
49
50
  constructor(directory) {
50
- this.child = spawn('git', ['--no-replace-objects', 'cat-file', '--batch'], { cwd: directory });
51
+ this.child = spawn(gitExecutable(), ['--no-replace-objects', 'cat-file', '--batch'], { cwd: directory });
51
52
  this.child.stderr.resume();
52
53
  this.child.stdin.on('error', () => { });
53
54
  this.child.on('error', error => this.child.stdout.destroy(error));
@@ -0,0 +1,20 @@
1
+ export interface BlobRequest {
2
+ readonly id: string;
3
+ readonly estimatedBytes: number;
4
+ readonly contents: boolean;
5
+ }
6
+ interface BlobFacts {
7
+ readonly lines: number | null;
8
+ readonly bytes?: Buffer;
9
+ }
10
+ type ReadBlobs = (ids: readonly string[]) => Promise<ReadonlyMap<string, Buffer>>;
11
+ export declare const gitBlobBatchBytes: number;
12
+ /** Keeps only inventory facts and requested bytes from the preceding snapshot. */
13
+ export declare class GitBlobHistory {
14
+ private readonly maxBatchBytes;
15
+ private previous;
16
+ constructor(maxBatchBytes?: number);
17
+ read(requests: readonly BlobRequest[], read: ReadBlobs): Promise<ReadonlyMap<string, BlobFacts>>;
18
+ private missingRequests;
19
+ }
20
+ export {};
@@ -0,0 +1,54 @@
1
+ import { textLineCount } from '../../core/model/snapshot.js';
2
+ export const gitBlobBatchBytes = 64 * 1024 * 1024;
3
+ /** Keeps only inventory facts and requested bytes from the preceding snapshot. */
4
+ export class GitBlobHistory {
5
+ maxBatchBytes;
6
+ previous = new Map();
7
+ constructor(maxBatchBytes = gitBlobBatchBytes) {
8
+ this.maxBatchBytes = maxBatchBytes;
9
+ }
10
+ async read(requests, read) {
11
+ const current = new Map();
12
+ const missing = this.missingRequests(requests, current);
13
+ for (const batch of blobBatches(missing, this.maxBatchBytes))
14
+ await readBatch(batch, read, current);
15
+ this.previous = current;
16
+ return current;
17
+ }
18
+ missingRequests(requests, current) {
19
+ const missing = [];
20
+ for (const request of requests) {
21
+ const facts = this.previous.get(request.id);
22
+ if (!facts || (request.contents && facts.bytes === undefined))
23
+ missing.push(request);
24
+ else
25
+ current.set(request.id, request.contents ? facts : { lines: facts.lines });
26
+ }
27
+ return missing;
28
+ }
29
+ }
30
+ async function readBatch(requests, read, current) {
31
+ const blobs = await read(requests.map(({ id }) => id));
32
+ for (const { id, contents } of requests) {
33
+ const bytes = blobs.get(id);
34
+ if (!bytes)
35
+ throw new Error(`Git blob unavailable: ${id}`);
36
+ current.set(id, { lines: textLineCount(bytes), ...(contents ? { bytes: Buffer.from(bytes) } : {}) });
37
+ }
38
+ }
39
+ function* blobBatches(requests, maxBytes) {
40
+ let batch = [];
41
+ let estimatedBytes = 0;
42
+ for (const request of requests) {
43
+ if (batch.length && estimatedBytes + request.estimatedBytes > maxBytes) {
44
+ yield batch;
45
+ batch = [];
46
+ estimatedBytes = 0;
47
+ }
48
+ batch.push(request);
49
+ estimatedBytes += request.estimatedBytes;
50
+ }
51
+ if (batch.length)
52
+ yield batch;
53
+ }
54
+ //# sourceMappingURL=blob-history.js.map
@@ -15,51 +15,26 @@ export async function gitChurn(directory, commit, paths) {
15
15
  return summarizeGitHistory(log, commit, paths, shallow.trim() === 'true');
16
16
  }
17
17
  export function summarizeGitHistory(log, commit, paths, shallow) {
18
- const fields = log.split('\0');
19
- if (fields[0] !== '' || fields.at(-1) !== '')
20
- throw new Error('Invalid Git history record');
21
18
  const touches = new Map(paths.map(path => [path, 0]));
22
- let index = 1;
23
19
  let visited = 0;
24
20
  let commits = 0;
25
21
  let endingAt;
26
22
  let capReached = false;
27
- while (index < fields.length - 1) {
28
- const [sha, date, ...parents] = fields[index++].split(' ');
29
- const timestamp = Number(date);
30
- const hasParent = parents.length > 0 && parents.every(parent => oid.test(parent));
31
- const root = parents.length === 1 && parents[0] === '';
32
- if (sha === undefined || !oid.test(sha) || date === undefined || !/^\d+$/.test(date) || !Number.isSafeInteger(timestamp) || (!hasParent && !root)) {
33
- throw new Error('Invalid Git history record');
34
- }
35
- if (endingAt === undefined) {
36
- if (sha !== commit)
37
- throw new Error('Git history did not start at the inspected commit');
38
- endingAt = timestamp;
39
- }
40
- if (visited >= churnSettings.maxCommits) {
23
+ for (const record of gitRecords(log)) {
24
+ if (endingAt === undefined && record.sha !== commit)
25
+ throw new Error('Git history did not start at the inspected commit');
26
+ endingAt ??= record.timestamp;
27
+ if (visited++ >= churnSettings.maxCommits) {
41
28
  capReached = true;
42
29
  break;
43
30
  }
44
- visited++;
45
- const cutoff = endingAt - churnSettings.lookbackDays * 86400;
46
- const overlaps = hasParent && timestamp >= cutoff && timestamp <= endingAt;
47
- const changed = new Set();
48
- let first = true;
49
- while (index < fields.length && fields[index] !== '') {
50
- const path = fields[index++];
51
- if (overlaps) {
52
- const normalized = first ? path.replace(/^\n/, '') : path;
53
- if (touches.has(normalized))
54
- changed.add(normalized);
55
- }
56
- first = false;
57
- }
58
- index++;
59
- if (overlaps)
60
- commits++;
61
- for (const path of changed)
62
- touches.set(path, touches.get(path) + 1);
31
+ // Only commits with a parent, inside the window that ends at the inspected commit, count.
32
+ if (!record.hasParent || record.timestamp < endingAt - churnSettings.lookbackDays * 86400 || record.timestamp > endingAt)
33
+ continue;
34
+ commits++;
35
+ for (const path of new Set(record.paths))
36
+ if (touches.has(path))
37
+ touches.set(path, touches.get(path) + 1);
63
38
  }
64
39
  if (endingAt === undefined)
65
40
  throw new Error('Empty Git history');
@@ -68,4 +43,30 @@ export function summarizeGitHistory(log, commit, paths, shallow) {
68
43
  window: { endingAt: new Date(endingAt * 1000).toISOString(), commits, shallow, capReached },
69
44
  };
70
45
  }
46
+ /** The records of `git log -z --format=%x00%H %ct %P --name-only`: a header field, then path fields up to an empty one. */
47
+ function* gitRecords(log) {
48
+ const fields = log.split('\0');
49
+ if (fields[0] !== '' || fields.at(-1) !== '')
50
+ throw new Error('Invalid Git history record');
51
+ let index = 1;
52
+ while (index < fields.length - 1) {
53
+ const header = recordHeader(fields[index++]);
54
+ const paths = [];
55
+ // Git starts each record's path list on a new line.
56
+ for (; index < fields.length && fields[index] !== ''; index++)
57
+ paths.push(paths.length ? fields[index] : fields[index].replace(/^\n/, ''));
58
+ index++;
59
+ yield { ...header, paths };
60
+ }
61
+ }
62
+ function recordHeader(field) {
63
+ const [sha, date, ...parents] = field.split(' ');
64
+ const timestamp = Number(date);
65
+ const hasParent = parents.length > 0 && parents.every(parent => oid.test(parent));
66
+ const root = parents.length === 1 && parents[0] === '';
67
+ const named = sha !== undefined && oid.test(sha) && date !== undefined && /^\d+$/.test(date);
68
+ if (!named || !Number.isSafeInteger(timestamp) || (!hasParent && !root))
69
+ throw new Error('Invalid Git history record');
70
+ return { sha: sha, timestamp, hasParent };
71
+ }
71
72
  //# sourceMappingURL=git-churn.js.map
@@ -0,0 +1 @@
1
+ export declare function gitExecutable(path?: string | undefined): string;
@@ -0,0 +1,31 @@
1
+ import { accessSync, constants, statSync } from 'node:fs';
2
+ import { delimiter, isAbsolute, join } from 'node:path';
3
+ let resolved;
4
+ export function gitExecutable(path = process.env.PATH) {
5
+ if (resolved && resolved.path === path)
6
+ return resolved.executable;
7
+ const executable = findGit(path);
8
+ resolved = { path, executable };
9
+ return executable;
10
+ }
11
+ function findGit(path) {
12
+ // Preserve native lookup for Windows and for PATH entries relative to the child's working directory.
13
+ if (process.platform === 'win32' || path === undefined)
14
+ return 'git';
15
+ for (const directory of path.split(delimiter)) {
16
+ if (!isAbsolute(directory))
17
+ return 'git';
18
+ const candidate = join(directory, 'git');
19
+ try {
20
+ if (!statSync(candidate).isFile())
21
+ continue;
22
+ accessSync(candidate, constants.X_OK);
23
+ return candidate;
24
+ }
25
+ catch {
26
+ // Continue searching when this entry cannot run Git.
27
+ }
28
+ }
29
+ return 'git';
30
+ }
31
+ //# sourceMappingURL=git-executable.js.map
@@ -1,4 +1,5 @@
1
1
  import type { SourceSnapshot } from '../../core/model/snapshot.js';
2
+ import { GitBlobHistory } from './blob-history.js';
2
3
  export declare function gitRoot(directory: string): Promise<string>;
3
4
  export declare function physicalGitRoot(directory: string): Promise<string>;
4
5
  export declare function gitText(directory: string, args: readonly string[], timeout?: number): Promise<string>;
@@ -36,5 +37,11 @@ export declare class GitBlobReader {
36
37
  private answer;
37
38
  private stop;
38
39
  }
39
- export declare function readGitCommit(directory: string, revision: string, excludes: (path: string) => boolean, isSource: (path: string) => boolean, claims?: (path: string) => boolean): Promise<SourceSnapshot>;
40
+ export interface GitSelection {
41
+ readonly excludes: (path: string) => boolean;
42
+ readonly isSource: (path: string) => boolean;
43
+ readonly claims?: (path: string) => boolean;
44
+ readonly history?: GitBlobHistory;
45
+ }
46
+ export declare function readGitCommit(directory: string, revision: string, { excludes, isSource, claims, history }: GitSelection): Promise<SourceSnapshot>;
40
47
  export {};
@@ -1,13 +1,18 @@
1
1
  import { realpath } from 'node:fs/promises';
2
- import { execFile, spawn, spawnSync } from 'node:child_process';
2
+ import { execFile, spawn } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
- import { comparePaths, isExcludedDirectory, textLineCount, utf8 } from '../../core/model/snapshot.js';
4
+ import { comparePaths, isExcludedDirectory, utf8 } from '../../core/model/snapshot.js';
5
5
  import { isClaimedText, maxClaimedFileBytes } from '../../core/model/source.js';
6
6
  import { isGeneratedSource } from '../../core/profile/exclusions.js';
7
+ import { gitExecutable } from './git-executable.js';
8
+ import { GitBlobHistory, gitBlobBatchBytes } from './blob-history.js';
7
9
  const git = promisify(execFile);
8
- const maxBuffer = 64 * 1024 * 1024;
10
+ const maxBuffer = gitBlobBatchBytes;
9
11
  const oidPattern = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
10
- const env = { ...process.env, GIT_NO_LAZY_FETCH: '1' };
12
+ const baseEnv = { ...process.env, GIT_NO_LAZY_FETCH: '1' };
13
+ function gitEnvironment() {
14
+ return { ...baseEnv, PATH: process.env.PATH };
15
+ }
11
16
  export async function gitRoot(directory) {
12
17
  try {
13
18
  return (await gitText(directory, ['rev-parse', '--show-toplevel'])).replace(/\r?\n$/, '');
@@ -22,16 +27,16 @@ export async function physicalGitRoot(directory) {
22
27
  return realpath(await gitRoot(directory));
23
28
  }
24
29
  export async function gitText(directory, args, timeout) {
25
- const { stdout } = await git('git', ['--no-replace-objects', ...args], { cwd: directory, env, maxBuffer, timeout });
30
+ const { stdout } = await git(gitExecutable(), ['--no-replace-objects', ...args], { cwd: directory, env: gitEnvironment(), maxBuffer, timeout });
26
31
  return stdout;
27
32
  }
28
33
  export async function gitUtf8(directory, args, timeout) {
29
- const result = await git('git', ['--no-replace-objects', ...args], { cwd: directory, env, encoding: 'buffer', maxBuffer, timeout });
34
+ const result = await git(gitExecutable(), ['--no-replace-objects', ...args], { cwd: directory, env: gitEnvironment(), encoding: 'buffer', maxBuffer, timeout });
30
35
  return utf8(result.stdout);
31
36
  }
32
37
  export async function gitWorkingTreePaths(directory) {
33
38
  try {
34
- const { stdout } = await git('git', ['--no-replace-objects', 'ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.'], { cwd: directory, env: { ...env, LC_ALL: 'C' }, encoding: 'buffer', maxBuffer });
39
+ const { stdout } = await git(gitExecutable(), ['--no-replace-objects', 'ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.'], { cwd: directory, env: { ...gitEnvironment(), LC_ALL: 'C' }, encoding: 'buffer', maxBuffer });
35
40
  return [...new Set(utf8(stdout).split('\0').filter(Boolean))];
36
41
  }
37
42
  catch (error) {
@@ -73,7 +78,7 @@ export async function gitTreeFiles(directory, commit, prefix, includeSize = fals
73
78
  args.push(commit);
74
79
  if (prefix !== undefined)
75
80
  args.push('--', prefix);
76
- const tree = await git('git', args, { cwd: directory, env, encoding: 'buffer', maxBuffer });
81
+ const tree = await git(gitExecutable(), args, { cwd: directory, env: gitEnvironment(), encoding: 'buffer', maxBuffer });
77
82
  const entries = [];
78
83
  for (const entry of utf8(tree.stdout).split('\0')) {
79
84
  if (!entry)
@@ -120,7 +125,7 @@ export class GitBlobReader {
120
125
  });
121
126
  }
122
127
  start() {
123
- const child = spawn('git', ['--no-replace-objects', 'cat-file', '--batch'], { cwd: this.directory, env });
128
+ const child = spawn(gitExecutable(), ['--no-replace-objects', 'cat-file', '--batch'], { cwd: this.directory, env: gitEnvironment() });
124
129
  const errors = [];
125
130
  child.stdout.on('data', (chunk) => this.receive(chunk));
126
131
  child.stderr.on('data', (chunk) => errors.push(chunk));
@@ -184,86 +189,78 @@ function setHeld(child, held) {
184
189
  handle.unref();
185
190
  }
186
191
  }
187
- export async function readGitCommit(directory, revision, excludes, isSource, claims) {
192
+ export async function readGitCommit(directory, revision, { excludes, isSource, claims, history }) {
188
193
  const id = await resolveGitCommit(directory, revision);
189
194
  const tracked = (await gitTreeFiles(directory, id, undefined, true)).filter(({ path }) => !path.split('/').slice(0, -1).some(isExcludedDirectory) && !excludes(path));
190
- const entries = tracked.filter(entry => isSource(entry.path));
191
- const blobs = readBlobs(directory, [...new Set(entries.map(entry => entry.oid))]);
195
+ const entries = tracked.filter(({ path }) => isSource(path));
196
+ const claimed = tracked.filter(({ path }) => !isSource(path) && claims?.(path));
197
+ const oversized = new Set(claimed.filter(({ size }) => size !== undefined && size > maxClaimedFileBytes).map(({ path }) => path));
198
+ const requested = claimed.filter(({ path }) => !oversized.has(path));
199
+ const blobs = await (history ?? new GitBlobHistory()).read(blobRequests(tracked.filter(({ path }) => !oversized.has(path)), entries, requested), ids => readBlobs(directory, ids));
192
200
  const generated = new Set();
193
201
  const files = entries.flatMap(({ path, oid }) => {
194
- const bytes = blobs.get(oid);
202
+ const bytes = blobs.get(oid)?.bytes;
195
203
  if (!bytes)
196
204
  throw new Error(`Git blob unavailable: ${oid}`);
197
205
  if (!isGeneratedSource(bytes))
198
- return [{ path, bytes }];
206
+ return [{ path, bytes: snapshotBytes(bytes, history) }];
199
207
  generated.add(path);
200
208
  return [];
201
209
  });
202
- const claimed = tracked.filter(({ path }) => !isSource(path) && claims?.(path));
203
- const oversized = new Set(claimed.filter(({ size }) => size !== undefined && size > maxClaimedFileBytes).map(({ path }) => path));
204
- const requested = new Set(claimed.filter(({ path }) => !oversized.has(path)).map(({ oid }) => oid));
205
- const claimedBlobs = new Map();
206
- const counts = inventoryLineCounts(directory, tracked.filter(({ path }) => !oversized.has(path)), blobs, (oid, bytes) => { if (requested.has(oid) && isClaimedText(bytes))
207
- claimedBlobs.set(oid, bytes); });
208
- for (const { path, oid } of claimed) {
209
- const bytes = claimedBlobs.get(oid);
210
- if (bytes && !oversized.has(path))
211
- files.push({ path, bytes });
210
+ for (const { path, oid } of requested) {
211
+ const bytes = blobs.get(oid)?.bytes;
212
+ if (bytes && isClaimedText(bytes))
213
+ files.push({ path, bytes: snapshotBytes(bytes, history) });
212
214
  }
213
215
  files.sort((left, right) => comparePaths(left.path, right.path));
214
- const inventory = tracked.filter(({ path }) => !generated.has(path)).map(({ path, oid, size }) => ({ path, lines: counts.get(oid) ?? null, ...(size === undefined ? {} : { bytes: size }) }));
216
+ const inventory = tracked.filter(({ path }) => !generated.has(path)).map(({ path, oid, size }) => ({ path, lines: blobs.get(oid)?.lines ?? null, ...(size === undefined ? {} : { bytes: size }) }));
215
217
  const blobIds = new Map(tracked.map(({ path, oid }) => [path, oid]));
216
218
  return { subject: { kind: 'commit', id }, files, blobIds, inventory, generatedExcluded: [...generated].sort(comparePaths),
217
219
  ...(oversized.size ? { oversizedClaims: [...oversized].sort(comparePaths) } : {}) };
218
220
  }
219
- function inventoryLineCounts(directory, entries, sources, capture) {
220
- const lines = new Map([...sources].map(([oid, value]) => [oid, textLineCount(value)]));
221
- for (const [oid, bytes] of sources)
222
- capture(oid, bytes);
223
- const entriesById = new Map(entries.map(entry => [entry.oid, entry]));
224
- let batch = [];
225
- let bytes = 0;
226
- for (const [oid, { size }] of entriesById) {
227
- if (lines.has(oid) || size === undefined || size + 128 > maxBuffer)
228
- continue;
229
- const estimate = size + 128;
230
- if (bytes + estimate > maxBuffer)
231
- flush();
232
- batch.push(oid);
233
- bytes += estimate;
234
- }
235
- flush();
236
- return lines;
237
- function flush() {
238
- for (const [oid, value] of readBlobs(directory, batch)) {
239
- lines.set(oid, textLineCount(value));
240
- capture(oid, value);
221
+ function snapshotBytes(bytes, history) {
222
+ // Inspectors receive mutable byte arrays. Keep retained Git data independent of those inputs.
223
+ return history === undefined ? bytes : Buffer.from(bytes);
224
+ }
225
+ function blobRequests(tracked, sources, claimed) {
226
+ const required = new Set(sources.map(({ oid }) => oid));
227
+ const contents = new Set([...required, ...claimed.map(({ oid }) => oid)]);
228
+ const byId = new Map(tracked.map(({ oid, size }) => [oid, size]));
229
+ const requests = [];
230
+ for (const [id, size] of byId) {
231
+ if (size !== undefined && size + 128 <= maxBuffer) {
232
+ requests.push({ id, estimatedBytes: size + 128, contents: contents.has(id) });
233
+ }
234
+ else if (required.has(id)) {
235
+ requests.push({ id, estimatedBytes: maxBuffer, contents: true });
241
236
  }
242
- batch = [];
243
- bytes = 0;
244
237
  }
238
+ return requests;
245
239
  }
246
- function readBlobs(directory, ids) {
240
+ async function readBlobs(directory, ids) {
241
+ const command = git(gitExecutable(), ['--no-replace-objects', 'cat-file', '--batch'], { cwd: directory, env: gitEnvironment(), encoding: 'buffer', maxBuffer });
242
+ command.child.stdin?.on('error', () => { });
243
+ command.child.stdin?.end(`${ids.join('\n')}\n`);
244
+ const { stdout } = await command.catch((error) => {
245
+ if (error instanceof Error && 'code' in error && typeof error.code === 'number'
246
+ && 'stderr' in error && Buffer.isBuffer(error.stderr)) {
247
+ throw new Error(`git cat-file failed: ${error.stderr.toString('utf8').trim()}`, { cause: error });
248
+ }
249
+ throw error;
250
+ });
247
251
  const blobs = new Map();
248
- if (ids.length === 0)
249
- return blobs;
250
- const result = spawnSync('git', ['--no-replace-objects', 'cat-file', '--batch'], { cwd: directory, env, input: `${ids.join('\n')}\n`, maxBuffer });
251
- if (result.error)
252
- throw result.error;
253
- if (result.status !== 0)
254
- throw new Error(`git cat-file failed: ${result.stderr.toString('utf8').trim()}`);
255
252
  let cursor = 0;
256
253
  for (const oid of ids) {
257
- const end = result.stdout.indexOf(10, cursor);
254
+ const end = stdout.indexOf(10, cursor);
258
255
  if (end < 0)
259
256
  throw new Error(`Missing Git blob header: ${oid}`);
260
- const match = /^([a-f0-9]+) blob (\d+)$/.exec(result.stdout.toString('ascii', cursor, end));
257
+ const match = /^([a-f0-9]+) blob (\d+)$/.exec(stdout.toString('ascii', cursor, end));
261
258
  const size = Number(match?.[2]);
262
259
  const from = end + 1;
263
260
  const to = from + size;
264
- if (match?.[1] !== oid || !Number.isSafeInteger(size) || result.stdout[to] !== 10)
261
+ if (match?.[1] !== oid || !Number.isSafeInteger(size) || stdout[to] !== 10)
265
262
  throw new Error(`Invalid Git blob: ${oid}`);
266
- blobs.set(oid, result.stdout.subarray(from, to));
263
+ blobs.set(oid, stdout.subarray(from, to));
267
264
  cursor = to + 1;
268
265
  }
269
266
  return blobs;
@@ -1,3 +1,4 @@
1
+ import type { GitSelection } from './git.js';
1
2
  export interface SourceSelection {
2
3
  readonly directory: string;
3
4
  readonly output: string;
@@ -7,7 +8,7 @@ export interface SourceSelection {
7
8
  readonly revision: string;
8
9
  };
9
10
  }
10
- export declare function readInspectionSource(request: SourceSelection, excludes: (path: string) => boolean, isSource: (path: string) => boolean, claims?: (path: string) => boolean): Promise<{
11
+ export declare function readInspectionSource(request: SourceSelection, selection: GitSelection): Promise<{
11
12
  root: string;
12
13
  snapshot: import("../../plugin.js").SourceSnapshot;
13
14
  excludedOutput: string | null;
@@ -2,7 +2,8 @@ import { realpath } from 'node:fs/promises';
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
3
  import { gitRoot, gitWorkingTreePaths, readGitCommit } from './git.js';
4
4
  import { containsPath, readWorkingTree } from './local.js';
5
- export async function readInspectionSource(request, excludes, isSource, claims) {
5
+ export async function readInspectionSource(request, selection) {
6
+ const { excludes, isSource, claims } = selection;
6
7
  const root = await realpath('workingTree' in request.source ? request.directory : await gitRoot(request.directory));
7
8
  const output = await physicalPath(resolve(request.output));
8
9
  if (containsPath(output, root) || output.split(sep).includes('.git')) {
@@ -10,7 +11,7 @@ export async function readInspectionSource(request, excludes, isSource, claims)
10
11
  }
11
12
  const snapshot = 'workingTree' in request.source
12
13
  ? await readWorkingTree(root, output, excludes, isSource, claims, await gitWorkingTreePaths(root))
13
- : await readGitCommit(root, request.source.revision, excludes, isSource, claims);
14
+ : await readGitCommit(root, request.source.revision, selection);
14
15
  const excludedOutput = snapshot.subject.kind === 'working-tree' && containsPath(root, output)
15
16
  ? relative(root, output).split(sep).join('/') : null;
16
17
  return { root, snapshot, excludedOutput, output };
@@ -1,10 +1,11 @@
1
1
  import { utf8 } from '../../core/model/snapshot.js';
2
2
  import { validSubjectId } from '../../core/model/report.js';
3
3
  import { isSourcePathname } from '../../core/ports/source-provider.js';
4
+ import { cacheRoot } from '../cache/root.js';
4
5
  import { GitBlobBatch } from './blob-batch.js';
5
6
  import { gitText, gitTreeFiles } from './git.js';
6
- import { cachedBlob, sourceCacheRoot } from './source-cache.js';
7
- export function readLocalSources(repository, cache = sourceCacheRoot()) {
7
+ import { cachedBlob } from './source-cache.js';
8
+ export function readLocalSources(repository, cache = cacheRoot()) {
8
9
  const git = new GitBlobBatch(repository);
9
10
  const known = new Map();
10
11
  return {
@@ -1,3 +1 @@
1
- export declare function sourceCacheRoot(env?: NodeJS.ProcessEnv, system?: NodeJS.Platform, home?: string): string;
2
- export declare function clearSourceCache(root?: string): Promise<void>;
3
1
  export declare function cachedBlob(root: string, oid: string, load: () => Promise<Buffer | undefined>): Promise<Buffer | undefined>;