repometry 0.7.0 → 0.8.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 (83) hide show
  1. package/README.md +23 -20
  2. package/package.json +1 -1
  3. package/target/main/resources/config/process-plugins-v1.schema.json +4 -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/viewer-inspection-v1.schema.json +2 -1
  7. package/target/main/resources/viewer/files.css +1 -0
  8. package/target/main/ts/api/git/git-reader.d.ts +10 -2
  9. package/target/main/ts/api/git/git-reader.js +74 -35
  10. package/target/main/ts/api/git/git.d.ts +19 -1
  11. package/target/main/ts/api/git/git.js +97 -7
  12. package/target/main/ts/api/import/go-cover.d.ts +13 -0
  13. package/target/main/ts/api/import/go-cover.js +150 -0
  14. package/target/main/ts/api/import/lcov-files.d.ts +6 -1
  15. package/target/main/ts/api/import/lcov-files.js +27 -7
  16. package/target/main/ts/api/process/docker-tool-runner.js +5 -21
  17. package/target/main/ts/api/process/host-language-runner.d.ts +13 -0
  18. package/target/main/ts/api/process/host-language-runner.js +176 -0
  19. package/target/main/ts/api/process/plugin.d.ts +4 -1
  20. package/target/main/ts/api/process/plugin.js +7 -3
  21. package/target/main/ts/api/process/tool-snapshot.d.ts +3 -0
  22. package/target/main/ts/api/process/tool-snapshot.js +26 -0
  23. package/target/main/ts/cli/imports.d.ts +1 -0
  24. package/target/main/ts/cli/imports.js +5 -2
  25. package/target/main/ts/cli/main.js +46 -15
  26. package/target/main/ts/compose/analysis-files.d.ts +2 -1
  27. package/target/main/ts/compose/analysis-files.js +19 -5
  28. package/target/main/ts/compose/analysis-imports.js +2 -1
  29. package/target/main/ts/compose/analysis-report.d.ts +1 -0
  30. package/target/main/ts/compose/analysis-report.js +13 -12
  31. package/target/main/ts/compose/analysis-repository.d.ts +2 -1
  32. package/target/main/ts/compose/analysis-repository.js +42 -4
  33. package/target/main/ts/compose/analysis-sources.d.ts +5 -0
  34. package/target/main/ts/compose/analysis-sources.js +10 -3
  35. package/target/main/ts/compose/analyze-snapshot.d.ts +2 -1
  36. package/target/main/ts/compose/analyze-snapshot.js +5 -3
  37. package/target/main/ts/compose/diff-coverage.d.ts +2 -1
  38. package/target/main/ts/compose/diff-coverage.js +8 -6
  39. package/target/main/ts/compose/history-cache.d.ts +29 -0
  40. package/target/main/ts/compose/history-cache.js +57 -0
  41. package/target/main/ts/compose/inspect.d.ts +6 -1
  42. package/target/main/ts/compose/inspect.js +10 -10
  43. package/target/main/ts/compose/inspection-coverage.d.ts +9 -0
  44. package/target/main/ts/compose/inspection-coverage.js +9 -0
  45. package/target/main/ts/compose/languages.d.ts +6 -1
  46. package/target/main/ts/compose/languages.js +19 -6
  47. package/target/main/ts/compose/native-language-plugins.d.ts +6 -0
  48. package/target/main/ts/compose/native-language-plugins.js +40 -0
  49. package/target/main/ts/compose/plugin-list.d.ts +3 -8
  50. package/target/main/ts/compose/plugin-list.js +12 -5
  51. package/target/main/ts/compose/prepare-metabranch.js +1 -1
  52. package/target/main/ts/compose/process-plugins.js +6 -5
  53. package/target/main/ts/compose/review.d.ts +1 -2
  54. package/target/main/ts/compose/review.js +2 -2
  55. package/target/main/ts/core/engine/plan.js +5 -6
  56. package/target/main/ts/core/engine/plugin.d.ts +2 -0
  57. package/target/main/ts/core/model/file-types.d.ts +1 -0
  58. package/target/main/ts/core/model/file-types.js +14 -3
  59. package/target/main/ts/core/model/quality-summary.js +2 -0
  60. package/target/main/ts/core/model/source.d.ts +2 -0
  61. package/target/main/ts/core/usecases/inspect.d.ts +1 -1
  62. package/target/main/ts/core/usecases/inspect.js +1 -1
  63. package/target/main/ts/plugins/security/dockerfile.js +6 -15
  64. package/target/main/ts/report/html/app/viewer-language-bar.d.ts +2 -0
  65. package/target/main/ts/report/html/app/viewer-language-bar.js +5 -1
  66. package/target/main/ts/report/html/app/viewer-profile.js +9 -2
  67. package/target/main/ts/report/json/projections/commit-summary.d.ts +1 -0
  68. package/target/main/ts/report/json/projections/commit-summary.js +5 -0
  69. package/target/main/ts/report/json/projections/file-metrics.js +39 -44
  70. package/target/main/ts/report/json/projections/inspection-details.js +3 -2
  71. package/target/main/ts/report/json/store/directory.d.ts +3 -0
  72. package/target/main/ts/report/json/store/directory.js +19 -0
  73. package/target/main/ts/report/json/store/local-store.d.ts +14 -2
  74. package/target/main/ts/report/json/store/local-store.js +74 -60
  75. package/target/main/ts/report/json/store/object-store.d.ts +14 -0
  76. package/target/main/ts/report/json/store/object-store.js +73 -0
  77. package/target/main/ts/report/json/store/report-tree.d.ts +46 -0
  78. package/target/main/ts/report/json/store/report-tree.js +290 -0
  79. package/target/main/ts/report/json/store/store-check.d.ts +32 -0
  80. package/target/main/ts/report/json/store/store-check.js +144 -0
  81. package/target/main/ts/report/json/validation/report.d.ts +6 -1
  82. package/target/main/ts/report/json/validation/report.js +10 -4
  83. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +1 -0
