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
@@ -0,0 +1,290 @@
1
+ import { isRecord } from '../../../core/model/plugin-data.js';
2
+ import { comparePaths, digest } from '../../../core/model/snapshot.js';
3
+ /**
4
+ * A saved report keeps per-file rows in content-addressed objects, so an unchanged file version is stored once
5
+ * however many commits share it. The commit file keeps the rest of the report and the row order.
6
+ */
7
+ export const storedReportSchema = 'urn:repometry:schema:report-store:1';
8
+ /** Applied configuration that describes one commit rather than the profile, kept in the commit file. */
9
+ const commitConfig = ['churnWindow'];
10
+ const idPattern = /^[a-f0-9]{32}-[a-f0-9]{8}$/;
11
+ export function objectId(text) {
12
+ return digest(text).slice(0, 32);
13
+ }
14
+ /**
15
+ * An object's name: the ID of its content, then a hint from the path it describes. Objects stay plain JSON, so Git
16
+ * compresses them and stores a new version as a small difference from the last. Git finds the last version by the
17
+ * end of the file name and by its folder, so every version of one path's object ends alike and shares a folder.
18
+ */
19
+ function objectName(text, path) {
20
+ return `${objectId(text)}-${digest(path).slice(0, 8)}`;
21
+ }
22
+ export function objectPath(id) {
23
+ if (!idPattern.test(id))
24
+ throw new Error(`Invalid report object ID: ${id}`);
25
+ return `objects/${id.slice(33, 35)}/${id}.json`;
26
+ }
27
+ export class ObjectError extends Error {
28
+ id;
29
+ reason;
30
+ constructor(id, reason) {
31
+ super(`Report object ${id} is ${reason}. Run repometry store check --repair, or analyze the commit again.`);
32
+ this.id = id;
33
+ this.reason = reason;
34
+ }
35
+ }
36
+ /** Reads an object and checks its content against its ID. */
37
+ export function objectText(id, bytes) {
38
+ const text = present(id, bytes);
39
+ if (objectId(text) !== id.slice(0, 32))
40
+ throw new ObjectError(id, 'corrupt');
41
+ return text;
42
+ }
43
+ function present(id, bytes) {
44
+ if (bytes === undefined)
45
+ throw new ObjectError(id, 'missing');
46
+ return Buffer.from(bytes).toString('utf8');
47
+ }
48
+ function parsed(id, text) {
49
+ try {
50
+ return JSON.parse(text);
51
+ }
52
+ catch {
53
+ throw new ObjectError(id, 'corrupt');
54
+ }
55
+ }
56
+ /** Object texts read recently, up to `limit` characters; the oldest go first. Objects never change, so any reader may share it. */
57
+ export class ObjectCache {
58
+ limit;
59
+ texts = new Map();
60
+ size = 0;
61
+ constructor(limit = 64 * 1024 * 1024) {
62
+ this.limit = limit;
63
+ }
64
+ get(id) {
65
+ return this.texts.get(id);
66
+ }
67
+ set(id, text) {
68
+ if (this.texts.has(id))
69
+ return;
70
+ this.texts.set(id, text);
71
+ this.size += text.length;
72
+ for (const [oldest, value] of this.texts) {
73
+ if (this.size <= this.limit)
74
+ break;
75
+ this.texts.delete(oldest);
76
+ this.size -= value.length;
77
+ }
78
+ }
79
+ }
80
+ /**
81
+ * An object source over stored bytes, for reading reports: each report's revision check covers the content of its
82
+ * objects, so reads skip hashing them. Values are parsed per read, so reports never share mutable rows.
83
+ */
84
+ export function storedObjects(load, cache = new ObjectCache(0)) {
85
+ return {
86
+ async read(ids) {
87
+ const cached = new Map(ids.flatMap(id => {
88
+ const text = cache.get(id);
89
+ return text === undefined ? [] : [[id, text]];
90
+ }));
91
+ const wanted = [...new Set(ids)].filter(id => !cached.has(id));
92
+ const bytes = await load(wanted);
93
+ const loaded = new Map(wanted.map((id, position) => [id, present(id, bytes[position])]));
94
+ const values = ids.map(id => parsed(id, cached.get(id) ?? loaded.get(id)));
95
+ // Only texts that parsed are kept, so a damaged object is read afresh once repaired.
96
+ for (const [id, text] of loaded)
97
+ cache.set(id, text);
98
+ return values;
99
+ },
100
+ };
101
+ }
102
+ /** Splits a JSON-normalized report into the commit record and the objects it references. */
103
+ export function splitReport(report) {
104
+ const objects = new Map();
105
+ const put = (value, path) => {
106
+ const text = JSON.stringify(value);
107
+ const id = objectName(text, path);
108
+ objects.set(id, text);
109
+ return id;
110
+ };
111
+ const lists = [];
112
+ const catalog = {};
113
+ mapParts(report, {
114
+ list: (slot, rows) => Array.isArray(rows) && lists.push([slot, rows]),
115
+ config: () => undefined, definitions: () => undefined, catalog: (key, value) => catalog[key] = value,
116
+ });
117
+ const paths = [...new Set(lists.flatMap(([, rows]) => rows.flatMap(row => typeof row.path === 'string' ? [row.path] : [])))]
118
+ .sort(comparePaths);
119
+ const index = new Map(paths.map((path, position) => [path, position]));
120
+ const nodes = paths.map(() => ({}));
121
+ const entries = new Map(lists.map(([slot, rows]) => [slot, liftRows(rows, slot, index, nodes)]));
122
+ const config = isRecord(report.appliedConfig) ? report.appliedConfig : {};
123
+ const profile = put({
124
+ appliedConfig: mapEntries(config, (key, value) => commitConfig.includes(key) ? null : value),
125
+ definitions: report.definitions,
126
+ ...(isRecord(report.pluginData) ? { catalog } : {}),
127
+ }, '');
128
+ const stored = mapParts(report, {
129
+ list: (slot, rows) => entries.get(slot) ?? rows,
130
+ config: () => Object.fromEntries(Object.entries(config).filter(([key]) => commitConfig.includes(key))),
131
+ definitions: () => null, catalog: () => null,
132
+ });
133
+ return { stored: { profile, tree: writeDirectory(directoryOf(paths, nodes), put, '/'), report: stored }, objects };
134
+ }
135
+ /** Rebuilds the exact report a commit record was split from. */
136
+ export async function rebuildReport(stored, source) {
137
+ if (!isRecord(stored) || typeof stored.profile !== 'string' || typeof stored.tree !== 'string' || !isRecord(stored.report)) {
138
+ throw new Error('Invalid stored report');
139
+ }
140
+ const [[profile], files] = await Promise.all([source.read([stored.profile]), readTree(stored.tree, source)]);
141
+ const config = isRecord(profile) ? profile.appliedConfig : undefined;
142
+ if (!isRecord(profile) || !isRecord(config))
143
+ throw new Error('Invalid stored report profile');
144
+ const catalog = isRecord(profile.catalog) ? profile.catalog : {};
145
+ return mapParts(stored.report, {
146
+ list: rowExpander(files),
147
+ config: value => ({ ...config, ...(isRecord(value) ? value : {}) }),
148
+ definitions: () => profile.definitions,
149
+ catalog: (key, value) => Object.hasOwn(catalog, key) ? catalog[key] : value,
150
+ });
151
+ }
152
+ /** The one place that knows which parts of a report are per file, per profile or per commit. */
153
+ function mapParts(report, parts) {
154
+ return mapEntries(report, (key, value) => {
155
+ if (key === 'appliedConfig')
156
+ return parts.config(value);
157
+ if (key === 'definitions')
158
+ return parts.definitions(value);
159
+ if (key === 'measurements' || key === 'findings' || key === 'ruleSkips')
160
+ return parts.list(key, value);
161
+ if (key !== 'pluginData' || !isRecord(value))
162
+ return value;
163
+ return mapEntries(value, (name, item) => name === 'products'
164
+ ? isRecord(item) ? mapEntries(item, (contract, rows) => parts.list(`products/${contract}`, rows)) : item
165
+ : name === 'inventory' ? parts.list(name, item) : parts.catalog(name, item));
166
+ });
167
+ }
168
+ /** Moves file rows into their file nodes. Each run of one file's rows becomes a [file, count] range entry. */
169
+ function liftRows(rows, slot, index, nodes) {
170
+ const entries = [];
171
+ let last;
172
+ for (const row of rows) {
173
+ const file = typeof row.path === 'string' ? index.get(row.path) : undefined;
174
+ if (file === undefined) {
175
+ entries.push(row);
176
+ last = undefined;
177
+ continue;
178
+ }
179
+ const runs = nodes[file][slot] ??= [];
180
+ if (file !== last) {
181
+ runs.push([]);
182
+ const previous = entries.at(-1);
183
+ if (Array.isArray(previous) && previous[0] + previous[1] === file)
184
+ previous[1]++;
185
+ else
186
+ entries.push([file, 1]);
187
+ last = file;
188
+ }
189
+ // Keep the key order of the row; the path comes back from the tree.
190
+ runs.at(-1).push({ ...row, path: 0 });
191
+ }
192
+ return entries;
193
+ }
194
+ function rowExpander(files) {
195
+ const paths = [...files.keys()].sort(comparePaths);
196
+ const cursors = new Map();
197
+ const run = (file, slot) => {
198
+ const key = `${slot}\n${file}`;
199
+ const position = cursors.get(key) ?? 0;
200
+ cursors.set(key, position + 1);
201
+ const path = paths[file];
202
+ const rows = files.get(path)?.[slot]?.[position];
203
+ if (!Array.isArray(rows) || !rows.every(isRecord))
204
+ throw new Error('Invalid stored report rows');
205
+ // Rows come freshly parsed for this report; the path takes the place its placeholder holds.
206
+ for (const row of rows)
207
+ row.path = path;
208
+ return rows;
209
+ };
210
+ return (slot, entries) => {
211
+ if (!Array.isArray(entries))
212
+ return entries;
213
+ return entries.flatMap(entry => {
214
+ if (!Array.isArray(entry))
215
+ return [entry];
216
+ const [first, count] = entry;
217
+ if (!Number.isSafeInteger(first) || !Number.isSafeInteger(count) || first < 0 || count < 1
218
+ || first + count > paths.length)
219
+ throw new Error('Invalid stored report rows');
220
+ return Array.from({ length: count }, (_, offset) => run(first + offset, slot)).flat();
221
+ });
222
+ };
223
+ }
224
+ function directoryOf(paths, nodes) {
225
+ const root = new Map();
226
+ paths.forEach((path, position) => {
227
+ const parts = path.split('/');
228
+ const name = parts.pop();
229
+ let directory = root;
230
+ for (const part of parts) {
231
+ let child = directory.get(`${part}/`);
232
+ if (!(child instanceof Map))
233
+ directory.set(`${part}/`, child = new Map());
234
+ directory = child;
235
+ }
236
+ directory.set(name, nodes[position]);
237
+ });
238
+ return root;
239
+ }
240
+ /** Writes a directory as sorted [name, entry] pairs. A file keeps its inventory inline and its other rows in one object. */
241
+ function writeDirectory(directory, put, path) {
242
+ return put([...directory].sort(([a], [b]) => comparePaths(a, b)).map(([name, value]) => {
243
+ if (value instanceof Map)
244
+ return [name, writeDirectory(value, put, path + name)];
245
+ const { inventory, ...rows } = value;
246
+ return [name, { ...(inventory ? { inventory } : {}), ...(Object.keys(rows).length ? { data: put(rows, path + name) } : {}) }];
247
+ }), path);
248
+ }
249
+ async function readTree(root, source) {
250
+ const files = new Map();
251
+ const data = [];
252
+ let level = [['', root]];
253
+ while (level.length) {
254
+ const directories = await source.read(level.map(([, id]) => id));
255
+ const next = [];
256
+ level.forEach(([prefix], position) => {
257
+ const entries = directories[position];
258
+ if (!Array.isArray(entries))
259
+ throw new Error('Invalid stored report tree');
260
+ for (const entry of entries) {
261
+ const [name, value] = Array.isArray(entry) ? entry : [];
262
+ if (typeof name !== 'string')
263
+ throw new Error('Invalid stored report tree');
264
+ const path = prefix + name;
265
+ if (name.endsWith('/') && typeof value === 'string')
266
+ next.push([path, value]);
267
+ else if (!name.endsWith('/') && isRecord(value)) {
268
+ files.set(path, Array.isArray(value.inventory) ? { inventory: value.inventory } : {});
269
+ if (typeof value.data === 'string')
270
+ data.push([path, value.data]);
271
+ }
272
+ else
273
+ throw new Error('Invalid stored report tree');
274
+ }
275
+ });
276
+ level = next;
277
+ }
278
+ const loaded = await source.read(data.map(([, id]) => id));
279
+ data.forEach(([path], position) => {
280
+ const rows = loaded[position];
281
+ if (!isRecord(rows))
282
+ throw new Error('Invalid stored report file');
283
+ files.set(path, { ...files.get(path), ...rows });
284
+ });
285
+ return files;
286
+ }
287
+ function mapEntries(value, map) {
288
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, map(key, item)]));
289
+ }
290
+ //# sourceMappingURL=report-tree.js.map
@@ -0,0 +1,32 @@
1
+ import type { Subject } from '../../../core/model/source.js';
2
+ import type { ObjectSource } from './report-tree.js';
3
+ export declare const storeCheckSchema = "urn:repometry:schema:store-check:1";
4
+ export interface StoreProblem {
5
+ readonly subject: Subject;
6
+ readonly problem: 'missing-objects' | 'corrupt-objects' | 'unreadable';
7
+ readonly objects?: readonly string[];
8
+ readonly message: string;
9
+ }
10
+ export interface StoreCheck {
11
+ readonly schema: typeof storeCheckSchema;
12
+ readonly reports: number;
13
+ readonly objects: number;
14
+ readonly unreferenced: number;
15
+ readonly summary: 'current' | 'stale';
16
+ readonly problems: readonly StoreProblem[];
17
+ readonly repaired?: {
18
+ readonly restored: number;
19
+ readonly removed: number;
20
+ readonly summary: boolean;
21
+ };
22
+ }
23
+ export interface StoreRepair {
24
+ /** Another copy of the objects, such as the storage branch, to restore missing or corrupt ones from. */
25
+ readonly from?: ObjectSource;
26
+ }
27
+ /**
28
+ * Verifies every saved report: its objects exist and match their IDs, and the report rebuilds to the revision
29
+ * in its header. With `repair`, restores objects from `from`, removes old unreferenced objects and refreshes
30
+ * summary.json. A report that stays broken needs `repometry analyze` again.
31
+ */
32
+ export declare function checkStore(directory: string, repair?: StoreRepair): Promise<StoreCheck>;
@@ -0,0 +1,144 @@
1
+ import { lstat, readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { repositorySummary } from '../projections/commit-summary.js';
4
+ import { readStoredReport } from '../validation/report.js';
5
+ import { hasCode } from './directory.js';
6
+ import { LocalReportStore } from './local-store.js';
7
+ import { ObjectError, objectId, objectPath, objectText } from './report-tree.js';
8
+ export const storeCheckSchema = 'urn:repometry:schema:store-check:1';
9
+ /** Objects this recent may belong to a save that has not published its report yet. */
10
+ const unreferencedGraceMs = 60 * 60 * 1000;
11
+ /**
12
+ * Verifies every saved report: its objects exist and match their IDs, and the report rebuilds to the revision
13
+ * in its header. With `repair`, restores objects from `from`, removes old unreferenced objects and refreshes
14
+ * summary.json. A report that stays broken needs `repometry analyze` again.
15
+ */
16
+ export async function checkStore(directory, repair) {
17
+ const store = new LocalReportStore(directory);
18
+ const reachable = new Set();
19
+ const problems = [];
20
+ const counts = { restored: 0, removed: 0 };
21
+ const subjects = await store.subjects();
22
+ for (const subject of subjects) {
23
+ const result = await checkReport(store, subject, repair);
24
+ for (const id of result.ids)
25
+ reachable.add(id);
26
+ if (result.problem)
27
+ problems.push(result.problem);
28
+ counts.restored += result.restored;
29
+ }
30
+ const unreferenced = (await store.objects.ids()).filter(id => !reachable.has(id));
31
+ // While a report is broken, objects under its missing directories look unreferenced: keep them.
32
+ if (repair && problems.length === 0)
33
+ counts.removed = await removeOld(store, directory, unreferenced);
34
+ const stale = await summaryStale(store, directory);
35
+ if (repair && stale)
36
+ await store.refreshSummary();
37
+ return {
38
+ schema: storeCheckSchema, reports: subjects.length, objects: reachable.size, unreferenced: unreferenced.length - counts.removed,
39
+ summary: stale && !repair ? 'stale' : 'current', problems,
40
+ ...(repair ? { repaired: { ...counts, summary: stale } } : {}),
41
+ };
42
+ }
43
+ /** Single-file reports saved before objects have no objects to check; reading them verifies their revision. */
44
+ async function checkReport(store, subject, repair) {
45
+ let text;
46
+ try {
47
+ text = await store.text(subject);
48
+ }
49
+ catch (error) {
50
+ return { ids: new Set(), restored: 0, problem: unreadable(subject, error) };
51
+ }
52
+ let restored = 0;
53
+ for (;;) {
54
+ const { ids, failed, error } = await verify(store, text, subject);
55
+ const count = failed.size && repair?.from ? await restore(store, repair.from, [...failed.keys()]) : 0;
56
+ restored += count;
57
+ if (count)
58
+ continue;
59
+ const problem = failed.size ? objectProblem(subject, failed) : error === undefined ? undefined : unreadable(subject, error);
60
+ return { ids, restored, ...(problem ? { problem } : {}) };
61
+ }
62
+ }
63
+ /** Reads a report through objects checked against their IDs, noting each object it reaches and each it cannot read. */
64
+ async function verify(store, text, subject) {
65
+ const ids = new Set();
66
+ const failed = new Map();
67
+ const reads = [];
68
+ const objects = {
69
+ async read(list) {
70
+ const pending = list.map(async (id) => {
71
+ ids.add(id);
72
+ try {
73
+ return JSON.parse(objectText(id, await store.objects.bytes(id)));
74
+ }
75
+ catch (error) {
76
+ if (!(error instanceof ObjectError))
77
+ throw error;
78
+ failed.set(id, error.reason);
79
+ return undefined;
80
+ }
81
+ });
82
+ reads.push(...pending);
83
+ const values = await Promise.all(pending);
84
+ if (failed.size)
85
+ throw new ObjectError([...failed.keys()][0], [...failed.values()][0]);
86
+ return values;
87
+ },
88
+ };
89
+ try {
90
+ await readStoredReport(text, subject, objects);
91
+ return { ids, failed };
92
+ }
93
+ catch (error) {
94
+ // Let reads already under way finish, so every damaged object they reach is reported.
95
+ await Promise.allSettled(reads);
96
+ return { ids, failed, error };
97
+ }
98
+ }
99
+ async function restore(store, from, ids) {
100
+ const copies = new Map();
101
+ for (const id of ids) {
102
+ try {
103
+ const text = JSON.stringify((await from.read([id]))[0]);
104
+ if (objectId(text) === id.slice(0, 32))
105
+ copies.set(id, text);
106
+ }
107
+ catch (error) {
108
+ if (!(error instanceof ObjectError))
109
+ throw error;
110
+ }
111
+ }
112
+ await store.objects.write(copies);
113
+ return copies.size;
114
+ }
115
+ async function removeOld(store, directory, ids) {
116
+ let removed = 0;
117
+ for (const id of ids) {
118
+ if (Date.now() - (await lstat(join(directory, objectPath(id)))).mtimeMs < unreferencedGraceMs)
119
+ continue;
120
+ await store.objects.remove(id);
121
+ removed++;
122
+ }
123
+ return removed;
124
+ }
125
+ async function summaryStale(store, directory) {
126
+ const expected = `${JSON.stringify(repositorySummary(await store.listSummaries()))}\n`;
127
+ try {
128
+ return await readFile(join(directory, 'summary.json'), 'utf8') !== expected;
129
+ }
130
+ catch (error) {
131
+ if (hasCode(error, 'ENOENT'))
132
+ return (await store.listSummaries()).length > 0;
133
+ throw error;
134
+ }
135
+ }
136
+ function objectProblem(subject, failed) {
137
+ const missing = [...failed.values()].includes('missing');
138
+ return { subject, problem: missing ? 'missing-objects' : 'corrupt-objects', objects: [...failed.keys()],
139
+ message: `Restore with repometry store check --repair --from git:repometry, or run repometry analyze ${subject.kind === 'commit' ? subject.id : '--working-tree'}.` };
140
+ }
141
+ function unreadable(subject, error) {
142
+ return { subject, problem: 'unreadable', message: error instanceof Error ? error.message : String(error) };
143
+ }
144
+ //# sourceMappingURL=store-check.js.map
@@ -1,4 +1,5 @@
1
1
  import type { Subject } from '../../../core/model/source.js';
2
+ import type { ObjectSource } from '../store/report-tree.js';
2
3
  import type { CommitSummary } from '../wire/summary-model.js';
3
4
  import type { Report } from '../../../core/model/report.js';
4
5
  import type { ReportReader as DomainReportReader, ReportWriter } from '../../../core/ports/report.js';
@@ -9,7 +10,11 @@ export interface ReportReader extends DomainReportReader {
9
10
  }
10
11
  export interface ReportStore extends ReportReader, ReportWriter {
11
12
  }
12
- export declare function readReportText(text: string, subject: Subject): Report;
13
+ /**
14
+ * Reads a saved report file: a commit file whose rows live in `objects`, or a single-file report saved before
15
+ * objects existed, which is read as it is. Both give the same report.
16
+ */
17
+ export declare function readStoredReport(text: string, subject: Subject, objects: ObjectSource): Promise<Report>;
13
18
  export declare function reportRevision(report: Report): string;
14
19
  export declare function compareReports(a: Report, b: Report): number;
15
20
  export declare function readReport(value: unknown): Report;
@@ -7,15 +7,21 @@ import { isFinding } from '../../../core/model/finding.js';
7
7
  import { canonicalMetricId } from '../../../core/model/measurement.js';
8
8
  import { lcovLines } from '../../../core/model/line-coverage.js';
9
9
  import { digest } from '../../../core/model/snapshot.js';
10
- import { compactJsonSchema, unpackJson } from '../wire/compact-json.js';
10
+ import { unpackJson } from '../wire/compact-json.js';
11
+ import { rebuildReport, storedReportSchema } from '../store/report-tree.js';
11
12
  import { reportSchema } from '../../../core/model/report.js';
12
13
  export { reportSchema, validSubjectId } from '../../../core/model/report.js';
13
- export function readReportText(text, subject) {
14
+ /**
15
+ * Reads a saved report file: a commit file whose rows live in `objects`, or a single-file report saved before
16
+ * objects existed, which is read as it is. Both give the same report.
17
+ */
18
+ export async function readStoredReport(text, subject, objects) {
14
19
  const envelope = JSON.parse(text);
15
- const report = readReport(unpackJson(envelope));
20
+ const value = isRecord(envelope) && envelope.schema === storedReportSchema ? await rebuildReport(envelope, objects) : unpackJson(envelope);
21
+ const report = readReport(value);
16
22
  if (report.subject.kind !== subject.kind || report.subject.id !== subject.id)
17
23
  throw new Error(`Report subject mismatch: ${subject.id}`);
18
- if (isRecord(envelope) && envelope.schema === compactJsonSchema && isRecord(envelope.summary)
24
+ if (isRecord(envelope) && isRecord(envelope.summary)
19
25
  && envelope.summary.revision !== undefined && envelope.summary.revision !== reportRevision(report)) {
20
26
  throw new Error(`Report revision mismatch: ${subject.id}`);
21
27
  }
@@ -66,6 +66,7 @@ export interface ProfileLanguage {
66
66
  readonly label: string;
67
67
  readonly extensions: readonly string[];
68
68
  readonly globs: readonly string[];
69
+ readonly unavailableReason?: string;
69
70
  }
70
71
  export interface ProfileRule {
71
72
  readonly source: string;