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
@@ -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 {};
@@ -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
  }
@@ -22,7 +22,7 @@ export interface InspectionDetails {
22
22
  /** What the inspection read and how it scored it: a projection of the report's applied configuration. */
23
23
  export interface ProfileSettings {
24
24
  readonly id: string | null;
25
- readonly extensions: readonly string[];
25
+ readonly languages?: readonly ProfileLanguage[];
26
26
  readonly excludedPaths: readonly string[];
27
27
  readonly excludedDirectories: readonly string[];
28
28
  /** Every check the profile applies, each named with the plugin that runs it. */
@@ -60,6 +60,14 @@ export interface ProfileSettings {
60
60
  readonly tools: Readonly<Record<string, string>>;
61
61
  }[];
62
62
  }
63
+ export interface ProfileLanguage {
64
+ readonly plugin: string;
65
+ readonly id: string;
66
+ readonly label: string;
67
+ readonly extensions: readonly string[];
68
+ readonly globs: readonly string[];
69
+ readonly unavailableReason?: string;
70
+ }
63
71
  export interface ProfileRule {
64
72
  readonly source: string;
65
73
  readonly kind: 'check' | 'scanner';