@@ -23,8 +23,7 @@ export function fileMetrics(report, registry = { id: fileTypeId, catalog: [] })
23
23
  function languageIndex(id, analysed) {
24
24
  const existing = languageIndexes.get(id);
25
25
  if (existing !== undefined) {
26
- if (analysed)
27
- languages[existing].analysed = true;
26
+ languages[existing].analysed ||= analysed;
28
27
  return existing;
29
28
  }
30
29
  const index = languages.length;
@@ -48,8 +47,7 @@ export function fileMetrics(report, registry = { id: fileTypeId, catalog: [] })
48
47
  const skipped = new Set(report.ruleSkips?.map(({ path }) => path));
49
48
  addFileQuality(byPath, duplicatedLines, report.findings, skipped);
50
49
  let unassignedDiagnostics = 0;
51
- for (const diagnostic of report.diagnostics) {
52
- const { path, operation } = diagnostic;
50
+ for (const { path, operation } of report.diagnostics) {
53
51
  const target = path === undefined ? undefined
54
52
  : operation === `${legacySyntaxPlugin}/parse` || operation.startsWith('structure/') ? file(path) : byPath.get(path);
55
53
  if (target)
@@ -60,9 +58,7 @@ export function fileMetrics(report, registry = { id: fileTypeId, catalog: [] })
60
58
  const files = [...byPath.values()].sort(byName);
61
59
  const directories = new Map();
62
60
  for (const entry of files) {
63
- if (entry.language === undefined) {
64
- entry.language = languageIndex(registry.id(entry.path), entry.lines !== null || entry.lineCoverage !== null || entry.functions !== null);
65
- }
61
+ entry.language ??= languageIndex(registry.id(entry.path), entry.lines !== null || entry.lineCoverage !== null || entry.functions !== null);
66
62
  if (pluginMetrics && entry.analysed !== false) {
67
63
  const values = pluginMetrics.values(entry.path);
68
64
  if (Object.keys(values).length)
@@ -71,24 +67,11 @@ export function fileMetrics(report, registry = { id: fileTypeId, catalog: [] })
71
67
  if (entry.functions === 0 && !entry.complexity && pluginMetrics?.isAvailable(definitions.complexity, entry.path) !== false) {
72
68
  entry.complexity = { sum: 0, maximum: null, measuredFunctions: 0 };
73
69
  }
74
- let path = entry.path;
75
- do {
76
- path = path.slice(0, Math.max(0, path.lastIndexOf('/')));
77
- let directory = directories.get(path);
78
- if (!directory) {
79
- directory = { ...emptyMetrics(path), files: 0, sizeMeasuredFiles: 0, coverageMeasuredFiles: 0 };
80
- directories.set(path, directory);
81
- }
82
- addFile(directory, entry);
83
- } while (path !== '');
70
+ rollUpFile(directories, entry);
84
71
  }
85
72
  if (pluginMetrics) {
86
- for (const entry of directories.values()) {
87
- const values = pluginMetrics.values(entry.path, true);
88
- if (Object.keys(values).length)
89
- entry.values = values;
90
- applyDirectoryAvailability(entry, pluginMetrics.isAvailable);
91
- }
73
+ for (const entry of directories.values())
74
+ applyDirectoryProjection(entry, pluginMetrics);
92
75
  }
93
76
  const complexity = files.filter(entry => entry.complexity?.maximum != null)
94
77
  .sort((left, right) => right.complexity.maximum - left.complexity.maximum
@@ -143,8 +126,11 @@ function collectMeasurements(rows, file, includeMeasuredFiles) {
143
126
  }
144
127
  return duplicated;
145
128
  }
146
- function applyDirectoryAvailability(entry, available) {
147
- const known = (id) => available(id, entry.path, true);
129
+ function applyDirectoryProjection(entry, projection) {
130
+ const values = projection.values(entry.path, true);
131
+ if (Object.keys(values).length)
132
+ entry.values = values;
133
+ const known = (id) => projection.isAvailable(id, entry.path, true);
148
134
  if (!known(definitions.functions))
149
135
  entry.functions = null;
150
136
  if (!known(definitions.complexity))
@@ -185,25 +171,34 @@ function emptyMetrics(path) {
185
171
  function byName(left, right) {
186
172
  return comparePaths(left.path, right.path);
187
173
  }
188
- function addFile(directory, file) {
189
- directory.files++;
190
- if (file.lines !== null)
191
- directory.sizeMeasuredFiles++;
192
- directory.lines = sumKnown(directory.lines, file.lines);
193
- if (file.bytes !== undefined)
194
- directory.bytes = (directory.bytes ?? 0) + file.bytes;
195
- directory.functions = sumKnown(directory.functions, file.functions);
196
- directory.complexity = addComplexity(directory.complexity, file.complexity);
197
- if (file.lineCoverage) {
198
- directory.coverageMeasuredFiles++;
199
- directory.lineCoverage = {
200
- covered: (directory.lineCoverage?.covered ?? 0) + file.lineCoverage.covered,
201
- total: (directory.lineCoverage?.total ?? 0) + file.lineCoverage.total,
202
- };
203
- }
204
- directory.diagnosticCount += file.diagnosticCount;
205
- if (file.quality)
206
- addQuality(quality(directory), file.quality);
174
+ function rollUpFile(directories, file) {
175
+ let path = file.path;
176
+ do {
177
+ path = path.slice(0, Math.max(0, path.lastIndexOf('/')));
178
+ let directory = directories.get(path);
179
+ if (!directory) {
180
+ directory = { ...emptyMetrics(path), files: 0, sizeMeasuredFiles: 0, coverageMeasuredFiles: 0 };
181
+ directories.set(path, directory);
182
+ }
183
+ directory.files++;
184
+ if (file.lines !== null)
185
+ directory.sizeMeasuredFiles++;
186
+ directory.lines = sumKnown(directory.lines, file.lines);
187
+ if (file.bytes !== undefined)
188
+ directory.bytes = (directory.bytes ?? 0) + file.bytes;
189
+ directory.functions = sumKnown(directory.functions, file.functions);
190
+ directory.complexity = addComplexity(directory.complexity, file.complexity);
191
+ if (file.lineCoverage) {
192
+ directory.coverageMeasuredFiles++;
193
+ directory.lineCoverage = {
194
+ covered: (directory.lineCoverage?.covered ?? 0) + file.lineCoverage.covered,
195
+ total: (directory.lineCoverage?.total ?? 0) + file.lineCoverage.total,
196
+ };
197
+ }
198
+ directory.diagnosticCount += file.diagnosticCount;
199
+ if (file.quality)
200
+ addQuality(quality(directory), file.quality);
201
+ } while (path !== '');
207
202
  }
208
203
  function quality(entry) {
209
204
  return entry.quality ??= {};
@@ -58,11 +58,12 @@ export function profileSettings(applied) {
58
58
  };
59
59
  }
60
60
  function profileLanguages(plugins, recordedExtensions) {
61
- const recorded = plugins.flatMap(({ id: plugin, providesLanguages }) => {
61
+ const recorded = plugins.flatMap(({ id: plugin, providesLanguages, unavailableReason }) => {
62
62
  if (typeof plugin !== 'string' || !Array.isArray(providesLanguages))
63
63
  return [];
64
64
  return providesLanguages.flatMap(language => isRecord(language) && isLanguageDisplay(language)
65
- ? [{ plugin, id: language.id, label: language.label, extensions: strings(language.extensions), globs: strings(language.globs) }]
65
+ ? [{ plugin, id: language.id, label: language.label, extensions: strings(language.extensions), globs: strings(language.globs),
66
+ ...(typeof unavailableReason === 'string' ? { unavailableReason } : {}) }]
66
67
  : []);
67
68
  });
68
69
  if (recorded.length)
@@ -0,0 +1,3 @@
1
+ export declare function hasCode(error: unknown, code: string): boolean;
2
+ export declare function ensureDirectory(path: string): Promise<void>;
3
+ export declare function checkDirectory(path: string): Promise<void>;
@@ -0,0 +1,19 @@
1
+ import { lstat, mkdir } from 'node:fs/promises';
2
+ export function hasCode(error, code) {
3
+ return error instanceof Error && 'code' in error && error.code === code;
4
+ }
5
+ export async function ensureDirectory(path) {
6
+ try {
7
+ await mkdir(path, { mode: 0o700 });
8
+ }
9
+ catch (error) {
10
+ if (!hasCode(error, 'EEXIST'))
11
+ throw error;
12
+ }
13
+ await checkDirectory(path);
14
+ }
15
+ export async function checkDirectory(path) {
16
+ if (!(await lstat(path)).isDirectory())
17
+ throw new Error(`Expected a directory: ${path}`);
18
+ }
19
+ //# sourceMappingURL=directory.js.map
@@ -1,13 +1,25 @@
1
1
  import type { Subject } from '../../../core/model/snapshot.js';
2
2
  import type { CommitSummary } from '../wire/summary-model.js';
3
3
  import type { Report, ReportStore } from '../validation/report.js';
4
+ import { LocalObjectStore } from './object-store.js';
4
5
  export declare class LocalReportStore implements ReportStore {
5
6
  private readonly directory;
7
+ readonly objects: LocalObjectStore;
8
+ private readonly cache;
6
9
  constructor(directory: string);
7
- save(report: Report): Promise<void>;
10
+ save(report: Report, { deferSummary }?: {
11
+ deferSummary?: boolean | undefined;
12
+ }): Promise<void>;
8
13
  read(subject: Subject): Promise<Report>;
9
14
  list(): Promise<readonly Report[]>;
15
+ /** Saved subjects by folder name, whether or not their report is published yet. */
16
+ subjects(): Promise<readonly Subject[]>;
17
+ /** The saved report file of a subject. */
18
+ text(subject: Subject): Promise<string>;
10
19
  listSummaries(): Promise<readonly CommitSummary[]>;
11
- private refreshSummary;
20
+ refreshSummary(): Promise<void>;
21
+ private readWith;
12
22
  private folder;
13
23
  }
24
+ /** The summary row a saved report keeps on its first line, unless it has none or it needs recalculating. */
25
+ export declare function headerSummary(text: string, sha: string): CommitSummary | undefined;
@@ -2,49 +2,71 @@ import { lstat, mkdir, open, readFile, readdir } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
4
  import { isRecord } from '../../../core/engine/plugin.js';
5
- import { commitSummary, orderSummaries, repositorySummary } from '../projections/commit-summary.js';
5
+ import { commitSummary, needsMaintainabilityRefresh, orderSummaries, repositorySummary } from '../projections/commit-summary.js';
6
6
  import { summarySchema } from '../wire/summary-model.js';
7
- import { compactJsonSchema, packJson } from '../wire/compact-json.js';
8
- import { compareReports, readReport, readReportText, validSubjectId } from '../validation/report.js';
7
+ import { compactJsonSchema } from '../wire/compact-json.js';
8
+ import { compareReports, readReport, readStoredReport, validSubjectId } from '../validation/report.js';
9
9
  import { validateSummaryRow } from '../validation/summary-validation.js';
10
+ import { checkDirectory, ensureDirectory, hasCode } from './directory.js';
11
+ import { LocalObjectStore } from './object-store.js';
10
12
  import { replaceFile } from './replace-file.js';
11
- const packedHeader = `{"schema":"${compactJsonSchema}","summary":`;
13
+ import { ObjectCache, rebuildReport, splitReport, storedReportSchema } from './report-tree.js';
14
+ const headerStart = `{"schema":"${storedReportSchema}"`;
15
+ // Reports saved before objects carried the same summary header under the compact JSON schema.
16
+ const summaryHeaders = [headerStart, `{"schema":"${compactJsonSchema}"`].map(start => `${start},"summary":`);
12
17
  export class LocalReportStore {
13
18
  directory;
19
+ objects;
20
+ cache = new ObjectCache();
14
21
  constructor(directory) {
15
22
  this.directory = directory;
23
+ this.objects = new LocalObjectStore(directory);
16
24
  }
17
- async save(report) {
25
+ async save(report, { deferSummary = false } = {}) {
18
26
  readReport(report);
19
27
  const base = join(this.directory, subjectFolder(report.subject.kind));
20
28
  const folder = this.folder(report.subject);
21
29
  await mkdir(this.directory, { mode: 0o700, recursive: true });
22
30
  await ensureDirectory(base);
23
31
  await ensureDirectory(folder);
24
- const packed = packJson(JSON.parse(JSON.stringify(report)));
25
- const { strings, shapes, data } = packed;
32
+ const value = JSON.parse(JSON.stringify(report));
33
+ const { stored, objects } = splitReport(value);
34
+ const saved = { read: async (ids) => ids.map(id => JSON.parse(objects.get(id))) };
35
+ if (JSON.stringify(await rebuildReport(stored, saved)) !== JSON.stringify(value)) {
36
+ throw new Error(`The store cannot keep report ${report.subject.id} exactly`);
37
+ }
26
38
  const row = report.subject.kind === 'commit' ? commitSummary(report) : undefined;
27
39
  if (row && !validateSummaryRow(row))
28
40
  throw new Error(`Invalid report summary: ${report.subject.id}`);
41
+ // Objects go first, so a published commit file never names a missing object.
42
+ await this.objects.write(objects);
29
43
  // Keep the small index row on the first line of the same atomic file as the report.
30
- const contents = row
31
- ? `${packedHeader}${JSON.stringify(row)},\n${JSON.stringify({ strings, shapes, data }).slice(1)}\n`
32
- : `${JSON.stringify(packed)}\n`;
33
- await replaceFile(folder, 'report.json', contents);
34
- if (report.subject.kind === 'commit')
44
+ const body = JSON.stringify(stored).slice(1);
45
+ await replaceFile(folder, 'report.json', row ? `${headerStart},"summary":${JSON.stringify(row)},\n${body}\n` : `${headerStart},${body}\n`);
46
+ if (report.subject.kind === 'commit' && !deferSummary)
35
47
  await this.refreshSummary();
36
48
  }
37
- async read(subject) {
38
- const folder = this.folder(subject);
39
- const path = join(folder, 'report.json');
40
- await checkDirectory(join(this.directory, subjectFolder(subject.kind)));
41
- await checkDirectory(folder);
42
- if (!(await lstat(path)).isFile())
43
- throw new Error(`Expected a report file: ${path}`);
44
- return readReportText(await readFile(path, 'utf8'), subject);
49
+ read(subject) {
50
+ return this.readWith(subject, this.objects.source(this.cache));
45
51
  }
46
52
  async list() {
53
+ const objects = this.objects.source(this.cache);
47
54
  const reports = [];
55
+ for (const subject of await this.subjects()) {
56
+ try {
57
+ reports.push(await this.readWith(subject, objects));
58
+ }
59
+ catch (error) {
60
+ // A writer may have created the directory but not published its report yet.
61
+ if (!hasCode(error, 'ENOENT'))
62
+ throw error;
63
+ }
64
+ }
65
+ return reports.sort(compareReports);
66
+ }
67
+ /** Saved subjects by folder name, whether or not their report is published yet. */
68
+ async subjects() {
69
+ const subjects = [];
48
70
  for (const kind of ['commit', 'working-tree']) {
49
71
  const base = join(this.directory, subjectFolder(kind));
50
72
  try {
@@ -56,19 +78,21 @@ export class LocalReportStore {
56
78
  throw error;
57
79
  }
58
80
  for (const entry of await readdir(base, { withFileTypes: true })) {
59
- if (!entry.isDirectory() || !validSubjectId(kind, entry.name))
60
- continue;
61
- try {
62
- reports.push(await this.read({ kind, id: entry.name }));
63
- }
64
- catch (error) {
65
- // A writer may have created the directory but not published its report yet.
66
- if (!hasCode(error, 'ENOENT'))
67
- throw error;
68
- }
81
+ if (entry.isDirectory() && validSubjectId(kind, entry.name))
82
+ subjects.push({ kind, id: entry.name });
69
83
  }
70
84
  }
71
- return reports.sort(compareReports);
85
+ return subjects;
86
+ }
87
+ /** The saved report file of a subject. */
88
+ async text(subject) {
89
+ const folder = this.folder(subject);
90
+ const path = join(folder, 'report.json');
91
+ await checkDirectory(join(this.directory, subjectFolder(subject.kind)));
92
+ await checkDirectory(folder);
93
+ if (!(await lstat(path)).isFile())
94
+ throw new Error(`Expected a report file: ${path}`);
95
+ return readFile(path, 'utf8');
72
96
  }
73
97
  async listSummaries() {
74
98
  const base = join(this.directory, 'commits');
@@ -120,6 +144,9 @@ export class LocalReportStore {
120
144
  }
121
145
  throw new Error('Reports kept changing during summary publication. The inspection is saved and the summary can be refreshed by retrying.');
122
146
  }
147
+ async readWith(subject, objects) {
148
+ return readStoredReport(await this.text(subject), subject, objects);
149
+ }
123
150
  folder(subject) {
124
151
  if (!validSubjectId(subject.kind, subject.id))
125
152
  throw new Error(`Invalid ${subject.kind} ID: ${subject.id}`);
@@ -129,42 +156,29 @@ export class LocalReportStore {
129
156
  async function readSummaryHeader(path, sha) {
130
157
  const file = await open(path, 'r');
131
158
  try {
132
- const buffer = Buffer.alloc(4096);
159
+ const buffer = Buffer.alloc(64 * 1024);
133
160
  const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
134
- const end = buffer.subarray(0, bytesRead).indexOf(10);
135
- if (end < 0)
136
- return undefined;
137
- const first = buffer.toString('utf8', 0, end);
138
- if (!first.startsWith(packedHeader) || !first.endsWith(','))
139
- return undefined;
140
- const envelope = JSON.parse(first.slice(0, -1) + '}');
141
- if (!isRecord(envelope) || !validateSummaryRow(envelope.summary) || envelope.summary.sha !== sha
142
- || !envelope.summary.revision || envelope.summary.detail !== undefined)
143
- throw new Error(`Invalid report summary: ${sha}`);
144
- return envelope.summary;
161
+ return headerSummary(buffer.toString('utf8', 0, bytesRead), sha);
145
162
  }
146
163
  finally {
147
164
  await file.close();
148
165
  }
149
166
  }
167
+ /** The summary row a saved report keeps on its first line, unless it has none or it needs recalculating. */
168
+ export function headerSummary(text, sha) {
169
+ const end = text.indexOf('\n');
170
+ if (end < 0)
171
+ return undefined;
172
+ const first = text.slice(0, end);
173
+ if (!summaryHeaders.some(start => first.startsWith(start)) || !first.endsWith(','))
174
+ return undefined;
175
+ const envelope = JSON.parse(first.slice(0, -1) + '}');
176
+ if (!isRecord(envelope) || !validateSummaryRow(envelope.summary) || envelope.summary.sha !== sha
177
+ || !envelope.summary.revision || envelope.summary.detail !== undefined)
178
+ throw new Error(`Invalid report summary: ${sha}`);
179
+ return needsMaintainabilityRefresh(envelope.summary) ? undefined : envelope.summary;
180
+ }
150
181
  function subjectFolder(kind) {
151
182
  return kind === 'commit' ? 'commits' : 'working-trees';
152
183
  }
153
- function hasCode(error, code) {
154
- return error instanceof Error && 'code' in error && error.code === code;
155
- }
156
- async function ensureDirectory(path) {
157
- try {
158
- await mkdir(path, { mode: 0o700 });
159
- }
160
- catch (error) {
161
- if (!hasCode(error, 'EEXIST'))
162
- throw error;
163
- }
164
- await checkDirectory(path);
165
- }
166
- async function checkDirectory(path) {
167
- if (!(await lstat(path)).isDirectory())
168
- throw new Error(`Expected a directory: ${path}`);
169
- }
170
184
  //# sourceMappingURL=local-store.js.map
@@ -0,0 +1,14 @@
1
+ import type { ObjectCache } from './report-tree.js';
2
+ import type { ObjectSource } from './report-tree.js';
3
+ /** Content-addressed report objects under `<store>/objects`. Objects are immutable: a valid one is never rewritten. */
4
+ export declare class LocalObjectStore {
5
+ private readonly directory;
6
+ constructor(directory: string);
7
+ source(cache?: ObjectCache): ObjectSource;
8
+ /** Writes each object that is missing or fails its check. */
9
+ write(objects: ReadonlyMap<string, string>): Promise<void>;
10
+ valid(id: string): Promise<boolean>;
11
+ bytes(id: string): Promise<Buffer | undefined>;
12
+ ids(): Promise<readonly string[]>;
13
+ remove(id: string): Promise<void>;
14
+ }
@@ -0,0 +1,73 @@
1
+ import { readFile, readdir, rm } from 'node:fs/promises';
2
+ import { basename, dirname, join } from 'node:path';
3
+ import { checkDirectory, ensureDirectory, hasCode } from './directory.js';
4
+ import { replaceFile } from './replace-file.js';
5
+ import { ObjectError, objectPath, objectText, storedObjects } from './report-tree.js';
6
+ /** Content-addressed report objects under `<store>/objects`. Objects are immutable: a valid one is never rewritten. */
7
+ export class LocalObjectStore {
8
+ directory;
9
+ constructor(directory) {
10
+ this.directory = directory;
11
+ }
12
+ source(cache) {
13
+ return storedObjects(ids => Promise.all(ids.map(id => this.bytes(id))), cache);
14
+ }
15
+ /** Writes each object that is missing or fails its check. */
16
+ async write(objects) {
17
+ await ensureDirectory(join(this.directory, 'objects'));
18
+ await Promise.all([...objects].map(async ([id, text]) => {
19
+ if (await this.valid(id))
20
+ return;
21
+ const path = join(this.directory, objectPath(id));
22
+ await ensureDirectory(dirname(path));
23
+ await replaceFile(dirname(path), basename(path), text);
24
+ }));
25
+ }
26
+ async valid(id) {
27
+ try {
28
+ objectText(id, await this.bytes(id));
29
+ return true;
30
+ }
31
+ catch (error) {
32
+ if (error instanceof ObjectError)
33
+ return false;
34
+ throw error;
35
+ }
36
+ }
37
+ async bytes(id) {
38
+ try {
39
+ return await readFile(join(this.directory, objectPath(id)));
40
+ }
41
+ catch (error) {
42
+ if (hasCode(error, 'ENOENT'))
43
+ return undefined;
44
+ throw error;
45
+ }
46
+ }
47
+ async ids() {
48
+ const root = join(this.directory, 'objects');
49
+ try {
50
+ await checkDirectory(root);
51
+ }
52
+ catch (error) {
53
+ if (hasCode(error, 'ENOENT'))
54
+ return [];
55
+ throw error;
56
+ }
57
+ const ids = [];
58
+ for (const fanout of await readdir(root)) {
59
+ if (!/^[a-f0-9]{2}$/.test(fanout))
60
+ continue;
61
+ for (const name of await readdir(join(root, fanout))) {
62
+ const match = /^([a-f0-9]{32}-[a-f0-9]{8})\.json$/.exec(name);
63
+ if (match?.[1])
64
+ ids.push(match[1]);
65
+ }
66
+ }
67
+ return ids;
68
+ }
69
+ async remove(id) {
70
+ await rm(join(this.directory, objectPath(id)), { force: true });
71
+ }
72
+ }
73
+ //# sourceMappingURL=object-store.js.map
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A saved report keeps per-file rows in content-addressed objects, so an unchanged file version is stored once
3
+ * however many commits share it. The commit file keeps the rest of the report and the row order.
4
+ */
5
+ export declare const storedReportSchema = "urn:repometry:schema:report-store:1";
6
+ type Row = Readonly<Record<string, unknown>>;
7
+ /** Reads verified, parsed objects in the order of `ids`. */
8
+ export interface ObjectSource {
9
+ read(ids: readonly string[]): Promise<readonly unknown[]>;
10
+ }
11
+ export interface StoredReport {
12
+ readonly profile: string;
13
+ readonly tree: string;
14
+ readonly report: Readonly<Record<string, unknown>>;
15
+ }
16
+ export declare function objectId(text: string): string;
17
+ export declare function objectPath(id: string): string;
18
+ export declare class ObjectError extends Error {
19
+ readonly id: string;
20
+ readonly reason: 'missing' | 'corrupt';
21
+ constructor(id: string, reason: 'missing' | 'corrupt');
22
+ }
23
+ /** Reads an object and checks its content against its ID. */
24
+ export declare function objectText(id: string, bytes: Uint8Array | undefined): string;
25
+ /** Object texts read recently, up to `limit` characters; the oldest go first. Objects never change, so any reader may share it. */
26
+ export declare class ObjectCache {
27
+ private readonly limit;
28
+ private readonly texts;
29
+ private size;
30
+ constructor(limit?: number);
31
+ get(id: string): string | undefined;
32
+ set(id: string, text: string): void;
33
+ }
34
+ /**
35
+ * An object source over stored bytes, for reading reports: each report's revision check covers the content of its
36
+ * objects, so reads skip hashing them. Values are parsed per read, so reports never share mutable rows.
37
+ */
38
+ export declare function storedObjects(load: (ids: readonly string[]) => Promise<readonly (Uint8Array | undefined)[]>, cache?: ObjectCache): ObjectSource;
39
+ /** Splits a JSON-normalized report into the commit record and the objects it references. */
40
+ export declare function splitReport(report: Row): {
41
+ readonly stored: StoredReport;
42
+ readonly objects: ReadonlyMap<string, string>;
43
+ };
44
+ /** Rebuilds the exact report a commit record was split from. */
45
+ export declare function rebuildReport(stored: unknown, source: ObjectSource): Promise<Readonly<Record<string, unknown>>>;
46
+ export {};