@mark1russell7/canon-ontology 0.0.0-bootstrap.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +38 -1
- package/build/index.d.mts +655 -0
- package/build/index.mjs +2131 -0
- package/build/index.mjs.map +1 -0
- package/build/targets-DkEkvgll.d.mts +194 -0
- package/build/targets-DsUgzuOM.mjs +877 -0
- package/build/targets-DsUgzuOM.mjs.map +1 -0
- package/build/targets.d.mts +2 -0
- package/build/targets.mjs +1 -0
- package/package.json +69 -5
package/build/index.mjs
ADDED
|
@@ -0,0 +1,2131 @@
|
|
|
1
|
+
import { arrayOf, booleanOf, isRecord, numberOf, readArray, readText, recordOf, textOf, timeOf } from "@mark1russell7/optional/read";
|
|
2
|
+
import { A as kindOfId, C as kindOf, D as ONTOLOGY_FOLDER, E as GRAMMAR_FILE, F as repositoryId, M as npmPackageId, N as npmPurl, O as RECORD_SCHEMA_FILE, P as pathOfId, S as isLive, T as relationOf, _ as readScope, a as SIZES, b as edgesOf, c as targetsOf, d as hasFullScope, f as resultClaimsOf, g as inScope, h as canonicalScope, i as PLACES_SHOWN, j as makeId, k as idPart, l as CLAIM_STATUSES, m as SCOPE_MODULUS_LIMIT, n as NECESSARY_GATES, o as compareTargets, p as scopeOf, r as ONTOLOGY_REPOSITORY, s as targetId, u as claimFails, v as sameScope, w as lineageOf, x as isKindIn, y as scopeText } from "./targets-DsUgzuOM.mjs";
|
|
3
|
+
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
4
|
+
import formats from "ajv-formats";
|
|
5
|
+
import { countOf, listOf } from "@mark1russell7/text/english";
|
|
6
|
+
import { compareCodeUnits } from "@mark1russell7/text/order";
|
|
7
|
+
import { dirname, join, relative } from "node:path";
|
|
8
|
+
import { HOMES, OWNERS, reposOf } from "@mark1russell7/conventions";
|
|
9
|
+
import { findFiles, findUp, toPosix } from "@mark1russell7/files";
|
|
10
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { errorMessage } from "@mark1russell7/text";
|
|
13
|
+
import { redactSecrets } from "@mark1russell7/text/redact";
|
|
14
|
+
import { fetchTransport, send } from "polite-crawler/api";
|
|
15
|
+
import { HostScheduler, realClock } from "polite-crawler/politeness";
|
|
16
|
+
import { parse } from "yaml";
|
|
17
|
+
// src/atlas.ts
|
|
18
|
+
/** The URL of the data of the duplication atlas. */
|
|
19
|
+
const ATLAS_URL = "https://metrograph-labs.github.io/codeatlas/data/atlas.json";
|
|
20
|
+
/** The id of the record of kind source for the duplication atlas. */
|
|
21
|
+
const ATLAS_SOURCE_ID = "source.codeatlas";
|
|
22
|
+
/** The schema of the atlas that this reader knows. The reader refuses an atlas with a different schema. */
|
|
23
|
+
const ATLAS_SCHEMA = "codeatlas/1";
|
|
24
|
+
/** The largest text of an atlas that the reader accepts, in characters. */
|
|
25
|
+
const ATLAS_LIMIT = 33554432;
|
|
26
|
+
const COMMIT = /^[0-9a-f]{40}$/;
|
|
27
|
+
/**
|
|
28
|
+
* This function reads one function. It drops a function of a test file. It also drops a function with no name, unless
|
|
29
|
+
* `anonymous` is true.
|
|
30
|
+
*/
|
|
31
|
+
function copyOf(value, anonymous = false) {
|
|
32
|
+
const repo = textOf(value, "repo");
|
|
33
|
+
const file = textOf(value, "file");
|
|
34
|
+
const line = numberOf(value, "line");
|
|
35
|
+
const name = textOf(value, "name");
|
|
36
|
+
if (repo === void 0 || file === void 0 || line === void 0 || name === void 0) return void 0;
|
|
37
|
+
if (booleanOf(value, "test") !== false || !Number.isInteger(line) || line < 1 || name === "") return void 0;
|
|
38
|
+
if (name.startsWith("<") && (!anonymous || name !== "<anonymous>")) return void 0;
|
|
39
|
+
return {
|
|
40
|
+
repo,
|
|
41
|
+
file,
|
|
42
|
+
line,
|
|
43
|
+
name
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** This function reads one class of cloned code. It drops a class with a bad count of nodes. */
|
|
47
|
+
function classOf(value) {
|
|
48
|
+
const nodes = numberOf(value, "nodes");
|
|
49
|
+
if (nodes === void 0 || !Number.isInteger(nodes) || nodes < 1) return void 0;
|
|
50
|
+
return {
|
|
51
|
+
nodes,
|
|
52
|
+
areas: arrayOf(value, "homes", readText) ?? [],
|
|
53
|
+
members: arrayOf(value, "members", (member) => copyOf(member, true)) ?? []
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* This function reads the answer of the fetch of the atlas. It gives an error for a failed fetch, a text of more than
|
|
58
|
+
* `limit` characters and a text that is not JSON. A schema that is not `ATLAS_SCHEMA` also gives an error. It drops each
|
|
59
|
+
* row with a bad field. An atlas with no list of classes has no classes.
|
|
60
|
+
*/
|
|
61
|
+
function readAtlas(answer, limit = ATLAS_LIMIT) {
|
|
62
|
+
if (answer === void 0) return { error: "The fetch gave no answer for the atlas." };
|
|
63
|
+
if ("error" in answer) return { error: `The fetch of the atlas gave the error ${answer.error}.` };
|
|
64
|
+
if (answer.text.length > limit) return { error: `The atlas has more than ${String(limit)} characters.` };
|
|
65
|
+
let data;
|
|
66
|
+
try {
|
|
67
|
+
data = JSON.parse(answer.text);
|
|
68
|
+
} catch {
|
|
69
|
+
return { error: "The atlas is not JSON." };
|
|
70
|
+
}
|
|
71
|
+
const schema = textOf(data, "schema");
|
|
72
|
+
if (schema !== "codeatlas/1") return { error: `The atlas has the schema ${schema ?? "(none)"}, not ${ATLAS_SCHEMA}.` };
|
|
73
|
+
const repositories = arrayOf(data, "repos", (row) => {
|
|
74
|
+
const repo = textOf(row, "repo");
|
|
75
|
+
const owner = textOf(row, "owner");
|
|
76
|
+
const commit = textOf(row, "commit");
|
|
77
|
+
return repo === void 0 || owner === void 0 || commit === void 0 || !COMMIT.test(commit) ? void 0 : {
|
|
78
|
+
repo,
|
|
79
|
+
owner,
|
|
80
|
+
commit
|
|
81
|
+
};
|
|
82
|
+
});
|
|
83
|
+
const rows = arrayOf(data, "homed", (row) => {
|
|
84
|
+
const area = textOf(row, "area");
|
|
85
|
+
return area === void 0 ? void 0 : {
|
|
86
|
+
area,
|
|
87
|
+
copies: arrayOf(row, "copies", copyOf) ?? []
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
if (repositories === void 0 || rows === void 0) return { error: "The atlas has no list of repositories or no list of homed rows." };
|
|
91
|
+
return { atlas: {
|
|
92
|
+
repositories,
|
|
93
|
+
rows,
|
|
94
|
+
classes: arrayOf(data, "classes", classOf) ?? []
|
|
95
|
+
} };
|
|
96
|
+
}
|
|
97
|
+
/** This function gives the repositories of each area that hold its own code: the home and each repository of a package of the area. */
|
|
98
|
+
function ownRepositories(records) {
|
|
99
|
+
const own = /* @__PURE__ */ new Map();
|
|
100
|
+
const add = (area, repository) => {
|
|
101
|
+
const set = own.get(area) ?? /* @__PURE__ */ new Set();
|
|
102
|
+
set.add(repository);
|
|
103
|
+
own.set(area, set);
|
|
104
|
+
};
|
|
105
|
+
for (const record of records) {
|
|
106
|
+
const edges = record.edges ?? [];
|
|
107
|
+
if (record.kind === "repository") {
|
|
108
|
+
for (const edge of edges) if (edge.type === "home-of") add(edge.to, record.id);
|
|
109
|
+
}
|
|
110
|
+
const partOf = edges.find((edge) => edge.type === "part-of")?.to;
|
|
111
|
+
if (record.kind === "package" && partOf !== void 0) {
|
|
112
|
+
for (const edge of edges) if (edge.type === "covers") add(edge.to, partOf);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return own;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* This function gives a function that finds the repository of a name of the atlas. It finds the repository under the
|
|
119
|
+
* owner that the atlas names, or under the one owner that has a repository of that name. A fork and an archived
|
|
120
|
+
* repository are not found.
|
|
121
|
+
*/
|
|
122
|
+
function repositoryFinder(atlas, repositories) {
|
|
123
|
+
const live = repositories.filter((repository) => repository.fork !== true && repository.archived !== true);
|
|
124
|
+
const byFullName = new Map(live.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository]));
|
|
125
|
+
const byName = /* @__PURE__ */ new Map();
|
|
126
|
+
for (const repository of live) byName.set(repository.name.toLowerCase(), [...byName.get(repository.name.toLowerCase()) ?? [], repository]);
|
|
127
|
+
const read = new Map(atlas.repositories.map((row) => [row.repo.toLowerCase(), row]));
|
|
128
|
+
return (repo) => {
|
|
129
|
+
const scan = read.get(repo.toLowerCase());
|
|
130
|
+
const named = byName.get(repo.toLowerCase()) ?? [];
|
|
131
|
+
const found = (scan === void 0 ? void 0 : byFullName.get(`${scan.owner}/${repo}`.toLowerCase())) ?? (named.length === 1 ? named[0] : void 0);
|
|
132
|
+
if (scan !== void 0 && found !== void 0) return {
|
|
133
|
+
repository: found,
|
|
134
|
+
commit: scan.commit
|
|
135
|
+
};
|
|
136
|
+
return { why: scan === void 0 ? "the atlas has no commit for it" : named.length > 1 ? "two owners have a repository of that name" : "GitHub lists no public repository of that name that is not a fork and not archived" };
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* This function makes a record of kind candidate for each pair of a repository and an area that the atlas finds. It
|
|
141
|
+
* reads nothing itself.
|
|
142
|
+
*
|
|
143
|
+
* - The import finds each repository of the atlas under its owner, or under the one owner that has a repository of that
|
|
144
|
+
* name. It leaves out a name of two owners, a fork, an archived repository and a repository that is not public.
|
|
145
|
+
* - It leaves out an area that the map of homes does not have, and the repositories that hold the own code of the area.
|
|
146
|
+
* - Each candidate has the commit that the atlas read, and each place once, in the order of the file and the line.
|
|
147
|
+
*/
|
|
148
|
+
function recordsFromAtlas(atlas, repositories, mapRecords) {
|
|
149
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
150
|
+
const find = repositoryFinder(atlas, repositories);
|
|
151
|
+
const areas = new Set(mapRecords.filter((record) => record.kind === "area").map((record) => record.id));
|
|
152
|
+
const own = ownRepositories(mapRecords);
|
|
153
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
154
|
+
for (const row of atlas.rows) {
|
|
155
|
+
const area = makeId("area", row.area);
|
|
156
|
+
if (!areas.has(area)) {
|
|
157
|
+
skipped.add(`The atlas names the area ${row.area}, which the map of homes does not have.`);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
for (const copy of row.copies) {
|
|
161
|
+
const found = find(copy.repo);
|
|
162
|
+
if ("why" in found) {
|
|
163
|
+
skipped.add(`The atlas names the repository ${copy.repo}, but ${found.why}.`);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const repository = repositoryId(found.repository.owner, found.repository.name);
|
|
167
|
+
if (own.get(area)?.has(repository) === true) continue;
|
|
168
|
+
const key = `${repository} ${area}`;
|
|
169
|
+
const id = makeId("candidate", found.repository.owner, found.repository.name, row.area);
|
|
170
|
+
const pair = pairs.get(key) ?? {
|
|
171
|
+
id,
|
|
172
|
+
repository,
|
|
173
|
+
area,
|
|
174
|
+
commit: found.commit,
|
|
175
|
+
places: /* @__PURE__ */ new Map()
|
|
176
|
+
};
|
|
177
|
+
pair.places.set(`${copy.file}:${String(copy.line)}:${copy.name}`, copy);
|
|
178
|
+
pairs.set(key, pair);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const records = [{
|
|
182
|
+
id: ATLAS_SOURCE_ID,
|
|
183
|
+
kind: "source",
|
|
184
|
+
attrs: {
|
|
185
|
+
title: "The duplication atlas of codeatlas",
|
|
186
|
+
url: "https://metrograph-labs.github.io/codeatlas/",
|
|
187
|
+
version: ATLAS_SCHEMA,
|
|
188
|
+
license: "MIT"
|
|
189
|
+
}
|
|
190
|
+
}];
|
|
191
|
+
for (const pair of pairs.values()) {
|
|
192
|
+
const places = [...pair.places.values()].sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)).map(({ file, line, name }) => ({
|
|
193
|
+
file,
|
|
194
|
+
line,
|
|
195
|
+
name
|
|
196
|
+
}));
|
|
197
|
+
records.push({
|
|
198
|
+
id: pair.id,
|
|
199
|
+
kind: "candidate",
|
|
200
|
+
attrs: {
|
|
201
|
+
commit: pair.commit,
|
|
202
|
+
places
|
|
203
|
+
},
|
|
204
|
+
envelope: { source_ids: [ATLAS_SOURCE_ID] },
|
|
205
|
+
edges: [{
|
|
206
|
+
type: "about",
|
|
207
|
+
to: pair.area
|
|
208
|
+
}, {
|
|
209
|
+
type: "about",
|
|
210
|
+
to: pair.repository
|
|
211
|
+
}]
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
records.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
215
|
+
return {
|
|
216
|
+
records,
|
|
217
|
+
skipped: [...skipped].sort()
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
// src/board.ts
|
|
221
|
+
/** The label of each issue of the board. */
|
|
222
|
+
const TARGET_LABEL = "target";
|
|
223
|
+
/** The time of a claim with no pull request, in hours. */
|
|
224
|
+
const CLAIM_HOURS = 48;
|
|
225
|
+
/** The most open issues of the board. */
|
|
226
|
+
const BOARD_LIMIT = 20;
|
|
227
|
+
/** The start of the hidden line of an issue body that has the id of its target. */
|
|
228
|
+
const MARK = "<!-- canon-target: ";
|
|
229
|
+
/** The end of the hidden line. */
|
|
230
|
+
const MARK_END = " -->";
|
|
231
|
+
/** This function gives the id of the target of an issue body, or undefined when the body has no hidden line. */
|
|
232
|
+
function targetOfIssue(body) {
|
|
233
|
+
const start = body.indexOf(MARK);
|
|
234
|
+
if (start < 0) return void 0;
|
|
235
|
+
const end = body.indexOf(MARK_END, start + 19);
|
|
236
|
+
const id = end < 0 ? "" : body.slice(start + 19, end).trim();
|
|
237
|
+
return id === "" || /\s/.test(id) ? void 0 : id;
|
|
238
|
+
}
|
|
239
|
+
/** This function gives the time of the end of a claim, as an ISO 8601 text to the minute. */
|
|
240
|
+
function claimEnd(claimedAt) {
|
|
241
|
+
return `${new Date(claimedAt + 1728e5).toISOString().slice(0, 16)}Z`;
|
|
242
|
+
}
|
|
243
|
+
/** This function tells if a claim is older than `CLAIM_HOURS`. A claim with no known start is live. */
|
|
244
|
+
function isExpired(issue, now) {
|
|
245
|
+
return issue.assignees.length > 0 && issue.claimedAt !== void 0 && now - issue.claimedAt >= 1728e5;
|
|
246
|
+
}
|
|
247
|
+
/** This function gives the title, the body and the labels of the issue of a target. */
|
|
248
|
+
function issueText(target, repository = ONTOLOGY_REPOSITORY) {
|
|
249
|
+
const { attrs } = target;
|
|
250
|
+
const path = pathOfId(target.id);
|
|
251
|
+
const body = [
|
|
252
|
+
`${MARK}${target.id}${MARK_END}`,
|
|
253
|
+
`**Target:** \`${target.id}\``,
|
|
254
|
+
"",
|
|
255
|
+
"| Gap | Home | Size | Area |",
|
|
256
|
+
"| --- | --- | --- | --- |",
|
|
257
|
+
`| \`${attrs.gap}\` | [${attrs.home}](https://github.com/${attrs.home}) | ${attrs.size} | ${attrs.area === void 0 ? "" : `\`${attrs.area}\``} |`,
|
|
258
|
+
"",
|
|
259
|
+
"## Acceptance",
|
|
260
|
+
"",
|
|
261
|
+
attrs.acceptance.text,
|
|
262
|
+
"",
|
|
263
|
+
...attrs.acceptance.checks.map((check) => `- [ ] ${check}`),
|
|
264
|
+
"",
|
|
265
|
+
"## Why",
|
|
266
|
+
"",
|
|
267
|
+
attrs.why,
|
|
268
|
+
"",
|
|
269
|
+
"## Claim and close",
|
|
270
|
+
"",
|
|
271
|
+
`1. Write the comment \`/claim\` on this issue. A claim stops after ${String(48)} hours with no open pull request.`,
|
|
272
|
+
`2. Do the work. [\`AGENTS.md\`](https://github.com/${repository}/blob/main/AGENTS.md) tells how.`,
|
|
273
|
+
`3. In the pull request, write the line \`Target: ${target.id}\`.`,
|
|
274
|
+
"",
|
|
275
|
+
`The record of the target is [\`${path}\`](https://github.com/${repository}/blob/main/${path}). Write \`/unclaim\` to stop your claim.`,
|
|
276
|
+
""
|
|
277
|
+
].join("\n");
|
|
278
|
+
return {
|
|
279
|
+
title: attrs.title,
|
|
280
|
+
body,
|
|
281
|
+
labels: [TARGET_LABEL, `gap:${attrs.gap}`]
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
/** This function tells if an issue has the text of a target: the same title, body and labels. */
|
|
285
|
+
function sameText(issue, text) {
|
|
286
|
+
const labels = [...issue.labels].sort();
|
|
287
|
+
const wanted = [...text.labels].sort();
|
|
288
|
+
return issue.title === text.title && issue.body === text.body && labels.length === wanted.length && labels.every((label, index) => label === wanted[index]);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* This function gives the steps that make the board agree with the target query.
|
|
292
|
+
*
|
|
293
|
+
* - The board keeps the open issue of each claimable target. It adds other claimable targets, up to the limit. An issue
|
|
294
|
+
* does not close because new targets come before it.
|
|
295
|
+
* - Each added target is the first claimable target of the gap with the fewest targets on the board. So one gap with
|
|
296
|
+
* many targets does not fill the board.
|
|
297
|
+
* - An issue whose target is not claimable closes: `completed` when the target is gone, else `not_planned`.
|
|
298
|
+
* - A claim older than `CLAIM_HOURS` stops when no open pull request names its target.
|
|
299
|
+
* - An issue with no hidden line is not an issue of the board. Of two issues of one target, the board uses the first.
|
|
300
|
+
*/
|
|
301
|
+
function planBoard(input) {
|
|
302
|
+
const limit = input.limit ?? 20;
|
|
303
|
+
const known = new Set(input.targets.map((target) => target.id));
|
|
304
|
+
const claimable = input.targets.filter((target) => target.attrs.claimable);
|
|
305
|
+
const byTarget = /* @__PURE__ */ new Map();
|
|
306
|
+
for (const issue of [...input.issues].sort((a, b) => a.number - b.number)) {
|
|
307
|
+
const id = targetOfIssue(issue.body);
|
|
308
|
+
if (id !== void 0 && !byTarget.has(id)) byTarget.set(id, issue);
|
|
309
|
+
}
|
|
310
|
+
const board = new Set(claimable.filter((target) => byTarget.get(target.id)?.state === "open").map((target) => target.id));
|
|
311
|
+
const gaps = /* @__PURE__ */ new Map();
|
|
312
|
+
for (const target of claimable) if (board.has(target.id)) gaps.set(target.attrs.gap, (gaps.get(target.attrs.gap) ?? 0) + 1);
|
|
313
|
+
const waiting = claimable.filter((target) => !board.has(target.id));
|
|
314
|
+
while (board.size < limit && waiting.length > 0) {
|
|
315
|
+
let best = 0;
|
|
316
|
+
for (let index = 1; index < waiting.length; index += 1) if ((gaps.get(waiting[index]?.attrs.gap ?? "") ?? 0) < (gaps.get(waiting[best]?.attrs.gap ?? "") ?? 0)) best = index;
|
|
317
|
+
const [next] = waiting.splice(best, 1);
|
|
318
|
+
if (next === void 0) break;
|
|
319
|
+
board.add(next.id);
|
|
320
|
+
gaps.set(next.attrs.gap, (gaps.get(next.attrs.gap) ?? 0) + 1);
|
|
321
|
+
}
|
|
322
|
+
const actions = [];
|
|
323
|
+
for (const target of claimable.filter((candidate) => board.has(candidate.id))) {
|
|
324
|
+
const text = issueText(target);
|
|
325
|
+
const issue = byTarget.get(target.id);
|
|
326
|
+
if (issue === void 0) {
|
|
327
|
+
actions.push({
|
|
328
|
+
kind: "create",
|
|
329
|
+
target: target.id,
|
|
330
|
+
text
|
|
331
|
+
});
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (issue.state === "closed" || !sameText(issue, text)) actions.push({
|
|
335
|
+
kind: "update",
|
|
336
|
+
number: issue.number,
|
|
337
|
+
target: target.id,
|
|
338
|
+
text,
|
|
339
|
+
reopen: issue.state === "closed"
|
|
340
|
+
});
|
|
341
|
+
if (issue.state === "open" && isExpired(issue, input.now) && !input.pulls.has(target.id)) actions.push({
|
|
342
|
+
kind: "release",
|
|
343
|
+
number: issue.number,
|
|
344
|
+
target: target.id,
|
|
345
|
+
users: issue.assignees
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
for (const [target, issue] of byTarget) if (issue.state === "open" && !board.has(target)) actions.push({
|
|
349
|
+
kind: "close",
|
|
350
|
+
number: issue.number,
|
|
351
|
+
target,
|
|
352
|
+
reason: known.has(target) ? "not_planned" : "completed"
|
|
353
|
+
});
|
|
354
|
+
return actions;
|
|
355
|
+
}
|
|
356
|
+
/** The comment of a step of the board, or undefined for a step with no comment. */
|
|
357
|
+
function actionComment(action) {
|
|
358
|
+
if (action.kind === "release") return `The claim of ${action.users.map((user) => `\`${user}\``).join(", ")} stopped: ${String(48)} hours passed with no open pull request. Another contributor can claim the target now.`;
|
|
359
|
+
if (action.kind === "close") return action.reason === "completed" ? "The target query does not give this target now, so the gap is closed." : "The target query does not give this target as claimable now. The issue opens again when the target is claimable.";
|
|
360
|
+
}
|
|
361
|
+
/** This function applies the steps of the board through the API, in their order. It gives the number of each new issue. */
|
|
362
|
+
async function applyBoard(api, actions) {
|
|
363
|
+
const labels = new Set(actions.flatMap((action) => action.kind === "create" || action.kind === "update" ? action.text.labels : []));
|
|
364
|
+
if (labels.size > 0) await api.ensureLabels([...labels].sort());
|
|
365
|
+
const created = [];
|
|
366
|
+
for (const action of actions) {
|
|
367
|
+
if (action.kind === "create") {
|
|
368
|
+
created.push(await api.create(action.text));
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (action.kind === "update") {
|
|
372
|
+
const { title, body, labels: issueLabels } = action.text;
|
|
373
|
+
await api.update(action.number, {
|
|
374
|
+
title,
|
|
375
|
+
body,
|
|
376
|
+
labels: issueLabels,
|
|
377
|
+
...action.reopen ? {
|
|
378
|
+
state: "open",
|
|
379
|
+
stateReason: "reopened"
|
|
380
|
+
} : {}
|
|
381
|
+
});
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (action.kind === "release") await api.update(action.number, { assignees: [] });
|
|
385
|
+
const comment = actionComment(action);
|
|
386
|
+
if (comment !== void 0) await api.comment(action.number, comment);
|
|
387
|
+
if (action.kind === "close") await api.update(action.number, {
|
|
388
|
+
state: "closed",
|
|
389
|
+
stateReason: action.reason
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
return created;
|
|
393
|
+
}
|
|
394
|
+
/** This function gives the command of a comment: its first word is `/claim` or `/unclaim`. */
|
|
395
|
+
function claimCommandOf(comment) {
|
|
396
|
+
const first = comment.trim().split(/\s/, 1)[0];
|
|
397
|
+
return first === "/claim" ? "claim" : first === "/unclaim" ? "unclaim" : void 0;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* This function decides a claim comment. A contributor claims one target at a time, and a claim stops after
|
|
401
|
+
* `CLAIM_HOURS` with no pull request. A claim that stopped does not block a new claim, also before the board removes it.
|
|
402
|
+
*/
|
|
403
|
+
function decideClaim(input) {
|
|
404
|
+
const { command, user, issue, target, now } = input;
|
|
405
|
+
const who = `\`${user}\``;
|
|
406
|
+
if (issue.state !== "open") return {
|
|
407
|
+
kind: "refuse",
|
|
408
|
+
comment: "This issue is closed, so its target has no claim."
|
|
409
|
+
};
|
|
410
|
+
if (target === void 0 || !target.attrs.claimable) return {
|
|
411
|
+
kind: "refuse",
|
|
412
|
+
comment: "The target of this issue is not claimable now. `AGENTS.md` tells which targets are claimable."
|
|
413
|
+
};
|
|
414
|
+
const has = issue.assignees.includes(user);
|
|
415
|
+
if (command === "unclaim") return has ? {
|
|
416
|
+
kind: "set",
|
|
417
|
+
assignees: issue.assignees.filter((login) => login !== user),
|
|
418
|
+
comment: `${who} stopped the claim. Another contributor can claim the target now.`
|
|
419
|
+
} : {
|
|
420
|
+
kind: "refuse",
|
|
421
|
+
comment: `${who} has no claim on this target.`
|
|
422
|
+
};
|
|
423
|
+
const until = issue.claimedAt === void 0 ? "the end of the claim" : claimEnd(issue.claimedAt);
|
|
424
|
+
if (has) return {
|
|
425
|
+
kind: "refuse",
|
|
426
|
+
comment: `${who} has the claim already, until ${until}.`
|
|
427
|
+
};
|
|
428
|
+
if (issue.assignees.length > 0 && !isExpired(issue, now)) return {
|
|
429
|
+
kind: "refuse",
|
|
430
|
+
comment: `${issue.assignees.map((login) => `\`${login}\``).join(", ")} has the claim until ${until}. Claim another target, or claim this target after that time.`
|
|
431
|
+
};
|
|
432
|
+
const other = input.issues.find((candidate) => candidate.number !== issue.number && candidate.state === "open" && candidate.assignees.includes(user) && !isExpired(candidate, now));
|
|
433
|
+
if (other !== void 0) return {
|
|
434
|
+
kind: "refuse",
|
|
435
|
+
comment: `${who} has a claim on #${String(other.number)} already. Claim one target at a time. Write \`/unclaim\` on #${String(other.number)} to stop that claim.`
|
|
436
|
+
};
|
|
437
|
+
return {
|
|
438
|
+
kind: "set",
|
|
439
|
+
assignees: [user],
|
|
440
|
+
comment: `${who} claims this target until ${claimEnd(now)}. Open the pull request before that time, with the line \`Target: ${target.id}\`.`
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
// src/check.ts
|
|
444
|
+
/** This function makes a validator of JSON Schema 2020-12 with the formats `uri` and `date-time`. */
|
|
445
|
+
function makeAjv() {
|
|
446
|
+
const ajv = new Ajv2020({
|
|
447
|
+
allErrors: true,
|
|
448
|
+
strict: true,
|
|
449
|
+
strictTypes: false,
|
|
450
|
+
logger: false
|
|
451
|
+
});
|
|
452
|
+
formats["default"](ajv);
|
|
453
|
+
return ajv;
|
|
454
|
+
}
|
|
455
|
+
/** This function gives the text of each error of a validation, with the name `name` for the value. */
|
|
456
|
+
function errorTexts(name, errors) {
|
|
457
|
+
return (errors ?? []).map((error) => {
|
|
458
|
+
const extra = error.keyword === "additionalProperties" ? ` (${String(error.params["additionalProperty"])})` : "";
|
|
459
|
+
const allowed = error.keyword === "enum" ? `: ${JSON.stringify(error.params["allowedValues"])}` : "";
|
|
460
|
+
return `${name}${error.instancePath} ${error.message ?? error.keyword}${extra}${allowed}`;
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/** This function compiles a schema of the grammar with the shared `$defs`. It gives a problem when the schema is not valid. */
|
|
464
|
+
function compile(ajv, grammar, schema, what, problems) {
|
|
465
|
+
try {
|
|
466
|
+
return ajv.compile({
|
|
467
|
+
$defs: grammar.$defs,
|
|
468
|
+
...schema
|
|
469
|
+
});
|
|
470
|
+
} catch (error) {
|
|
471
|
+
problems.push({
|
|
472
|
+
path: GRAMMAR_FILE,
|
|
473
|
+
message: `${what}: ${error instanceof Error ? error.message : String(error)}`
|
|
474
|
+
});
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/** This function checks the grammar itself, and compiles its validators. */
|
|
479
|
+
function checkGrammar(ontology, problems) {
|
|
480
|
+
const { grammar } = ontology;
|
|
481
|
+
const ajv = makeAjv();
|
|
482
|
+
const name = new RegExp(grammar.namePattern);
|
|
483
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
484
|
+
const qualifiers = /* @__PURE__ */ new Map();
|
|
485
|
+
const fail = (message) => {
|
|
486
|
+
problems.push({
|
|
487
|
+
path: GRAMMAR_FILE,
|
|
488
|
+
message
|
|
489
|
+
});
|
|
490
|
+
};
|
|
491
|
+
const seen = /* @__PURE__ */ new Set();
|
|
492
|
+
for (const kind of grammar.kinds) {
|
|
493
|
+
if (seen.has(kind.name)) fail(`The kind ${kind.name} comes more than one time.`);
|
|
494
|
+
seen.add(kind.name);
|
|
495
|
+
if (!name.test(kind.name)) fail(`The kind name ${kind.name} does not agree with the name pattern.`);
|
|
496
|
+
if (kind.parent !== null && kindOf(grammar, kind.parent) === void 0) fail(`The parent ${kind.parent} of the kind ${kind.name} is not a kind.`);
|
|
497
|
+
if (kind.parent !== null && lineageOf(grammar, kind.name).length <= lineageOf(grammar, kind.parent).length) fail(`The parents of the kind ${kind.name} make a loop.`);
|
|
498
|
+
const validate = compile(ajv, grammar, kind.attributes, `the attributes of the kind ${kind.name}`, problems);
|
|
499
|
+
if (validate !== void 0) kinds.set(kind.name, validate);
|
|
500
|
+
}
|
|
501
|
+
for (const relation of grammar.relations) {
|
|
502
|
+
if (seen.has(relation.name)) fail(`The name ${relation.name} is a kind and a relation kind, or two relation kinds.`);
|
|
503
|
+
seen.add(relation.name);
|
|
504
|
+
if (!name.test(relation.name)) fail(`The relation name ${relation.name} does not agree with the name pattern.`);
|
|
505
|
+
for (const end of [...relation.from, ...relation.to]) if (kindOf(grammar, end) === void 0) fail(`The relation ${relation.name} names ${end}, which is not a kind.`);
|
|
506
|
+
if (relation.parent !== void 0 && relationOf(grammar, relation.parent) === void 0) fail(`The parent ${relation.parent} of the relation ${relation.name} is not a relation kind.`);
|
|
507
|
+
const fields = Object.keys(relation.qualifiers?.["properties"] ?? {});
|
|
508
|
+
for (const part of relation.key ?? []) if (part !== "from" && part !== "to" && !fields.includes(part)) fail(`The key of the relation ${relation.name} names ${part}, which is not an end or a qualifier.`);
|
|
509
|
+
if (relation.qualifiers !== void 0) {
|
|
510
|
+
const validate = compile(ajv, grammar, relation.qualifiers, `the qualifiers of the relation ${relation.name}`, problems);
|
|
511
|
+
if (validate !== void 0) qualifiers.set(relation.name, validate);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
record: ajv.compile(ontology.recordSchema),
|
|
516
|
+
kinds,
|
|
517
|
+
qualifiers
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
/** This function checks that each id of an envelope names a record, and that each source id names a record of kind source. */
|
|
521
|
+
function checkEnvelope(envelope, what, path, kinds, grammar, problems) {
|
|
522
|
+
if (envelope === void 0) return;
|
|
523
|
+
for (const source of envelope.source_ids ?? []) {
|
|
524
|
+
const kind = kinds.get(source);
|
|
525
|
+
if (kind === void 0) problems.push({
|
|
526
|
+
path,
|
|
527
|
+
message: `${what}: the source ${source} is not a record.`
|
|
528
|
+
});
|
|
529
|
+
else if (!isKindIn(grammar, kind, ["source"])) problems.push({
|
|
530
|
+
path,
|
|
531
|
+
message: `${what}: the source ${source} is a ${kind}, not a source.`
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
for (const field of ["superseded_by", "retired_from"]) {
|
|
535
|
+
const id = envelope[field];
|
|
536
|
+
if (id !== void 0 && !kinds.has(id)) problems.push({
|
|
537
|
+
path,
|
|
538
|
+
message: `${what}: ${field} names ${id}, which is not a record.`
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
/** This function gives the key of a relation: the values of the parts of the key of its kind. The default key is the two ends. */
|
|
543
|
+
/**
|
|
544
|
+
* This function examines the scopes (roadmap C16). Each scope is valid and not empty. A live result about a problem has
|
|
545
|
+
* a scope, and the problem has a scope of the same variable. So the rule of the results can compare the two scopes.
|
|
546
|
+
*/
|
|
547
|
+
function checkScopes(ontology, problems) {
|
|
548
|
+
const scopes = /* @__PURE__ */ new Map();
|
|
549
|
+
const records = new Map(ontology.records.map((entry) => [entry.record.id, entry]));
|
|
550
|
+
for (const { path, record } of ontology.records) {
|
|
551
|
+
const value = record.attrs["scope"];
|
|
552
|
+
if (value === void 0) continue;
|
|
553
|
+
const scope = readScope(value);
|
|
554
|
+
if (typeof scope === "string") problems.push({
|
|
555
|
+
path,
|
|
556
|
+
message: scope
|
|
557
|
+
});
|
|
558
|
+
else if (canonicalScope(scope) === void 0) problems.push({
|
|
559
|
+
path,
|
|
560
|
+
message: "The scope has no value: no value from from to to is in its classes."
|
|
561
|
+
});
|
|
562
|
+
else scopes.set(record.id, scope);
|
|
563
|
+
}
|
|
564
|
+
const named = /* @__PURE__ */ new Set();
|
|
565
|
+
for (const { path, record } of ontology.records) {
|
|
566
|
+
if (record.kind !== "result" || !isLive(record)) continue;
|
|
567
|
+
for (const edge of record.edges ?? []) {
|
|
568
|
+
const problem = records.get(edge.to);
|
|
569
|
+
if (edge.type !== "about" || !isLive(edge) || problem?.record.kind !== "problem") continue;
|
|
570
|
+
if (record.attrs["scope"] === void 0) problems.push({
|
|
571
|
+
path,
|
|
572
|
+
message: `The result is about ${edge.to}, so it has a scope.`
|
|
573
|
+
});
|
|
574
|
+
if (problem.record.attrs["scope"] === void 0 && !named.has(edge.to)) {
|
|
575
|
+
named.add(edge.to);
|
|
576
|
+
problems.push({
|
|
577
|
+
path: problem.path,
|
|
578
|
+
message: `The result ${record.id} is about the problem, so the problem has a scope.`
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
const own = scopes.get(record.id);
|
|
582
|
+
const theirs = scopes.get(edge.to);
|
|
583
|
+
if (own !== void 0 && theirs !== void 0 && own.variable !== theirs.variable) problems.push({
|
|
584
|
+
path,
|
|
585
|
+
message: `The scope of the result has the variable ${own.variable}, and the scope of ${edge.to} has ${theirs.variable}.`
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
function keyOf(edge, key) {
|
|
591
|
+
return JSON.stringify(key.map((part) => part === "from" ? edge.from : part === "to" ? edge.to : edge.qualifiers[part] ?? null));
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* This function checks the ontology, and gives each problem that it finds, in the order of the paths. No problem means
|
|
595
|
+
* that the data is valid:
|
|
596
|
+
*
|
|
597
|
+
* - The grammar is valid: unique names, known parents and ends, keys of known parts and schemas that compile.
|
|
598
|
+
* - Each record file agrees with `schema/record.schema.json`, and its attributes agree with the schema of its kind.
|
|
599
|
+
* - The id of each record starts with its kind, its file is at the path of its id, and no two records have one id.
|
|
600
|
+
* - Each relation has a relation kind that is not abstract, ends of the correct kinds, and correct qualifiers.
|
|
601
|
+
* - No two live relations of a kind have the same key. For example, an area has at most one home.
|
|
602
|
+
* - Each id of an envelope names a record, and each source is a record of kind source.
|
|
603
|
+
*/
|
|
604
|
+
function checkOntology(ontology) {
|
|
605
|
+
const problems = [];
|
|
606
|
+
const { grammar } = ontology;
|
|
607
|
+
const validators = checkGrammar(ontology, problems);
|
|
608
|
+
const idPattern = new RegExp(grammar.idPattern);
|
|
609
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
610
|
+
const paths = /* @__PURE__ */ new Map();
|
|
611
|
+
for (const { path, record } of ontology.records) {
|
|
612
|
+
if (!validators.record(record)) {
|
|
613
|
+
for (const message of errorTexts("record", validators.record.errors)) problems.push({
|
|
614
|
+
path,
|
|
615
|
+
message
|
|
616
|
+
});
|
|
617
|
+
continue;
|
|
618
|
+
}
|
|
619
|
+
const earlier = paths.get(record.id);
|
|
620
|
+
if (earlier !== void 0) problems.push({
|
|
621
|
+
path,
|
|
622
|
+
message: `The id ${record.id} is also the id of ${earlier}.`
|
|
623
|
+
});
|
|
624
|
+
paths.set(record.id, path);
|
|
625
|
+
kinds.set(record.id, record.kind);
|
|
626
|
+
}
|
|
627
|
+
for (const { path, record } of ontology.records) {
|
|
628
|
+
if (paths.get(record.id) !== path) continue;
|
|
629
|
+
if (!idPattern.test(record.id)) problems.push({
|
|
630
|
+
path,
|
|
631
|
+
message: `The id ${record.id} does not agree with the id pattern.`
|
|
632
|
+
});
|
|
633
|
+
if (kindOfId(record.id) !== record.kind) problems.push({
|
|
634
|
+
path,
|
|
635
|
+
message: `The id ${record.id} does not start with its kind ${record.kind} and a dot.`
|
|
636
|
+
});
|
|
637
|
+
else if (pathOfId(record.id) !== path) problems.push({
|
|
638
|
+
path,
|
|
639
|
+
message: `The file of ${record.id} is not at ${pathOfId(record.id)}.`
|
|
640
|
+
});
|
|
641
|
+
const validate = validators.kinds.get(record.kind);
|
|
642
|
+
if (kindOf(grammar, record.kind) === void 0) problems.push({
|
|
643
|
+
path,
|
|
644
|
+
message: `The kind ${record.kind} is not a kind of the grammar.`
|
|
645
|
+
});
|
|
646
|
+
else if (validate !== void 0 && !validate(record.attrs)) for (const message of errorTexts("attrs", validate.errors)) problems.push({
|
|
647
|
+
path,
|
|
648
|
+
message
|
|
649
|
+
});
|
|
650
|
+
checkEnvelope(record.envelope, "envelope", path, kinds, grammar, problems);
|
|
651
|
+
for (const [index, edge] of (record.edges ?? []).entries()) {
|
|
652
|
+
const what = `edges/${String(index)} (${edge.type} ${edge.to})`;
|
|
653
|
+
const relation = relationOf(grammar, edge.type);
|
|
654
|
+
if (relation === void 0) {
|
|
655
|
+
problems.push({
|
|
656
|
+
path,
|
|
657
|
+
message: `${what}: ${edge.type} is not a relation kind of the grammar.`
|
|
658
|
+
});
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
if (relation.abstract === true) problems.push({
|
|
662
|
+
path,
|
|
663
|
+
message: `${what}: the relation kind ${edge.type} is abstract.`
|
|
664
|
+
});
|
|
665
|
+
if (!isKindIn(grammar, record.kind, relation.from)) problems.push({
|
|
666
|
+
path,
|
|
667
|
+
message: `${what}: a ${record.kind} cannot start a relation ${edge.type}.`
|
|
668
|
+
});
|
|
669
|
+
const to = kinds.get(edge.to);
|
|
670
|
+
if (to === void 0) problems.push({
|
|
671
|
+
path,
|
|
672
|
+
message: `${what}: ${edge.to} is not a record.`
|
|
673
|
+
});
|
|
674
|
+
else if (!isKindIn(grammar, to, relation.to)) problems.push({
|
|
675
|
+
path,
|
|
676
|
+
message: `${what}: a relation ${edge.type} cannot end at a ${to}.`
|
|
677
|
+
});
|
|
678
|
+
const validate = validators.qualifiers.get(edge.type);
|
|
679
|
+
if (validate === void 0 && relation.qualifiers === void 0 && Object.keys(edge.qualifiers ?? {}).length > 0) problems.push({
|
|
680
|
+
path,
|
|
681
|
+
message: `${what}: the relation kind ${edge.type} has no qualifiers.`
|
|
682
|
+
});
|
|
683
|
+
else if (validate !== void 0 && !validate(edge.qualifiers ?? {})) for (const message of errorTexts(`${what} qualifiers`, validate.errors)) problems.push({
|
|
684
|
+
path,
|
|
685
|
+
message
|
|
686
|
+
});
|
|
687
|
+
checkEnvelope(edge.envelope, `${what} envelope`, path, kinds, grammar, problems);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
const facts = /* @__PURE__ */ new Map();
|
|
691
|
+
for (const edge of edgesOf(ontology).filter(isLive)) {
|
|
692
|
+
const relation = relationOf(grammar, edge.type);
|
|
693
|
+
if (relation === void 0) continue;
|
|
694
|
+
const fact = `${edge.type} ${keyOf(edge, relation.key ?? ["from", "to"])}`;
|
|
695
|
+
const first = facts.get(fact);
|
|
696
|
+
const path = paths.get(edge.from) ?? pathOfId(edge.from);
|
|
697
|
+
if (first !== void 0) {
|
|
698
|
+
const parts = (relation.key ?? ["from", "to"]).join(" and ");
|
|
699
|
+
problems.push({
|
|
700
|
+
path,
|
|
701
|
+
message: `The relation ${edge.type} to ${edge.to} has the same ${parts} as a relation ${edge.type} of ${first}. The two cannot both be true.`
|
|
702
|
+
});
|
|
703
|
+
} else facts.set(fact, edge.from);
|
|
704
|
+
}
|
|
705
|
+
checkScopes(ontology, problems);
|
|
706
|
+
return problems.sort((a, b) => a.path === b.path ? 0 : a.path < b.path ? -1 : 1);
|
|
707
|
+
}
|
|
708
|
+
// src/clones.ts
|
|
709
|
+
/** The fewest copied syntax nodes of a class in the report. A smaller class is too small for a home. */
|
|
710
|
+
const CLONE_FLOOR = 200;
|
|
711
|
+
/** This function gives the public repositories of the records: each record of kind repository that exists. */
|
|
712
|
+
function repositoriesOf(records) {
|
|
713
|
+
const repositories = [];
|
|
714
|
+
for (const record of records) {
|
|
715
|
+
if (record.kind !== "repository" || record.attrs["exists"] !== true) continue;
|
|
716
|
+
const owner = textOf(record.attrs, "owner");
|
|
717
|
+
const name = textOf(record.attrs, "name");
|
|
718
|
+
const url = textOf(record.attrs, "url");
|
|
719
|
+
if (owner !== void 0 && name !== void 0 && url !== void 0) repositories.push({
|
|
720
|
+
owner,
|
|
721
|
+
name,
|
|
722
|
+
url
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
return repositories;
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* This function gives the classes of cloned code that no area covers, in groups by their repositories. It keeps a
|
|
729
|
+
* class with copies in two or more public repositories of the records and `floor` or more copied syntax nodes.
|
|
730
|
+
*
|
|
731
|
+
* - The atlas names each repository. This function finds it in the records as the import does. A copy in a
|
|
732
|
+
* repository that it cannot find is not a copy of the report.
|
|
733
|
+
* - The largest group comes first. Two groups of the same size are in the order of their repositories.
|
|
734
|
+
*/
|
|
735
|
+
function cloneGroups(atlas, records, floor = 200) {
|
|
736
|
+
const find = repositoryFinder(atlas, repositoriesOf(records));
|
|
737
|
+
const groups = /* @__PURE__ */ new Map();
|
|
738
|
+
for (const found of atlas.classes) {
|
|
739
|
+
if (found.areas.length > 0) continue;
|
|
740
|
+
const members = /* @__PURE__ */ new Map();
|
|
741
|
+
for (const copy of found.members) {
|
|
742
|
+
const place = find(copy.repo);
|
|
743
|
+
if ("why" in place) continue;
|
|
744
|
+
const member = {
|
|
745
|
+
repository: repositoryId(place.repository.owner, place.repository.name),
|
|
746
|
+
file: copy.file,
|
|
747
|
+
line: copy.line,
|
|
748
|
+
name: copy.name
|
|
749
|
+
};
|
|
750
|
+
members.set(`${member.repository} ${member.file}:${String(member.line)} ${member.name}`, member);
|
|
751
|
+
}
|
|
752
|
+
const repositories = [...new Set([...members.values()].map((member) => member.repository))].sort(compareCodeUnits);
|
|
753
|
+
const copied = found.nodes * (members.size - 1);
|
|
754
|
+
if (repositories.length < 2 || copied < floor) continue;
|
|
755
|
+
const ordered = [...members.values()].sort((a, b) => compareCodeUnits(a.repository, b.repository) || compareCodeUnits(a.file, b.file) || a.line - b.line);
|
|
756
|
+
const key = repositories.join(" ");
|
|
757
|
+
const group = groups.get(key) ?? {
|
|
758
|
+
repositories,
|
|
759
|
+
classes: []
|
|
760
|
+
};
|
|
761
|
+
group.classes.push({
|
|
762
|
+
copied,
|
|
763
|
+
members: ordered
|
|
764
|
+
});
|
|
765
|
+
groups.set(key, group);
|
|
766
|
+
}
|
|
767
|
+
const placeOf = (clone) => clone.members.map((member) => `${member.repository} ${member.file}:${String(member.line)}`).join(" ");
|
|
768
|
+
return [...groups.values()].map(({ repositories, classes }) => ({
|
|
769
|
+
repositories,
|
|
770
|
+
copied: classes.reduce((sum, clone) => sum + clone.copied, 0),
|
|
771
|
+
classes: classes.sort((a, b) => b.copied - a.copied || compareCodeUnits(placeOf(a), placeOf(b)))
|
|
772
|
+
})).sort((a, b) => b.copied - a.copied || compareCodeUnits(a.repositories.join(" "), b.repositories.join(" ")));
|
|
773
|
+
}
|
|
774
|
+
/** This function gives the name of a repository for a person: `owner/name`. */
|
|
775
|
+
function repositoryName(id, byId) {
|
|
776
|
+
const attrs = byId.get(id)?.attrs;
|
|
777
|
+
const owner = attrs === void 0 ? void 0 : textOf(attrs, "owner");
|
|
778
|
+
const name = attrs === void 0 ? void 0 : textOf(attrs, "name");
|
|
779
|
+
return owner === void 0 || name === void 0 ? id : `${owner}/${name}`;
|
|
780
|
+
}
|
|
781
|
+
/** This function gives the text of the functions of one file: each name with its line. */
|
|
782
|
+
function functionsText(members) {
|
|
783
|
+
const parts = [...new Map(members.map((member) => [`${String(member.line)} ${member.name}`, member])).values()].sort((a, b) => a.line - b.line || compareCodeUnits(a.name, b.name)).map((member) => member.name === "<anonymous>" ? `a function with no name at line ${String(member.line)}` : `\`${member.name}\` at line ${String(member.line)}`);
|
|
784
|
+
return listOf(parts);
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* This function gives the report of the groups as Markdown, for the maintainer of the map of homes. The report names
|
|
788
|
+
* each repository, the areas whose code it holds, and each file and function of the copies. It names no hash, so a
|
|
789
|
+
* new read of the atlas gives the same keys. Each title of an area is in quotes, because a title can have commas.
|
|
790
|
+
*/
|
|
791
|
+
function cloneReport(groups, records, floor = 200) {
|
|
792
|
+
const byId = new Map(records.map((record) => [record.id, record]));
|
|
793
|
+
const areasOf = /* @__PURE__ */ new Map();
|
|
794
|
+
for (const [area, repositories] of ownRepositories(records)) {
|
|
795
|
+
const title = textOf(byId.get(area)?.attrs ?? {}, "title") ?? area;
|
|
796
|
+
for (const repository of repositories) areasOf.set(repository, [...areasOf.get(repository) ?? [], title]);
|
|
797
|
+
}
|
|
798
|
+
const classes = groups.reduce((sum, group) => sum + group.classes.length, 0);
|
|
799
|
+
const lines = ["# The cloned code with no home", ""];
|
|
800
|
+
if (classes === 0) {
|
|
801
|
+
lines.push(`The duplication atlas finds no class of cloned code with no home, with ${String(floor)} or more copied syntax nodes.`);
|
|
802
|
+
return lines.join("\n");
|
|
803
|
+
}
|
|
804
|
+
lines.push(`The duplication atlas finds ${countOf(classes, "class", "classes")} of cloned code that no area of the map of homes covers, in ${countOf(groups.length, "group")}.`, `Each class has copies in two or more public repositories, and ${String(floor)} or more copied syntax nodes.`, "For each group, the maintainer chooses a home, or writes why the copies stay.");
|
|
805
|
+
for (const group of groups) {
|
|
806
|
+
lines.push("", `## ${listOf(group.repositories.map((id) => `\`${repositoryName(id, byId)}\``))}`, "");
|
|
807
|
+
lines.push(`${countOf(group.classes.length, "class", "classes")}, ${group.copied.toLocaleString("en-US")} copied syntax nodes.`, "");
|
|
808
|
+
for (const repository of group.repositories) {
|
|
809
|
+
const areas = (areasOf.get(repository) ?? []).sort(compareCodeUnits).map((title) => `"${title}"`);
|
|
810
|
+
const holds = areas.length === 0 ? "It holds the code of no area." : `It holds the code of the ${areas.length === 1 ? "area" : "areas"} ${listOf(areas)}.`;
|
|
811
|
+
lines.push(`- \`${repositoryName(repository, byId)}\`. ${holds}`);
|
|
812
|
+
const files = /* @__PURE__ */ new Map();
|
|
813
|
+
for (const clone of group.classes) for (const member of clone.members) if (member.repository === repository) files.set(member.file, [...files.get(member.file) ?? [], member]);
|
|
814
|
+
for (const [file, members] of [...files.entries()].sort(([a], [b]) => compareCodeUnits(a, b))) lines.push(` - \`${file}\`: ${functionsText(members)}.`);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return lines.join("\n");
|
|
818
|
+
}
|
|
819
|
+
// src/homes.ts
|
|
820
|
+
/** The id of the record of kind source for the map of homes. */
|
|
821
|
+
const MAP_SOURCE_ID = "source.conventions-map";
|
|
822
|
+
/** The id of the record of kind source for the lists of the public repositories of each owner on GitHub. */
|
|
823
|
+
const GITHUB_SOURCE_ID = "source.github-repositories";
|
|
824
|
+
/** The ids of the sources of the import. The import writes each record of these sources, and removes the old ones. */
|
|
825
|
+
const IMPORT_SOURCE_IDS = [MAP_SOURCE_ID, GITHUB_SOURCE_ID];
|
|
826
|
+
/** The envelope of each record that the import makes from the map. */
|
|
827
|
+
const ENVELOPE = { source_ids: [MAP_SOURCE_ID] };
|
|
828
|
+
/** The envelope of a repository that only the lists of GitHub name. */
|
|
829
|
+
const GITHUB_ENVELOPE = { source_ids: [GITHUB_SOURCE_ID] };
|
|
830
|
+
/**
|
|
831
|
+
* This function gives the public form of a text of the map. It removes the ids of roadmap items, because they mean
|
|
832
|
+
* nothing outside their repositories. The map itself keeps the ids.
|
|
833
|
+
*
|
|
834
|
+
* This function is a shortcut. It ends with the item C28 of `docs/ROADMAP.md`: when the notes of the map have no ids,
|
|
835
|
+
* the import stops this removal.
|
|
836
|
+
*/
|
|
837
|
+
function publicText(text) {
|
|
838
|
+
return text.replace(/\s?Planned as item [A-Z]+[0-9]+\./g, "").replace(/\bthe program [A-Z]+[0-9]+ of\b/g, "the roadmap of").replace(/ \((?:[A-Z]{1,3}-?[0-9]{1,4}|[0-9]{1,2}-[0-9]{1,2})\)/g, "").trim();
|
|
839
|
+
}
|
|
840
|
+
/** This function gives the repository `owner/name` of a repository URL of npm, or undefined when it is not on GitHub. */
|
|
841
|
+
function githubRepositoryOf(url) {
|
|
842
|
+
const lower = url.toLowerCase();
|
|
843
|
+
const at = lower.indexOf("github.com");
|
|
844
|
+
const separator = lower.charAt(at + 10);
|
|
845
|
+
if (at < 0 || separator !== "/" && separator !== ":") return void 0;
|
|
846
|
+
const [owner = "", rest = ""] = lower.slice(at + 10 + 1).split("/");
|
|
847
|
+
const name = (rest.split("#")[0] ?? "").replace(/\.git$/, "");
|
|
848
|
+
if (owner === "" || name === "" || /\s/.test(owner + name)) return void 0;
|
|
849
|
+
return `${owner}/${name}`;
|
|
850
|
+
}
|
|
851
|
+
/** The records of an import while it runs, by id. A second record with the same id adds its edges to the first. */
|
|
852
|
+
var RecordSet = class {
|
|
853
|
+
byId = /* @__PURE__ */ new Map();
|
|
854
|
+
add(record) {
|
|
855
|
+
const earlier = this.byId.get(record.id);
|
|
856
|
+
if (earlier === void 0) {
|
|
857
|
+
this.byId.set(record.id, record);
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
const edges = [...earlier.edges ?? []];
|
|
861
|
+
for (const edge of record.edges ?? []) if (!edges.some((other) => other.type === edge.type && other.to === edge.to)) edges.push(edge);
|
|
862
|
+
this.byId.set(record.id, {
|
|
863
|
+
...earlier,
|
|
864
|
+
edges
|
|
865
|
+
});
|
|
866
|
+
}
|
|
867
|
+
/** This function gives each record in the order of the ids, with its edges in the order of their type and end. */
|
|
868
|
+
sorted() {
|
|
869
|
+
const order = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
870
|
+
return [...this.byId.values()].map((record) => {
|
|
871
|
+
const edges = [...record.edges ?? []].sort((a, b) => order(`${a.type} ${a.to}`, `${b.type} ${b.to}`));
|
|
872
|
+
const base = {
|
|
873
|
+
id: record.id,
|
|
874
|
+
kind: record.kind,
|
|
875
|
+
attrs: record.attrs,
|
|
876
|
+
...record.envelope === void 0 ? {} : { envelope: record.envelope }
|
|
877
|
+
};
|
|
878
|
+
return edges.length === 0 ? base : {
|
|
879
|
+
...base,
|
|
880
|
+
edges
|
|
881
|
+
};
|
|
882
|
+
}).sort((a, b) => order(a.id, b.id));
|
|
883
|
+
}
|
|
884
|
+
};
|
|
885
|
+
/**
|
|
886
|
+
* This function makes the records of the ontology from the map of homes and the live facts. It reads nothing itself.
|
|
887
|
+
*
|
|
888
|
+
* - Each home gives a record of kind area, and its repository gives a record of kind repository with the relation home-of.
|
|
889
|
+
* - The import finds each repository under each owner, so a move between the owners does not wait on the map.
|
|
890
|
+
* - A repository that is not public is left out. A home whose repository is not public is left out, except a planned home:
|
|
891
|
+
* its repository is a record with `exists: false`.
|
|
892
|
+
* - Each package of the map gives a record of kind package. Its repository comes from npm when npm names one.
|
|
893
|
+
* - Each repository of `alsoIn` gives the relation holds-copy to the area: the code of the area moves between it and the home.
|
|
894
|
+
* - Each public repository that is not a fork and not archived gives a record of kind repository, also when the map does
|
|
895
|
+
* not name it. Its source is then the lists of GitHub. A repository record has the description of GitHub.
|
|
896
|
+
*/
|
|
897
|
+
function recordsFromHomes(homes, facts) {
|
|
898
|
+
const records = new RecordSet();
|
|
899
|
+
const skipped = [];
|
|
900
|
+
const known = new Map(facts.repositories.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository]));
|
|
901
|
+
const find = (home, ref) => {
|
|
902
|
+
for (const candidate of reposOf({
|
|
903
|
+
...home,
|
|
904
|
+
repo: ref,
|
|
905
|
+
alsoIn: []
|
|
906
|
+
})) {
|
|
907
|
+
const repository = known.get(candidate.toLowerCase());
|
|
908
|
+
if (repository !== void 0) return repository;
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
const addRepository = (repository, exists, edges, envelope = ENVELOPE) => {
|
|
912
|
+
const id = repositoryId(repository.owner, repository.name);
|
|
913
|
+
const attrs = {
|
|
914
|
+
owner: repository.owner,
|
|
915
|
+
name: repository.name,
|
|
916
|
+
url: repository.url,
|
|
917
|
+
exists
|
|
918
|
+
};
|
|
919
|
+
const description = repository.description?.trim() ?? "";
|
|
920
|
+
if (description !== "") attrs["description"] = description;
|
|
921
|
+
records.add({
|
|
922
|
+
id,
|
|
923
|
+
kind: "repository",
|
|
924
|
+
attrs,
|
|
925
|
+
envelope,
|
|
926
|
+
edges
|
|
927
|
+
});
|
|
928
|
+
return id;
|
|
929
|
+
};
|
|
930
|
+
records.add({
|
|
931
|
+
id: MAP_SOURCE_ID,
|
|
932
|
+
kind: "source",
|
|
933
|
+
attrs: {
|
|
934
|
+
title: "The map of homes of @mark1russell7/conventions",
|
|
935
|
+
url: "https://www.npmjs.com/package/@mark1russell7/conventions",
|
|
936
|
+
version: facts.version,
|
|
937
|
+
license: "MIT"
|
|
938
|
+
}
|
|
939
|
+
});
|
|
940
|
+
for (const home of homes) {
|
|
941
|
+
const areaId = makeId("area", home.area);
|
|
942
|
+
const found = find(home, home.repo);
|
|
943
|
+
const [owner = "", name = ""] = home.repo.split("/");
|
|
944
|
+
if (found === void 0 && home.state !== "planned") {
|
|
945
|
+
skipped.push(`The area ${home.area}: its repository is not public.`);
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
const homeId = addRepository(found ?? {
|
|
949
|
+
owner,
|
|
950
|
+
name,
|
|
951
|
+
url: `https://github.com/${home.repo}`
|
|
952
|
+
}, found !== void 0, [{
|
|
953
|
+
type: "home-of",
|
|
954
|
+
to: areaId,
|
|
955
|
+
qualifiers: { state: home.state }
|
|
956
|
+
}]);
|
|
957
|
+
const attrs = {
|
|
958
|
+
title: home.title,
|
|
959
|
+
covers: publicText(home.covers)
|
|
960
|
+
};
|
|
961
|
+
const note = home.note === void 0 ? "" : publicText(home.note);
|
|
962
|
+
if (note !== "") attrs["note"] = note;
|
|
963
|
+
if (home.words.length > 0) attrs["words"] = home.words;
|
|
964
|
+
if (home.signatures !== void 0 && home.signatures.length > 0) attrs["signatures"] = home.signatures;
|
|
965
|
+
if (home.modules !== void 0 && home.modules.length > 0) attrs["modules"] = home.modules;
|
|
966
|
+
records.add({
|
|
967
|
+
id: areaId,
|
|
968
|
+
kind: "area",
|
|
969
|
+
attrs,
|
|
970
|
+
envelope: ENVELOPE
|
|
971
|
+
});
|
|
972
|
+
const pending = new Set(home.pending ?? []);
|
|
973
|
+
for (const packageName of [.../* @__PURE__ */ new Set([...home.packages, ...pending])]) {
|
|
974
|
+
const fact = facts.npm.get(packageName);
|
|
975
|
+
const published = fact?.published ?? !pending.has(packageName);
|
|
976
|
+
const state = published ? "published" : home.packages.includes(packageName) ? "unpublished" : "planned";
|
|
977
|
+
const npmRepository = fact?.repository === void 0 ? void 0 : find(home, fact.repository);
|
|
978
|
+
const partOf = npmRepository === void 0 ? homeId : addRepository(npmRepository, true, []);
|
|
979
|
+
const packageAttrs = {
|
|
980
|
+
name: packageName,
|
|
981
|
+
registry: "npm",
|
|
982
|
+
purl: npmPurl(packageName),
|
|
983
|
+
state
|
|
984
|
+
};
|
|
985
|
+
if (published) packageAttrs["url"] = `https://www.npmjs.com/package/${packageName}`;
|
|
986
|
+
records.add({
|
|
987
|
+
id: npmPackageId(packageName),
|
|
988
|
+
kind: "package",
|
|
989
|
+
attrs: packageAttrs,
|
|
990
|
+
envelope: ENVELOPE,
|
|
991
|
+
edges: [{
|
|
992
|
+
type: "part-of",
|
|
993
|
+
to: partOf
|
|
994
|
+
}, {
|
|
995
|
+
type: "covers",
|
|
996
|
+
to: areaId
|
|
997
|
+
}]
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
for (const ref of home.alsoIn ?? []) {
|
|
1001
|
+
const repository = find(home, ref);
|
|
1002
|
+
if (repository === void 0) {
|
|
1003
|
+
skipped.push(`The area ${home.area}: a repository of alsoIn is not public.`);
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
if (repositoryId(repository.owner, repository.name) !== homeId) addRepository(repository, true, [{
|
|
1007
|
+
type: "holds-copy",
|
|
1008
|
+
to: areaId
|
|
1009
|
+
}]);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
records.add({
|
|
1013
|
+
id: GITHUB_SOURCE_ID,
|
|
1014
|
+
kind: "source",
|
|
1015
|
+
attrs: {
|
|
1016
|
+
title: "The lists of the public repositories of each owner on GitHub",
|
|
1017
|
+
url: "https://docs.github.com/en/rest/repos/repos#list-repositories-for-a-user"
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
for (const repository of facts.repositories) if (repository.fork !== true && repository.archived !== true) addRepository(repository, true, [], GITHUB_ENVELOPE);
|
|
1021
|
+
return {
|
|
1022
|
+
records: records.sorted(),
|
|
1023
|
+
skipped
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
// src/polite.ts
|
|
1027
|
+
/** The name of the client in each request. The repository is the contact. */
|
|
1028
|
+
const USER_AGENT = "canon-import/1 (+https://github.com/metrograph-labs/canon)";
|
|
1029
|
+
/** The most requests in progress at one time. Each host has one request in progress at most. */
|
|
1030
|
+
const HOSTS_AT_ONCE = 4;
|
|
1031
|
+
/** The name of each API in a message. Another host has its own name in the message. */
|
|
1032
|
+
const SOURCES = {
|
|
1033
|
+
"api.github.com": "the GitHub API",
|
|
1034
|
+
"registry.npmjs.org": "the npm registry"
|
|
1035
|
+
};
|
|
1036
|
+
/**
|
|
1037
|
+
* This function gives a fetch that reads each URL through `send` of `polite-crawler/api`. Each host has one request in
|
|
1038
|
+
* progress at most, and the policy of the crawler sets the rest between two requests of a host.
|
|
1039
|
+
*
|
|
1040
|
+
* - An answer 2xx gives its text. Another status gives the error `HTTP <status>`, as `githubFetch` of conventions does.
|
|
1041
|
+
* The fetch follows no redirect.
|
|
1042
|
+
* - A request with no answer, or a stopped host, gives the text of the error. The text has no token.
|
|
1043
|
+
*/
|
|
1044
|
+
function politeFetch(options = {}) {
|
|
1045
|
+
const transport = options.transport ?? fetchTransport({ userAgent: "canon-import/1 (+https://github.com/metrograph-labs/canon)" });
|
|
1046
|
+
const pace = {
|
|
1047
|
+
scheduler: new HostScheduler(realClock, 4),
|
|
1048
|
+
now: realClock.now
|
|
1049
|
+
};
|
|
1050
|
+
const token = options.githubToken === void 0 || options.githubToken === "" ? void 0 : options.githubToken;
|
|
1051
|
+
const answerOf = async (url) => {
|
|
1052
|
+
const host = new URL(url).host;
|
|
1053
|
+
const secrets = host === "api.github.com" && token !== void 0 ? [token] : [];
|
|
1054
|
+
const headers = secrets.length > 0 ? {
|
|
1055
|
+
accept: "application/vnd.github+json",
|
|
1056
|
+
authorization: `Bearer ${String(token)}`
|
|
1057
|
+
} : {};
|
|
1058
|
+
try {
|
|
1059
|
+
const { reply } = await send(pace, transport, {
|
|
1060
|
+
source: SOURCES[host] ?? host,
|
|
1061
|
+
host,
|
|
1062
|
+
what: url,
|
|
1063
|
+
exchange: {
|
|
1064
|
+
method: "GET",
|
|
1065
|
+
url,
|
|
1066
|
+
headers,
|
|
1067
|
+
body: null
|
|
1068
|
+
},
|
|
1069
|
+
secrets,
|
|
1070
|
+
redact: redactSecrets
|
|
1071
|
+
});
|
|
1072
|
+
return reply.status >= 200 && reply.status < 300 ? { text: reply.body } : { error: `HTTP ${String(reply.status)}` };
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
return { error: redactSecrets(errorMessage(error), secrets) };
|
|
1075
|
+
}
|
|
1076
|
+
};
|
|
1077
|
+
return async (urls) => new Map(await Promise.all(urls.map(async (url) => [url, await answerOf(url)])));
|
|
1078
|
+
}
|
|
1079
|
+
// src/facts.ts
|
|
1080
|
+
/** The most pages of 100 repositories that the read asks for each owner. A full last page is an error. */
|
|
1081
|
+
const REPOSITORY_PAGES = 5;
|
|
1082
|
+
/** This function gives the URLs of the pages of the public repositories of each owner. */
|
|
1083
|
+
function repositoryPageUrls() {
|
|
1084
|
+
return OWNERS.flatMap((owner) => Array.from({ length: 5 }, (_, page) => `https://api.github.com/users/${owner.login}/repos?type=owner&per_page=100&page=${String(page + 1)}`));
|
|
1085
|
+
}
|
|
1086
|
+
/** This function gives the URL of the latest version of an npm package in the registry. */
|
|
1087
|
+
function npmLatestUrl(name) {
|
|
1088
|
+
return `https://registry.npmjs.org/${name.replaceAll("/", "%2f")}/latest`;
|
|
1089
|
+
}
|
|
1090
|
+
/** This function reads the public repositories of the answers of the pages. It throws when a page has no answer, or the last page is full. */
|
|
1091
|
+
function repositoriesOfPages(answers) {
|
|
1092
|
+
const repositories = [];
|
|
1093
|
+
for (const owner of OWNERS) for (let page = 1; page <= 5; page += 1) {
|
|
1094
|
+
const url = `https://api.github.com/users/${owner.login}/repos?type=owner&per_page=100&page=${String(page)}`;
|
|
1095
|
+
const answer = answers.get(url);
|
|
1096
|
+
if (answer === void 0 || "error" in answer) throw new Error(`GitHub gave no list of the repositories of ${owner.login}: ${answer?.error ?? "no answer"}`);
|
|
1097
|
+
const list = JSON.parse(answer.text);
|
|
1098
|
+
if (page === 5 && list.length === 100) throw new Error(`${owner.login} has more than ${String(500)} repositories: increase REPOSITORY_PAGES.`);
|
|
1099
|
+
for (const item of list) if (!item.private) repositories.push({
|
|
1100
|
+
owner: item.owner.login,
|
|
1101
|
+
name: item.name,
|
|
1102
|
+
url: item.html_url,
|
|
1103
|
+
description: item.description ?? void 0,
|
|
1104
|
+
fork: item.fork === true,
|
|
1105
|
+
archived: item.archived === true,
|
|
1106
|
+
defaultBranch: item.default_branch
|
|
1107
|
+
});
|
|
1108
|
+
if (list.length < 100) break;
|
|
1109
|
+
}
|
|
1110
|
+
return repositories;
|
|
1111
|
+
}
|
|
1112
|
+
/** This function reads the fact of npm for one package from the answer for its latest version. It throws on an error that is not 404. */
|
|
1113
|
+
function npmFactOf(name, answer) {
|
|
1114
|
+
if (answer === void 0) throw new Error(`npm gave no answer for ${name}.`);
|
|
1115
|
+
if ("error" in answer) {
|
|
1116
|
+
if (answer.error === "HTTP 404") return { published: false };
|
|
1117
|
+
throw new Error(`npm gave an error for ${name}: ${answer.error}`);
|
|
1118
|
+
}
|
|
1119
|
+
const manifest = JSON.parse(answer.text);
|
|
1120
|
+
const url = typeof manifest.repository === "string" ? manifest.repository : manifest.repository?.url;
|
|
1121
|
+
const repository = url === void 0 ? void 0 : githubRepositoryOf(url);
|
|
1122
|
+
return repository === void 0 ? { published: true } : {
|
|
1123
|
+
published: true,
|
|
1124
|
+
repository
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
/** This function gives the version of the installed `@mark1russell7/conventions`, which has the map. */
|
|
1128
|
+
function conventionsVersion() {
|
|
1129
|
+
const file = createRequire(import.meta.url).resolve("@mark1russell7/conventions/package.json");
|
|
1130
|
+
return JSON.parse(readFileSync(file, "utf8")).version;
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* This function reads the live facts of the homes from GitHub, npm and the duplication atlas. The facts are the public
|
|
1134
|
+
* repositories of each owner, the latest version of each package of the map, and the atlas. The default fetch is
|
|
1135
|
+
* `politeFetch` with no token. Each request goes at the pace of its host.
|
|
1136
|
+
*/
|
|
1137
|
+
async function readHomeFacts(homes, fetch = politeFetch()) {
|
|
1138
|
+
const names = [...new Set(homes.flatMap((home) => [...home.packages, ...home.pending ?? []]))].sort();
|
|
1139
|
+
const answers = await fetch([
|
|
1140
|
+
...repositoryPageUrls(),
|
|
1141
|
+
...names.map(npmLatestUrl),
|
|
1142
|
+
ATLAS_URL
|
|
1143
|
+
]);
|
|
1144
|
+
const npm = new Map(names.map((name) => [name, npmFactOf(name, answers.get(npmLatestUrl(name)))]));
|
|
1145
|
+
return {
|
|
1146
|
+
repositories: repositoriesOfPages(answers),
|
|
1147
|
+
npm,
|
|
1148
|
+
version: conventionsVersion(),
|
|
1149
|
+
atlas: readAtlas(answers.get(ATLAS_URL))
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
// src/load.ts
|
|
1153
|
+
/** This error tells that a file of the ontology is not valid JSON. The check gives each other problem as a `Problem`. */
|
|
1154
|
+
var OntologyReadError = class extends Error {
|
|
1155
|
+
/** The path of the file, relative to the root. */
|
|
1156
|
+
path;
|
|
1157
|
+
constructor(path, message) {
|
|
1158
|
+
super(`${path}: ${message}`);
|
|
1159
|
+
this.name = "OntologyReadError";
|
|
1160
|
+
this.path = path;
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
/** This function reads a JSON file. It throws an `OntologyReadError` with the relative path when the text is not JSON. */
|
|
1164
|
+
function readJson(root, path) {
|
|
1165
|
+
const text = readFileSync(join(root, path), "utf8");
|
|
1166
|
+
try {
|
|
1167
|
+
return JSON.parse(text);
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
throw new OntologyReadError(path, error instanceof Error ? error.message : String(error));
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* This function reads the grammar, the schema of a record file and each record file of the repository at `root`. The
|
|
1174
|
+
* record files are each `.json` file under the folder `ontology`, in sorted order. The function does not check them:
|
|
1175
|
+
* `checkOntology` does that.
|
|
1176
|
+
*/
|
|
1177
|
+
function readOntology(root) {
|
|
1178
|
+
return {
|
|
1179
|
+
grammar: readJson(root, GRAMMAR_FILE),
|
|
1180
|
+
recordSchema: readJson(root, RECORD_SCHEMA_FILE),
|
|
1181
|
+
records: findFiles({
|
|
1182
|
+
root,
|
|
1183
|
+
include: [`${ONTOLOGY_FOLDER}/**/*.json`]
|
|
1184
|
+
}).map((file) => {
|
|
1185
|
+
const path = toPosix(relative(root, file));
|
|
1186
|
+
return {
|
|
1187
|
+
path,
|
|
1188
|
+
record: readJson(root, path)
|
|
1189
|
+
};
|
|
1190
|
+
})
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
// src/test-gates.ts
|
|
1194
|
+
/** The test gates of the read, in the order of the records. */
|
|
1195
|
+
const GATE_NAMES = [
|
|
1196
|
+
"mutation",
|
|
1197
|
+
"property",
|
|
1198
|
+
"speed",
|
|
1199
|
+
"rigs"
|
|
1200
|
+
];
|
|
1201
|
+
/** The lane file of the mutation tests, when the caller of the workflow gives no input `lane`. */
|
|
1202
|
+
const MUTATION_LANE = "mutation.json";
|
|
1203
|
+
/** The file of the rig records of a repository. */
|
|
1204
|
+
const RIGS_FILE = "docs/rigs.json";
|
|
1205
|
+
/** The packages of property tests. A package file that names one of them in its dependencies has property tests. */
|
|
1206
|
+
const PROPERTY_PACKAGES = ["fast-check", "@mark1russell7/rigor-testkit"];
|
|
1207
|
+
/** The package of the speed gates. */
|
|
1208
|
+
const BENCH_PACKAGE = "@mark1russell7/rigor-bench";
|
|
1209
|
+
/** The most rules of a branch that the read asks for. A full page is a no read. */
|
|
1210
|
+
const RULES_PAGE = 100;
|
|
1211
|
+
/** This function gives the path of a branch in a URL: each part of the name, encoded. */
|
|
1212
|
+
function branchPath(branch) {
|
|
1213
|
+
return branch.split("/").map(encodeURIComponent).join("/");
|
|
1214
|
+
}
|
|
1215
|
+
/** This function gives the URL of the full tree of the branch of a repository: one request for each repository. */
|
|
1216
|
+
function treeUrl(repository) {
|
|
1217
|
+
return `https://api.github.com/repos/${repository.owner}/${repository.name}/git/trees/${branchPath(repository.branch)}?recursive=1`;
|
|
1218
|
+
}
|
|
1219
|
+
/** This function gives the URL of the rules of the branch of a repository. GitHub gives them with no token. */
|
|
1220
|
+
function rulesUrl(repository) {
|
|
1221
|
+
return `https://api.github.com/repos/${repository.owner}/${repository.name}/rules/branches/${branchPath(repository.branch)}?per_page=${String(100)}`;
|
|
1222
|
+
}
|
|
1223
|
+
/** This function gives the URL of the text of one file of the branch. The host of raw files is not the API. */
|
|
1224
|
+
function fileUrl(repository, path) {
|
|
1225
|
+
return `https://raw.githubusercontent.com/${repository.owner}/${repository.name}/${branchPath(repository.branch)}/${path.split("/").map(encodeURIComponent).join("/")}`;
|
|
1226
|
+
}
|
|
1227
|
+
/** This function gives the text of the answer, or the reason why there is no text. */
|
|
1228
|
+
function textOrReason(answer, what) {
|
|
1229
|
+
if (answer === void 0) return { no_read: `GitHub gave no answer for ${what}.` };
|
|
1230
|
+
if ("error" in answer) return { no_read: `GitHub gave ${answer.error} for ${what}.` };
|
|
1231
|
+
return { text: answer.text };
|
|
1232
|
+
}
|
|
1233
|
+
/** This function reads JSON. It gives undefined when the text is not JSON. */
|
|
1234
|
+
function jsonOf(text) {
|
|
1235
|
+
try {
|
|
1236
|
+
return JSON.parse(text);
|
|
1237
|
+
} catch {
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* This function reads the answer for a tree. A tree that GitHub truncated is a no read, because a missing file of such a
|
|
1243
|
+
* tree does not show that the file is absent. A 404 and each other error are a no read too.
|
|
1244
|
+
*/
|
|
1245
|
+
function treeOf(answer) {
|
|
1246
|
+
const read = textOrReason(answer, "the tree of the branch");
|
|
1247
|
+
if ("no_read" in read) return read;
|
|
1248
|
+
const body = jsonOf(read.text);
|
|
1249
|
+
if (booleanOf(body, "truncated") === true) return { no_read: "GitHub gave a truncated tree, so the read cannot see each file." };
|
|
1250
|
+
const items = arrayOf(body, "tree", (item) => isRecord(item) ? item : void 0);
|
|
1251
|
+
if (items === void 0) return { no_read: "The answer for the tree has no list of files." };
|
|
1252
|
+
const files = /* @__PURE__ */ new Map();
|
|
1253
|
+
for (const item of items) {
|
|
1254
|
+
const path = textOf(item, "path");
|
|
1255
|
+
const sha = textOf(item, "sha");
|
|
1256
|
+
if (textOf(item, "type") === "blob" && path !== void 0 && sha !== void 0) files.set(path, sha);
|
|
1257
|
+
}
|
|
1258
|
+
return { files };
|
|
1259
|
+
}
|
|
1260
|
+
/** This function reads the names of the necessary checks from the answer for the rules of a branch. */
|
|
1261
|
+
function necessaryChecksOf(answer) {
|
|
1262
|
+
const read = textOrReason(answer, "the rules of the branch");
|
|
1263
|
+
if ("no_read" in read) return read;
|
|
1264
|
+
const rules = jsonOf(read.text);
|
|
1265
|
+
if (!Array.isArray(rules)) return { no_read: "The answer for the rules of the branch is not a list." };
|
|
1266
|
+
if (rules.length >= 100) return { no_read: `The branch has ${String(100)} rules or more, and the read asks for one page.` };
|
|
1267
|
+
const checks = /* @__PURE__ */ new Set();
|
|
1268
|
+
for (const rule of rules) {
|
|
1269
|
+
if (textOf(rule, "type") !== "required_status_checks") continue;
|
|
1270
|
+
const parameters = recordOf(rule, "parameters");
|
|
1271
|
+
for (const check of arrayOf(parameters, "required_status_checks", (item) => textOf(item, "context")) ?? []) checks.add(check);
|
|
1272
|
+
}
|
|
1273
|
+
return { checks: [...checks].sort() };
|
|
1274
|
+
}
|
|
1275
|
+
/** This function tells if a path is a workflow of GitHub Actions. GitHub reads only the files at the top of the folder. */
|
|
1276
|
+
function isWorkflowPath(path) {
|
|
1277
|
+
return /^\.github\/workflows\/[^/]+\.ya?ml$/.test(path);
|
|
1278
|
+
}
|
|
1279
|
+
/** This function tells if a path is a package file of the repository: not in `node_modules` and not in a fixture folder. */
|
|
1280
|
+
function isPackagePath(path) {
|
|
1281
|
+
const parts = path.split("/");
|
|
1282
|
+
return parts.at(-1) === "package.json" && !parts.some((part) => part === "node_modules" || /^(__)?fixtures?(__)?$/.test(part));
|
|
1283
|
+
}
|
|
1284
|
+
/** This function gives the paths of the files that the read needs from a tree: each workflow and each package file. */
|
|
1285
|
+
function filesToRead(tree) {
|
|
1286
|
+
return [...tree.files.keys()].filter((path) => isWorkflowPath(path) || isPackagePath(path)).sort();
|
|
1287
|
+
}
|
|
1288
|
+
/** This function reads the jobs of a workflow file. It gives a no read when the text is not a workflow. */
|
|
1289
|
+
function workflowOf(path, text) {
|
|
1290
|
+
let document;
|
|
1291
|
+
try {
|
|
1292
|
+
document = parse(text);
|
|
1293
|
+
} catch {
|
|
1294
|
+
return { no_read: `The workflow ${path} is not valid YAML.` };
|
|
1295
|
+
}
|
|
1296
|
+
const jobs = recordOf(document, "jobs");
|
|
1297
|
+
if (jobs === void 0) return { no_read: `The workflow ${path} has no jobs.` };
|
|
1298
|
+
return {
|
|
1299
|
+
path,
|
|
1300
|
+
jobs: Object.entries(jobs).map(([id, job]) => {
|
|
1301
|
+
const needs = isRecord(job) ? job["needs"] : void 0;
|
|
1302
|
+
return {
|
|
1303
|
+
id,
|
|
1304
|
+
name: textOf(job, "name") ?? id,
|
|
1305
|
+
uses: textOf(job, "uses"),
|
|
1306
|
+
with: recordOf(job, "with"),
|
|
1307
|
+
needs: typeof needs === "string" ? [needs] : arrayOf(job, "needs", readText) ?? [],
|
|
1308
|
+
steps: arrayOf(job, "steps", (step) => isRecord(step) ? {
|
|
1309
|
+
uses: textOf(step, "uses"),
|
|
1310
|
+
run: textOf(step, "run")
|
|
1311
|
+
} : void 0) ?? []
|
|
1312
|
+
};
|
|
1313
|
+
})
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
/** This function tells if a job uses the reusable workflow `file` of the template, or the copy of the template itself. */
|
|
1317
|
+
function callsTemplate(job, file) {
|
|
1318
|
+
const uses = job.uses ?? "";
|
|
1319
|
+
return (uses.startsWith("mark1russell7/template/") || uses.startsWith("./")) && new RegExp(`(^|/)\\.github/workflows/${file.replaceAll(".", "\\.")}(@|$)`).test(uses);
|
|
1320
|
+
}
|
|
1321
|
+
/** A command that starts the tests of a package. */
|
|
1322
|
+
const TEST_COMMAND = /\b(vitest|(pnpm|npm|yarn)(\s+-r|\s+--recursive)?\s+(run\s+)?test)\b/;
|
|
1323
|
+
/** A command or a step that starts a bench of `@mark1russell7/rigor-bench`. */
|
|
1324
|
+
const BENCH_COMMAND = /\b(rigor-gate-line|rigor-stamp|bench(mark)?)\b/i;
|
|
1325
|
+
/** This function gives the checks of the jobs `seeds` and of each job that needs them, also through other jobs. */
|
|
1326
|
+
function checksOf(workflow, seeds) {
|
|
1327
|
+
const ids = new Set(seeds.map((job) => job.id));
|
|
1328
|
+
let grew = ids.size > 0;
|
|
1329
|
+
while (grew) {
|
|
1330
|
+
grew = false;
|
|
1331
|
+
for (const job of workflow.jobs) if (!ids.has(job.id) && job.needs.some((need) => ids.has(need))) {
|
|
1332
|
+
ids.add(job.id);
|
|
1333
|
+
grew = true;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
return workflow.jobs.filter((job) => ids.has(job.id)).map((job) => job.uses === void 0 ? job.name : `${job.name} / *`);
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* This function tells if the check `pattern` of a gate gives the check `name`. A `*` and each expression `${{ }}` match
|
|
1340
|
+
* any text. A job of a matrix with no name gives its values after its name, in parentheses.
|
|
1341
|
+
*/
|
|
1342
|
+
function checkMatches(pattern, name) {
|
|
1343
|
+
if (pattern.length > MAX_CHECK_TEXT || name.length > MAX_CHECK_TEXT) return false;
|
|
1344
|
+
const parts = literalParts(pattern);
|
|
1345
|
+
if (globMatches(parts, name)) return true;
|
|
1346
|
+
if (!name.endsWith(")")) return false;
|
|
1347
|
+
for (let at = name.indexOf(" ("); at !== -1; at = name.indexOf(" (", at + 1)) if (globMatches(parts, name.slice(0, at))) return true;
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
/** The longest check name or pattern that `checkMatches` reads. A longer text matches nothing. */
|
|
1351
|
+
const MAX_CHECK_TEXT = 512;
|
|
1352
|
+
/**
|
|
1353
|
+
* This function gives the literal parts of a check pattern. A `*` and each expression `${{ }}` separate the parts. An
|
|
1354
|
+
* expression with no end is literal text. The function uses no regular expression, so its time is linear.
|
|
1355
|
+
*/
|
|
1356
|
+
function literalParts(pattern) {
|
|
1357
|
+
const parts = [];
|
|
1358
|
+
let part = "";
|
|
1359
|
+
for (let at = 0; at < pattern.length;) {
|
|
1360
|
+
if (pattern[at] === "*") {
|
|
1361
|
+
parts.push(part);
|
|
1362
|
+
part = "";
|
|
1363
|
+
at++;
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
const end = pattern.startsWith("${{", at) ? pattern.indexOf("}}", at + 3) : -1;
|
|
1367
|
+
if (end !== -1) {
|
|
1368
|
+
parts.push(part);
|
|
1369
|
+
part = "";
|
|
1370
|
+
at = end + 2;
|
|
1371
|
+
continue;
|
|
1372
|
+
}
|
|
1373
|
+
part += pattern[at] ?? "";
|
|
1374
|
+
at++;
|
|
1375
|
+
}
|
|
1376
|
+
parts.push(part);
|
|
1377
|
+
return parts;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* This function tells if `name` is the literal parts `parts` with any text between each two. The first part starts the
|
|
1381
|
+
* name, and the last part ends it. Each middle part takes its first place after the part before it.
|
|
1382
|
+
*/
|
|
1383
|
+
function globMatches(parts, name) {
|
|
1384
|
+
const first = parts[0] ?? "";
|
|
1385
|
+
if (parts.length === 1) return name === first;
|
|
1386
|
+
const last = parts.at(-1) ?? "";
|
|
1387
|
+
if (!name.startsWith(first) || name.length < first.length + last.length || !name.endsWith(last)) return false;
|
|
1388
|
+
const end = name.length - last.length;
|
|
1389
|
+
let at = first.length;
|
|
1390
|
+
for (const part of parts.slice(1, -1)) {
|
|
1391
|
+
const found = name.indexOf(part, at);
|
|
1392
|
+
if (found === -1 || found + part.length > end) return false;
|
|
1393
|
+
at = found + part.length;
|
|
1394
|
+
}
|
|
1395
|
+
return true;
|
|
1396
|
+
}
|
|
1397
|
+
/** This function selects the jobs of each workflow with `pick`, and gives their files and their checks. */
|
|
1398
|
+
function pickJobs(workflows, pick) {
|
|
1399
|
+
const files = [];
|
|
1400
|
+
const checks = /* @__PURE__ */ new Set();
|
|
1401
|
+
const jobs = [];
|
|
1402
|
+
for (const workflow of workflows) {
|
|
1403
|
+
const seeds = workflow.jobs.filter(pick);
|
|
1404
|
+
if (seeds.length === 0) continue;
|
|
1405
|
+
files.push(workflow.path);
|
|
1406
|
+
jobs.push(...seeds);
|
|
1407
|
+
for (const check of checksOf(workflow, seeds)) checks.add(check);
|
|
1408
|
+
}
|
|
1409
|
+
return {
|
|
1410
|
+
files,
|
|
1411
|
+
checks: [...checks].sort(),
|
|
1412
|
+
jobs
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
/** This function reads the names of the dependencies of each kind from the text of a package file. */
|
|
1416
|
+
function packageOf(path, text) {
|
|
1417
|
+
const manifest = jsonOf(text);
|
|
1418
|
+
if (!isRecord(manifest)) return { no_read: `The package file ${path} is not a JSON object.` };
|
|
1419
|
+
const names = [
|
|
1420
|
+
"dependencies",
|
|
1421
|
+
"devDependencies",
|
|
1422
|
+
"optionalDependencies",
|
|
1423
|
+
"peerDependencies"
|
|
1424
|
+
].flatMap((field) => Object.keys(recordOf(manifest, field) ?? {}));
|
|
1425
|
+
return {
|
|
1426
|
+
path,
|
|
1427
|
+
dependencies: new Set(names)
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
/** The facts of a gate from a list of parts. Each part has a text for `missing`, and the files that show it. */
|
|
1431
|
+
function factOf(parts, checks, rules) {
|
|
1432
|
+
const files = [...new Set(parts.flatMap((part) => part.files))].sort();
|
|
1433
|
+
const missing = parts.filter((part) => part.files.length === 0).map((part) => part.missing);
|
|
1434
|
+
if (missing.length > 0) return {
|
|
1435
|
+
exists: false,
|
|
1436
|
+
...files.length > 0 ? { files } : {},
|
|
1437
|
+
missing
|
|
1438
|
+
};
|
|
1439
|
+
if ("no_read" in rules) return {
|
|
1440
|
+
exists: true,
|
|
1441
|
+
files,
|
|
1442
|
+
checks,
|
|
1443
|
+
no_read: rules.no_read
|
|
1444
|
+
};
|
|
1445
|
+
return {
|
|
1446
|
+
exists: true,
|
|
1447
|
+
necessary: checks.some((check) => rules.checks.some((name) => checkMatches(check, name))),
|
|
1448
|
+
files,
|
|
1449
|
+
checks
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* This function gives the fact of each test gate from a tree, the answers for its files and the rules of the branch. It
|
|
1454
|
+
* reads nothing itself.
|
|
1455
|
+
*
|
|
1456
|
+
* - mutation: a lane file (`mutation.json`, or the input `lane` of the caller) and a job that calls `reusable-mutation.yml`.
|
|
1457
|
+
* - property: a package file that names `fast-check` or `@mark1russell7/rigor-testkit`. Its checks are the checks of
|
|
1458
|
+
* each job that calls `reusable-ci.yml` or starts the tests, and of each job that needs such a job.
|
|
1459
|
+
* - speed: a package file that names `@mark1russell7/rigor-bench`, and a job that starts a bench. A bench job uses the
|
|
1460
|
+
* action `stamp-gate`, the bin `rigor-gate-line` or `rigor-stamp`, or a command with the word `bench`.
|
|
1461
|
+
* - rigs: the file `docs/rigs.json` and a job that calls `reusable-rigs.yml`.
|
|
1462
|
+
*
|
|
1463
|
+
* A file with no answer, or a file that the read cannot parse, gives a no read for each gate that needs it.
|
|
1464
|
+
*/
|
|
1465
|
+
function gatesOf(tree, answers, rules) {
|
|
1466
|
+
const workflows = [];
|
|
1467
|
+
const packages = [];
|
|
1468
|
+
let workflowFault;
|
|
1469
|
+
let packageFault;
|
|
1470
|
+
for (const path of filesToRead(tree)) {
|
|
1471
|
+
const read = textOrReason(answers.get(path), `the file ${path}`);
|
|
1472
|
+
const parsed = "no_read" in read ? read : isWorkflowPath(path) ? workflowOf(path, read.text) : packageOf(path, read.text);
|
|
1473
|
+
if ("no_read" in parsed) {
|
|
1474
|
+
if (isWorkflowPath(path)) workflowFault ??= parsed.no_read;
|
|
1475
|
+
else packageFault ??= parsed.no_read;
|
|
1476
|
+
} else if ("jobs" in parsed) workflows.push(parsed);
|
|
1477
|
+
else packages.push(parsed);
|
|
1478
|
+
}
|
|
1479
|
+
const naming = (names) => packages.filter((file) => names.some((name) => file.dependencies.has(name))).map((file) => file.path);
|
|
1480
|
+
const has = (path) => tree.files.has(path) ? [path] : [];
|
|
1481
|
+
const mutationJobs = pickJobs(workflows, (job) => callsTemplate(job, "reusable-mutation.yml"));
|
|
1482
|
+
const lanes = mutationJobs.jobs.map((job) => typeof job.with?.["lane"] === "string" ? job.with["lane"] : MUTATION_LANE);
|
|
1483
|
+
const lane = lanes.find((path) => tree.files.has(path)) ?? lanes[0] ?? "mutation.json";
|
|
1484
|
+
const mutation = workflowFault !== void 0 ? { no_read: workflowFault } : factOf([{
|
|
1485
|
+
missing: `the lane file \`${lane}\``,
|
|
1486
|
+
files: has(lane)
|
|
1487
|
+
}, {
|
|
1488
|
+
missing: "a job that calls `reusable-mutation.yml` of `mark1russell7/template`",
|
|
1489
|
+
files: mutationJobs.files
|
|
1490
|
+
}], mutationJobs.checks, rules);
|
|
1491
|
+
const propertyFiles = naming(PROPERTY_PACKAGES);
|
|
1492
|
+
const testJobs = pickJobs(workflows, (job) => callsTemplate(job, "reusable-ci.yml") || job.steps.some((step) => TEST_COMMAND.test(step.run ?? "")));
|
|
1493
|
+
const propertyPart = {
|
|
1494
|
+
missing: "a package file that names `fast-check` or `@mark1russell7/rigor-testkit` in its dependencies",
|
|
1495
|
+
files: propertyFiles
|
|
1496
|
+
};
|
|
1497
|
+
const property = packageFault !== void 0 ? { no_read: packageFault } : propertyFiles.length > 0 && workflowFault !== void 0 ? {
|
|
1498
|
+
exists: true,
|
|
1499
|
+
files: propertyFiles,
|
|
1500
|
+
no_read: workflowFault
|
|
1501
|
+
} : factOf([propertyPart], testJobs.checks, rules);
|
|
1502
|
+
const benchJobs = pickJobs(workflows, (job) => job.steps.some((step) => (step.uses ?? "").includes("/.github/actions/stamp-gate") || BENCH_COMMAND.test(step.run ?? "")));
|
|
1503
|
+
const speed = (packageFault ?? workflowFault) !== void 0 ? { no_read: packageFault ?? workflowFault ?? "" } : factOf([{
|
|
1504
|
+
missing: `a package file that names \`${BENCH_PACKAGE}\` in its dependencies`,
|
|
1505
|
+
files: naming([BENCH_PACKAGE])
|
|
1506
|
+
}, {
|
|
1507
|
+
missing: "a job that starts a bench: the action `stamp-gate`, the bin `rigor-gate-line` or `rigor-stamp`, or a command `bench`",
|
|
1508
|
+
files: benchJobs.files
|
|
1509
|
+
}], benchJobs.checks, rules);
|
|
1510
|
+
const rigsJobs = pickJobs(workflows, (job) => callsTemplate(job, "reusable-rigs.yml"));
|
|
1511
|
+
return {
|
|
1512
|
+
mutation,
|
|
1513
|
+
property,
|
|
1514
|
+
speed,
|
|
1515
|
+
rigs: workflowFault !== void 0 ? { no_read: workflowFault } : factOf([{
|
|
1516
|
+
missing: `the file \`${RIGS_FILE}\``,
|
|
1517
|
+
files: has(RIGS_FILE)
|
|
1518
|
+
}, {
|
|
1519
|
+
missing: "a job that calls `reusable-rigs.yml` of `mark1russell7/template`",
|
|
1520
|
+
files: rigsJobs.files
|
|
1521
|
+
}], rigsJobs.checks, rules)
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
/** This function gives the time of a read in the form of the records: UTC, to the second. */
|
|
1525
|
+
function timeText(ms) {
|
|
1526
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
1527
|
+
}
|
|
1528
|
+
/** This function gives a no read for each gate. */
|
|
1529
|
+
function noReadOfEach(reason) {
|
|
1530
|
+
return {
|
|
1531
|
+
mutation: { no_read: reason },
|
|
1532
|
+
property: { no_read: reason },
|
|
1533
|
+
speed: { no_read: reason },
|
|
1534
|
+
rigs: { no_read: reason }
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* This function reads the test gates of each repository. The default fetch is `politeFetch` with no token, so each
|
|
1539
|
+
* request goes at the pace of its host. The read makes two rounds of requests:
|
|
1540
|
+
*
|
|
1541
|
+
* 1. the tree and the rules of the branch of each repository, from the API of GitHub,
|
|
1542
|
+
* 2. each workflow file and each package file of each tree, from the host of raw files. Two files with the same content
|
|
1543
|
+
* id give one request.
|
|
1544
|
+
*
|
|
1545
|
+
* A repository whose tree has no read gives a no read for each gate. The read does not throw for one repository.
|
|
1546
|
+
*/
|
|
1547
|
+
async function readTestGates(repositories, fetch = politeFetch(), now = Date.now) {
|
|
1548
|
+
const first = await fetch(repositories.flatMap((repository) => [treeUrl(repository), rulesUrl(repository)]));
|
|
1549
|
+
const trees = repositories.map((repository) => ({
|
|
1550
|
+
repository,
|
|
1551
|
+
tree: treeOf(first.get(treeUrl(repository))),
|
|
1552
|
+
rules: necessaryChecksOf(first.get(rulesUrl(repository)))
|
|
1553
|
+
}));
|
|
1554
|
+
const urlOfContent = /* @__PURE__ */ new Map();
|
|
1555
|
+
for (const { repository, tree } of trees) {
|
|
1556
|
+
if ("no_read" in tree) continue;
|
|
1557
|
+
for (const path of filesToRead(tree)) {
|
|
1558
|
+
const sha = tree.files.get(path) ?? "";
|
|
1559
|
+
if (!urlOfContent.has(sha)) urlOfContent.set(sha, fileUrl(repository, path));
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const second = await fetch([...new Set(urlOfContent.values())]);
|
|
1563
|
+
const readAt = timeText(now());
|
|
1564
|
+
const result = /* @__PURE__ */ new Map();
|
|
1565
|
+
for (const { repository, tree, rules } of trees) {
|
|
1566
|
+
const answers = /* @__PURE__ */ new Map();
|
|
1567
|
+
if (!("no_read" in tree)) for (const path of filesToRead(tree)) answers.set(path, second.get(urlOfContent.get(tree.files.get(path) ?? "") ?? ""));
|
|
1568
|
+
const gates = "no_read" in tree ? noReadOfEach(tree.no_read) : gatesOf(tree, answers, rules);
|
|
1569
|
+
result.set(repositoryId(repository.owner, repository.name), {
|
|
1570
|
+
read_at: readAt,
|
|
1571
|
+
branch: repository.branch,
|
|
1572
|
+
..."no_read" in rules ? {} : { necessary_checks: rules.checks },
|
|
1573
|
+
gates
|
|
1574
|
+
});
|
|
1575
|
+
}
|
|
1576
|
+
return result;
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* This function gives the home repositories that the read examines. Each is a record of kind repository that exists
|
|
1580
|
+
* and is the home of an area. The lists of GitHub give its default branch. A repository with no known default branch
|
|
1581
|
+
* is not in the list.
|
|
1582
|
+
*/
|
|
1583
|
+
function gateRepositoriesOf(records, repositories) {
|
|
1584
|
+
const branches = new Map(repositories.map((repository) => [`${repository.owner}/${repository.name}`.toLowerCase(), repository.defaultBranch]));
|
|
1585
|
+
const list = [];
|
|
1586
|
+
for (const record of records) {
|
|
1587
|
+
if (record.kind !== "repository" || record.attrs["exists"] !== true || !(record.edges ?? []).some((edge) => edge.type === "home-of")) continue;
|
|
1588
|
+
const owner = String(record.attrs["owner"]);
|
|
1589
|
+
const name = String(record.attrs["name"]);
|
|
1590
|
+
const branch = branches.get(`${owner}/${name}`.toLowerCase());
|
|
1591
|
+
if (branch !== void 0 && branch !== "") list.push({
|
|
1592
|
+
owner,
|
|
1593
|
+
name,
|
|
1594
|
+
branch
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
return list;
|
|
1598
|
+
}
|
|
1599
|
+
/** This function gives the text of the facts of a read with no time, to compare two reads. */
|
|
1600
|
+
function factText(gates) {
|
|
1601
|
+
if (!isRecord(gates)) return "";
|
|
1602
|
+
const { read_at: _time, ...facts } = gates;
|
|
1603
|
+
return JSON.stringify(facts);
|
|
1604
|
+
}
|
|
1605
|
+
/**
|
|
1606
|
+
* This function adds the test gates of each repository to its record as the attribute `test_gates`. When the earlier
|
|
1607
|
+
* record of a repository has the same facts, the new record keeps the earlier time. Thus a read with no change writes
|
|
1608
|
+
* no file.
|
|
1609
|
+
*/
|
|
1610
|
+
function withTestGates(records, gates, earlier = []) {
|
|
1611
|
+
const old = new Map(earlier.map(({ record }) => [record.id, record.attrs["test_gates"]]));
|
|
1612
|
+
return records.map((record) => {
|
|
1613
|
+
const read = gates.get(record.id);
|
|
1614
|
+
if (read === void 0 || record.kind !== "repository") return record;
|
|
1615
|
+
const before = old.get(record.id);
|
|
1616
|
+
const time = isRecord(before) && factText(before) === factText(read) ? textOf(before, "read_at") : void 0;
|
|
1617
|
+
return {
|
|
1618
|
+
...record,
|
|
1619
|
+
attrs: {
|
|
1620
|
+
...record.attrs,
|
|
1621
|
+
test_gates: time === void 0 ? read : {
|
|
1622
|
+
...read,
|
|
1623
|
+
read_at: time
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
});
|
|
1628
|
+
}
|
|
1629
|
+
// src/write.ts
|
|
1630
|
+
/** This function gives the text of the file of a record: JSON with two spaces and a last line end. */
|
|
1631
|
+
function recordText(record) {
|
|
1632
|
+
return `${JSON.stringify(record, null, 2)}\n`;
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
* This function plans the changes that make the files agree with the records `records`. The program that made the
|
|
1636
|
+
* records owns each existing record for which `owns` is true. A file of such a record with no new record is removed.
|
|
1637
|
+
* The plan writes only the files whose text changes. It does not write over a record that the program does not own.
|
|
1638
|
+
*/
|
|
1639
|
+
function planWrite(root, records, existing, owns) {
|
|
1640
|
+
const write = /* @__PURE__ */ new Map();
|
|
1641
|
+
const others = new Set(existing.filter(({ record }) => !owns(record)).map(({ path }) => path));
|
|
1642
|
+
const keep = [];
|
|
1643
|
+
for (const record of records) {
|
|
1644
|
+
const path = pathOfId(record.id);
|
|
1645
|
+
if (others.has(path)) {
|
|
1646
|
+
keep.push(path);
|
|
1647
|
+
continue;
|
|
1648
|
+
}
|
|
1649
|
+
const text = recordText(record);
|
|
1650
|
+
let old;
|
|
1651
|
+
try {
|
|
1652
|
+
old = readFileSync(join(root, path), "utf8");
|
|
1653
|
+
} catch {
|
|
1654
|
+
old = void 0;
|
|
1655
|
+
}
|
|
1656
|
+
if (old?.replace(/\r\n/g, "\n") !== text) write.set(path, text);
|
|
1657
|
+
}
|
|
1658
|
+
const kept = new Set(records.map((record) => pathOfId(record.id)));
|
|
1659
|
+
return {
|
|
1660
|
+
write,
|
|
1661
|
+
remove: existing.filter(({ path, record }) => owns(record) && !kept.has(path)).map(({ path }) => path),
|
|
1662
|
+
keep
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
/** This function tells if a plan changes no file. */
|
|
1666
|
+
function isEmptyPlan(plan) {
|
|
1667
|
+
return plan.write.size === 0 && plan.remove.length === 0;
|
|
1668
|
+
}
|
|
1669
|
+
/** This function applies a plan: it writes each file, with its folder, and removes each file of `remove`. */
|
|
1670
|
+
function applyPlan(root, plan) {
|
|
1671
|
+
for (const [path, text] of plan.write) {
|
|
1672
|
+
mkdirSync(dirname(join(root, path)), { recursive: true });
|
|
1673
|
+
writeFileSync(join(root, path), text);
|
|
1674
|
+
}
|
|
1675
|
+
for (const path of plan.remove) rmSync(join(root, path));
|
|
1676
|
+
}
|
|
1677
|
+
// src/cli.ts
|
|
1678
|
+
/** The help text of the command line. */
|
|
1679
|
+
const USAGE = `Usage: canon <command> [--root <folder>]
|
|
1680
|
+
|
|
1681
|
+
Commands:
|
|
1682
|
+
check Check the grammar and each record. Exit code 1 when there is a problem.
|
|
1683
|
+
targets Show the targets of the target query, the claimable targets first.
|
|
1684
|
+
targets --json Give the targets as JSON.
|
|
1685
|
+
targets --write Write the targets to ontology/target/.
|
|
1686
|
+
targets --check Exit code 1 when the files of ontology/target/ do not agree with the query.
|
|
1687
|
+
results Show each claim that needs a result record, and its state: checked, partial or not checked.
|
|
1688
|
+
results --json Give the claims as JSON.
|
|
1689
|
+
results --check Exit code 1 when a claim is not checked, or a status claim is partial.
|
|
1690
|
+
import Read the map of homes and the live facts, and write the records of the map.
|
|
1691
|
+
board Show the changes that make the target board agree with the target query.
|
|
1692
|
+
board --apply Make the changes: open, change and close the issues of the board.
|
|
1693
|
+
claim --issue <number> --user <login> --comment <text>
|
|
1694
|
+
Decide a comment /claim or /unclaim on an issue of the board, and write the answer.
|
|
1695
|
+
clones [--floor <n>]
|
|
1696
|
+
Read the duplication atlas, and show the cloned code that no home covers, as Markdown.
|
|
1697
|
+
The report keeps a class with n or more copied syntax nodes (default ${String(200)}).
|
|
1698
|
+
|
|
1699
|
+
The commands board and claim read the token of GitHub from GITHUB_TOKEN. The commands import and clones
|
|
1700
|
+
send it to the API of GitHub when it is set. They make each request at the pace of its host.
|
|
1701
|
+
|
|
1702
|
+
The root is the folder of ${GRAMMAR_FILE}: the current folder or a parent of it.`;
|
|
1703
|
+
/** This function finds the root of the repository: the folder whose `schema` folder has the grammar. */
|
|
1704
|
+
function findRoot(from) {
|
|
1705
|
+
const grammar = findUp(GRAMMAR_FILE, from);
|
|
1706
|
+
return grammar === null ? void 0 : dirname(dirname(grammar));
|
|
1707
|
+
}
|
|
1708
|
+
/** This function tells if a record is one of the sources `sources`, or comes from one of them. */
|
|
1709
|
+
function fromSources(record, sources) {
|
|
1710
|
+
return sources.includes(record.id) || (record.envelope?.source_ids ?? []).some((id) => sources.includes(id));
|
|
1711
|
+
}
|
|
1712
|
+
/** This function writes the changes of a plan as lines. */
|
|
1713
|
+
function showPlan(printer, plan) {
|
|
1714
|
+
for (const path of plan.write.keys()) printer.line(`write ${path}`);
|
|
1715
|
+
for (const path of plan.remove) printer.line(`remove ${path}`);
|
|
1716
|
+
for (const path of plan.keep) printer.warn(`A person wrote ${path}, so the program keeps it.`);
|
|
1717
|
+
}
|
|
1718
|
+
/** This function writes the problems of the check. It gives the exit code: 0 with no problem, else 1. */
|
|
1719
|
+
function check(printer, ontology) {
|
|
1720
|
+
const problems = checkOntology(ontology);
|
|
1721
|
+
for (const problem of problems) printer.status("fail", `${problem.path}: ${problem.message}`);
|
|
1722
|
+
if (problems.length > 0) return 1;
|
|
1723
|
+
printer.status("ok", `${String(ontology.records.length)} records agree with the grammar.`);
|
|
1724
|
+
return 0;
|
|
1725
|
+
}
|
|
1726
|
+
/** This function runs the command `results`. It gives the exit code. */
|
|
1727
|
+
function results(printer, ontology, flags) {
|
|
1728
|
+
const claims = resultClaimsOf(ontology);
|
|
1729
|
+
if (flags.has("--json")) {
|
|
1730
|
+
printer.json(claims);
|
|
1731
|
+
return 0;
|
|
1732
|
+
}
|
|
1733
|
+
const open = claims.filter(claimFails);
|
|
1734
|
+
if (claims.length > 0) printer.table(claims.map((claim) => [
|
|
1735
|
+
claim.state,
|
|
1736
|
+
claim.kind === "status" ? claim.status ?? "" : `solved by ${claim.function ?? ""}`,
|
|
1737
|
+
claim.problem,
|
|
1738
|
+
claim.results.join(", ")
|
|
1739
|
+
]), { head: [
|
|
1740
|
+
"state",
|
|
1741
|
+
"claim",
|
|
1742
|
+
"problem",
|
|
1743
|
+
"results"
|
|
1744
|
+
] });
|
|
1745
|
+
const total = `${String(claims.length - open.length)} of ${String(claims.length)} claims have a result record of the necessary scope.`;
|
|
1746
|
+
if (flags.has("--check") && open.length > 0) {
|
|
1747
|
+
printer.status("fail", `${total} Add a result for each claim that is not checked. A status claim needs a result with the scope of its problem.`);
|
|
1748
|
+
return 1;
|
|
1749
|
+
}
|
|
1750
|
+
printer.status(open.length === 0 ? "ok" : "info", total);
|
|
1751
|
+
return 0;
|
|
1752
|
+
}
|
|
1753
|
+
/** This function runs the command `targets`. It gives the exit code. */
|
|
1754
|
+
function targets(printer, root, ontology, flags) {
|
|
1755
|
+
const list = targetsOf(ontology);
|
|
1756
|
+
if (flags.has("--json")) {
|
|
1757
|
+
printer.json(list);
|
|
1758
|
+
return 0;
|
|
1759
|
+
}
|
|
1760
|
+
if (flags.has("--write") || flags.has("--check")) {
|
|
1761
|
+
const plan = planWrite(root, list, ontology.records, (record) => record.kind === "target");
|
|
1762
|
+
if (flags.has("--write")) {
|
|
1763
|
+
applyPlan(root, plan);
|
|
1764
|
+
showPlan(printer, plan);
|
|
1765
|
+
printer.status("ok", `${String(list.length)} targets.`);
|
|
1766
|
+
return 0;
|
|
1767
|
+
}
|
|
1768
|
+
if (isEmptyPlan(plan)) {
|
|
1769
|
+
printer.status("ok", `The ${String(list.length)} files of ontology/target/ agree with the target query.`);
|
|
1770
|
+
return 0;
|
|
1771
|
+
}
|
|
1772
|
+
showPlan(printer, plan);
|
|
1773
|
+
printer.status("fail", "The files of ontology/target/ do not agree with the target query. Start `pnpm canon targets --write`, and commit the files.");
|
|
1774
|
+
return 1;
|
|
1775
|
+
}
|
|
1776
|
+
printer.table(list.map((target) => [
|
|
1777
|
+
target.attrs.claimable ? "yes" : "no",
|
|
1778
|
+
target.attrs.size,
|
|
1779
|
+
target.attrs.home,
|
|
1780
|
+
target.attrs.title
|
|
1781
|
+
]), { head: [
|
|
1782
|
+
"claimable",
|
|
1783
|
+
"size",
|
|
1784
|
+
"repository",
|
|
1785
|
+
"title"
|
|
1786
|
+
] });
|
|
1787
|
+
printer.line(`${String(list.filter((target) => target.attrs.claimable).length)} of ${String(list.length)} targets are claimable.`);
|
|
1788
|
+
return 0;
|
|
1789
|
+
}
|
|
1790
|
+
/**
|
|
1791
|
+
* This function runs the command `import`. It gives the exit code. When the read of the duplication atlas fails, the
|
|
1792
|
+
* import does not own the records of the atlas, so the old candidates stay.
|
|
1793
|
+
*/
|
|
1794
|
+
async function importHomes(printer, root, ontology, options) {
|
|
1795
|
+
const fetch = options.fetch ?? politeFetch();
|
|
1796
|
+
const facts = await readHomeFacts(HOMES, fetch);
|
|
1797
|
+
const result = recordsFromHomes(HOMES, facts);
|
|
1798
|
+
const gates = await readTestGates(gateRepositoriesOf(result.records, facts.repositories), fetch, options.now);
|
|
1799
|
+
const homes = withTestGates(result.records, gates, ontology.records);
|
|
1800
|
+
const atlas = facts.atlas !== void 0 && "atlas" in facts.atlas ? recordsFromAtlas(facts.atlas.atlas, facts.repositories, result.records) : void 0;
|
|
1801
|
+
const sources = atlas === void 0 ? IMPORT_SOURCE_IDS : [...IMPORT_SOURCE_IDS, ATLAS_SOURCE_ID];
|
|
1802
|
+
const records = [...homes, ...atlas?.records ?? []];
|
|
1803
|
+
const plan = planWrite(root, records, ontology.records, (record) => fromSources(record, sources));
|
|
1804
|
+
applyPlan(root, plan);
|
|
1805
|
+
showPlan(printer, plan);
|
|
1806
|
+
for (const text of [...result.skipped, ...atlas?.skipped ?? []]) printer.warn(text);
|
|
1807
|
+
for (const [id, read] of gates) {
|
|
1808
|
+
const reasons = [...new Set(Object.values(read.gates).flatMap((gate) => gate.no_read === void 0 ? [] : [gate.no_read]))];
|
|
1809
|
+
if (reasons.length > 0) printer.warn(`The test gates of ${id} have no full read. ${reasons.join(" ")}`);
|
|
1810
|
+
}
|
|
1811
|
+
if (facts.atlas !== void 0 && "error" in facts.atlas) printer.warn(`The import keeps the old candidates. ${facts.atlas.error}`);
|
|
1812
|
+
printer.status("ok", `${String(records.length)} records of the map of homes, of the lists of GitHub and of the duplication atlas.`);
|
|
1813
|
+
return 0;
|
|
1814
|
+
}
|
|
1815
|
+
/** This function gives the value after the option `name`, or undefined. */
|
|
1816
|
+
function valueOf(args, name) {
|
|
1817
|
+
const index = args.indexOf(name);
|
|
1818
|
+
return index < 0 ? void 0 : args[index + 1];
|
|
1819
|
+
}
|
|
1820
|
+
/** This function writes a step of the board as a line. */
|
|
1821
|
+
function actionLine(action) {
|
|
1822
|
+
if (action.kind === "create") return `open ${action.target}`;
|
|
1823
|
+
if (action.kind === "update") return `${action.reopen ? "reopen " : "change "} #${String(action.number)} ${action.target}`;
|
|
1824
|
+
if (action.kind === "close") return `close #${String(action.number)} ${action.target} (${action.reason})`;
|
|
1825
|
+
return `release #${String(action.number)} ${action.target} (${action.users.join(", ")})`;
|
|
1826
|
+
}
|
|
1827
|
+
/** This function runs the command `clones`. It gives the exit code: 1 when the read of the atlas fails. */
|
|
1828
|
+
async function clones(printer, ontology, args, options) {
|
|
1829
|
+
const floorText = valueOf(args, "--floor");
|
|
1830
|
+
const floor = floorText === void 0 ? 200 : Number(floorText);
|
|
1831
|
+
if (!Number.isInteger(floor) || floor < 0) {
|
|
1832
|
+
printer.status("fail", `The floor ${floorText ?? ""} is not a whole number of 0 or more.`);
|
|
1833
|
+
return 2;
|
|
1834
|
+
}
|
|
1835
|
+
const read = readAtlas((await (options.fetch ?? politeFetch())([ATLAS_URL])).get(ATLAS_URL));
|
|
1836
|
+
if ("error" in read) {
|
|
1837
|
+
printer.status("fail", read.error);
|
|
1838
|
+
return 1;
|
|
1839
|
+
}
|
|
1840
|
+
const records = ontology.records.map((loaded) => loaded.record);
|
|
1841
|
+
printer.line(cloneReport(cloneGroups(read.atlas, records, floor), records, floor));
|
|
1842
|
+
return 0;
|
|
1843
|
+
}
|
|
1844
|
+
/** This function gives the API of the issues, or writes why there is none. */
|
|
1845
|
+
function issueApi(printer, options) {
|
|
1846
|
+
if (options.issues === void 0) {
|
|
1847
|
+
printer.status("fail", "This command needs the API of GitHub. Set GITHUB_TOKEN.");
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
return options.issues();
|
|
1851
|
+
}
|
|
1852
|
+
/** This function runs the command `board`. It gives the exit code. */
|
|
1853
|
+
async function board(printer, ontology, args, options) {
|
|
1854
|
+
const limitText = valueOf(args, "--limit");
|
|
1855
|
+
const limit = limitText === void 0 ? 20 : Number(limitText);
|
|
1856
|
+
if (!Number.isSafeInteger(limit) || limit < 0) {
|
|
1857
|
+
printer.status("fail", `The limit ${String(limitText)} is not a whole number of 0 or more.`);
|
|
1858
|
+
return 2;
|
|
1859
|
+
}
|
|
1860
|
+
const api = issueApi(printer, options);
|
|
1861
|
+
if (api === void 0) return 2;
|
|
1862
|
+
const now = (options.now ?? Date.now)();
|
|
1863
|
+
const issues = await api.issues();
|
|
1864
|
+
const pulls = /* @__PURE__ */ new Set();
|
|
1865
|
+
for (const issue of issues.filter((candidate) => candidate.state === "open" && isExpired(candidate, now))) {
|
|
1866
|
+
const id = targetOfIssue(issue.body);
|
|
1867
|
+
if (id !== void 0 && await api.hasOpenPull(id)) pulls.add(id);
|
|
1868
|
+
}
|
|
1869
|
+
const actions = planBoard({
|
|
1870
|
+
targets: targetsOf(ontology),
|
|
1871
|
+
issues,
|
|
1872
|
+
now,
|
|
1873
|
+
pulls,
|
|
1874
|
+
limit
|
|
1875
|
+
});
|
|
1876
|
+
for (const action of actions) printer.line(actionLine(action));
|
|
1877
|
+
if (!args.includes("--apply")) {
|
|
1878
|
+
printer.status("info", `${String(actions.length)} changes. Give --apply to make them.`);
|
|
1879
|
+
return 0;
|
|
1880
|
+
}
|
|
1881
|
+
const created = await applyBoard(api, actions);
|
|
1882
|
+
printer.status("ok", `${String(actions.length)} changes, ${String(created.length)} new issues.`);
|
|
1883
|
+
return 0;
|
|
1884
|
+
}
|
|
1885
|
+
/** This function runs the command `claim`. It gives the exit code. */
|
|
1886
|
+
async function claim(printer, ontology, args, options) {
|
|
1887
|
+
const number = Number(valueOf(args, "--issue"));
|
|
1888
|
+
const user = valueOf(args, "--user") ?? "";
|
|
1889
|
+
const command = claimCommandOf(valueOf(args, "--comment") ?? "");
|
|
1890
|
+
if (!Number.isSafeInteger(number) || number < 1 || user === "") {
|
|
1891
|
+
printer.status("fail", "Give --issue <number>, --user <login> and --comment <text>.");
|
|
1892
|
+
return 2;
|
|
1893
|
+
}
|
|
1894
|
+
if (command === void 0) {
|
|
1895
|
+
printer.status("info", "The comment is not /claim or /unclaim. No change.");
|
|
1896
|
+
return 0;
|
|
1897
|
+
}
|
|
1898
|
+
const api = issueApi(printer, options);
|
|
1899
|
+
if (api === void 0) return 2;
|
|
1900
|
+
const issues = await api.issues();
|
|
1901
|
+
const issue = issues.find((candidate) => candidate.number === number);
|
|
1902
|
+
if (issue === void 0) {
|
|
1903
|
+
printer.status("info", `The issue #${String(number)} is not an issue of the board. No change.`);
|
|
1904
|
+
return 0;
|
|
1905
|
+
}
|
|
1906
|
+
const id = targetOfIssue(issue.body);
|
|
1907
|
+
const decision = decideClaim({
|
|
1908
|
+
command,
|
|
1909
|
+
user,
|
|
1910
|
+
issue,
|
|
1911
|
+
target: targetsOf(ontology).find((candidate) => candidate.id === id),
|
|
1912
|
+
issues,
|
|
1913
|
+
now: (options.now ?? Date.now)()
|
|
1914
|
+
});
|
|
1915
|
+
if (decision.kind === "set") {
|
|
1916
|
+
const after = await api.update(number, { assignees: decision.assignees });
|
|
1917
|
+
if (command === "claim" && !after.assignees.includes(user)) {
|
|
1918
|
+
await api.comment(number, `GitHub did not assign \`${user}\`, so the claim did not start. Write the comment \`/claim\` again.`);
|
|
1919
|
+
printer.status("fail", `GitHub did not assign ${user} to #${String(number)}.`);
|
|
1920
|
+
return 1;
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
await api.comment(number, decision.comment);
|
|
1924
|
+
printer.status(decision.kind === "set" ? "ok" : "info", decision.comment);
|
|
1925
|
+
return 0;
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* This function runs the command line with the arguments `args`, and gives the exit code. It writes only to `printer`.
|
|
1929
|
+
* The folder `cwd` is the start of the search for the root. The commands `board` and `claim` use `options.issues`.
|
|
1930
|
+
*/
|
|
1931
|
+
async function runCli(args, printer, cwd, options = {}) {
|
|
1932
|
+
const rootIndex = args.indexOf("--root");
|
|
1933
|
+
const rootArg = rootIndex < 0 ? void 0 : args[rootIndex + 1];
|
|
1934
|
+
const [command, ...flagList] = rootIndex < 0 ? args : [...args.slice(0, rootIndex), ...args.slice(rootIndex + 2)];
|
|
1935
|
+
const flags = new Set(flagList);
|
|
1936
|
+
if (command === void 0 || command === "--help" || command === "help") {
|
|
1937
|
+
printer.line(USAGE);
|
|
1938
|
+
return command === void 0 ? 2 : 0;
|
|
1939
|
+
}
|
|
1940
|
+
const root = rootArg ?? findRoot(cwd);
|
|
1941
|
+
if (root === void 0) {
|
|
1942
|
+
printer.status("fail", `No ${GRAMMAR_FILE} in ${cwd} or a parent folder. Give --root <folder>.`);
|
|
1943
|
+
return 2;
|
|
1944
|
+
}
|
|
1945
|
+
try {
|
|
1946
|
+
const ontology = readOntology(root);
|
|
1947
|
+
if (command === "check") return check(printer, ontology);
|
|
1948
|
+
if (command === "targets") return targets(printer, root, ontology, flags);
|
|
1949
|
+
if (command === "results") return results(printer, ontology, flags);
|
|
1950
|
+
if (command === "import") return await importHomes(printer, root, ontology, options);
|
|
1951
|
+
if (command === "board") return await board(printer, ontology, flagList, options);
|
|
1952
|
+
if (command === "claim") return await claim(printer, ontology, flagList, options);
|
|
1953
|
+
if (command === "clones") return await clones(printer, ontology, flagList, options);
|
|
1954
|
+
} catch (error) {
|
|
1955
|
+
printer.error(error);
|
|
1956
|
+
return 1;
|
|
1957
|
+
}
|
|
1958
|
+
printer.status("fail", `The command ${command} is not a command of canon.`);
|
|
1959
|
+
printer.line(USAGE);
|
|
1960
|
+
return 2;
|
|
1961
|
+
}
|
|
1962
|
+
// src/github.ts
|
|
1963
|
+
/** The most items of one page of a list. */
|
|
1964
|
+
const PAGE = 100;
|
|
1965
|
+
/** The most pages of the list of issues: 1,000 issues. */
|
|
1966
|
+
const MAX_PAGES = 10;
|
|
1967
|
+
/** The colors of the labels of the board, by the start of their names. */
|
|
1968
|
+
const LABEL_COLOR = {
|
|
1969
|
+
target: "0e8a16",
|
|
1970
|
+
gap: "c5def5"
|
|
1971
|
+
};
|
|
1972
|
+
/** This error tells that GitHub refused a request of the board. Its text has no token and no body of an answer. */
|
|
1973
|
+
var IssueApiError = class extends Error {
|
|
1974
|
+
name = "IssueApiError";
|
|
1975
|
+
/** This number is the status of the answer of GitHub. */
|
|
1976
|
+
status;
|
|
1977
|
+
constructor(message, status) {
|
|
1978
|
+
super(message);
|
|
1979
|
+
this.status = status;
|
|
1980
|
+
}
|
|
1981
|
+
};
|
|
1982
|
+
/** This function gives the issue of an item of the REST API, or undefined for a pull request or an item that is not an issue. */
|
|
1983
|
+
function issueOfItem(item) {
|
|
1984
|
+
const number = numberOf(item, "number");
|
|
1985
|
+
const title = textOf(item, "title");
|
|
1986
|
+
const state = textOf(item, "state");
|
|
1987
|
+
if (number === void 0 || title === void 0 || state !== "open" && state !== "closed") return void 0;
|
|
1988
|
+
if (recordOf(item, "pull_request") !== void 0) return void 0;
|
|
1989
|
+
return {
|
|
1990
|
+
number,
|
|
1991
|
+
title,
|
|
1992
|
+
body: textOf(item, "body") ?? "",
|
|
1993
|
+
state,
|
|
1994
|
+
labels: arrayOf(item, "labels", (label) => textOf(label, "name")) ?? [],
|
|
1995
|
+
assignees: arrayOf(item, "assignees", (user) => textOf(user, "login")) ?? []
|
|
1996
|
+
};
|
|
1997
|
+
}
|
|
1998
|
+
/** This function gives the time of the last event that assigned one of the assignees, or undefined when there is none. */
|
|
1999
|
+
function claimTimeOf(events, assignees) {
|
|
2000
|
+
let last;
|
|
2001
|
+
for (const event of readArray(events, (value) => value) ?? []) {
|
|
2002
|
+
const at = timeOf(event, "created_at");
|
|
2003
|
+
const login = textOf(recordOf(event, "assignee"), "login");
|
|
2004
|
+
if (textOf(event, "event") === "assigned" && at !== void 0 && login !== void 0 && assignees.includes(login)) last = Math.max(last ?? at, at);
|
|
2005
|
+
}
|
|
2006
|
+
return last;
|
|
2007
|
+
}
|
|
2008
|
+
/** The body of a PATCH of an issue for a change. */
|
|
2009
|
+
function patchOf(change) {
|
|
2010
|
+
const body = {};
|
|
2011
|
+
if (change.title !== void 0) body["title"] = change.title;
|
|
2012
|
+
if (change.body !== void 0) body["body"] = change.body;
|
|
2013
|
+
if (change.labels !== void 0) body["labels"] = change.labels;
|
|
2014
|
+
if (change.state !== void 0) body["state"] = change.state;
|
|
2015
|
+
if (change.stateReason !== void 0) body["state_reason"] = change.stateReason;
|
|
2016
|
+
if (change.assignees !== void 0) body["assignees"] = change.assignees;
|
|
2017
|
+
return body;
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* This function gives the API of the issues of the repository `owner/name` through a REST client of GitHub. Each
|
|
2021
|
+
* request stops at `signal`. A status of 400 or more throws an `IssueApiError`.
|
|
2022
|
+
*/
|
|
2023
|
+
function githubIssueApi(client, repository, signal) {
|
|
2024
|
+
const base = `/repos/${repository}`;
|
|
2025
|
+
const send = async (request, what) => {
|
|
2026
|
+
const answer = await client.request(request, signal);
|
|
2027
|
+
if (answer.status >= 400) throw new IssueApiError(`GitHub refused ${what} of ${repository} with the status ${String(answer.status)}.`, answer.status);
|
|
2028
|
+
return answer;
|
|
2029
|
+
};
|
|
2030
|
+
const issueAnswer = (answer, what) => {
|
|
2031
|
+
const issue = issueOfItem(answer.body);
|
|
2032
|
+
if (issue === void 0) throw new IssueApiError(`GitHub gave no issue for ${what} of ${repository}.`, answer.status);
|
|
2033
|
+
return issue;
|
|
2034
|
+
};
|
|
2035
|
+
return {
|
|
2036
|
+
async issues() {
|
|
2037
|
+
const issues = [];
|
|
2038
|
+
for (let page = 1; page <= MAX_PAGES; page += 1) {
|
|
2039
|
+
const query = {
|
|
2040
|
+
labels: TARGET_LABEL,
|
|
2041
|
+
state: "all",
|
|
2042
|
+
per_page: String(PAGE),
|
|
2043
|
+
page: String(page)
|
|
2044
|
+
};
|
|
2045
|
+
const items = readArray((await send({
|
|
2046
|
+
method: "GET",
|
|
2047
|
+
path: `${base}/issues`,
|
|
2048
|
+
query
|
|
2049
|
+
}, "the list of issues")).body, (item) => item) ?? [];
|
|
2050
|
+
issues.push(...items.flatMap((item) => issueOfItem(item) ?? []));
|
|
2051
|
+
if (items.length < PAGE) break;
|
|
2052
|
+
}
|
|
2053
|
+
const claimed = [];
|
|
2054
|
+
for (const issue of issues) {
|
|
2055
|
+
if (issue.state !== "open" || issue.assignees.length === 0) {
|
|
2056
|
+
claimed.push(issue);
|
|
2057
|
+
continue;
|
|
2058
|
+
}
|
|
2059
|
+
const events = await send({
|
|
2060
|
+
method: "GET",
|
|
2061
|
+
path: `${base}/issues/${String(issue.number)}/events`,
|
|
2062
|
+
query: { per_page: String(PAGE) }
|
|
2063
|
+
}, "the events of an issue");
|
|
2064
|
+
claimed.push({
|
|
2065
|
+
...issue,
|
|
2066
|
+
claimedAt: claimTimeOf(events.body, issue.assignees)
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
return claimed;
|
|
2070
|
+
},
|
|
2071
|
+
async hasOpenPull(targetId) {
|
|
2072
|
+
const answer = await send({
|
|
2073
|
+
method: "GET",
|
|
2074
|
+
path: "/search/issues",
|
|
2075
|
+
query: {
|
|
2076
|
+
q: `"${targetId}" type:pr state:open`,
|
|
2077
|
+
per_page: String(PAGE)
|
|
2078
|
+
}
|
|
2079
|
+
}, "a search of pull requests");
|
|
2080
|
+
return (arrayOf(answer.body, "items", (item) => textOf(item, "body")) ?? []).some((body) => body.includes(targetId));
|
|
2081
|
+
},
|
|
2082
|
+
async ensureLabels(names) {
|
|
2083
|
+
const answer = await send({
|
|
2084
|
+
method: "GET",
|
|
2085
|
+
path: `${base}/labels`,
|
|
2086
|
+
query: { per_page: String(PAGE) }
|
|
2087
|
+
}, "the list of labels");
|
|
2088
|
+
const have = new Set(readArray(answer.body, (label) => textOf(label, "name")) ?? []);
|
|
2089
|
+
for (const name of names.filter((label) => !have.has(label))) {
|
|
2090
|
+
const color = name === "target" ? LABEL_COLOR.target : LABEL_COLOR.gap;
|
|
2091
|
+
await send({
|
|
2092
|
+
method: "POST",
|
|
2093
|
+
path: `${base}/labels`,
|
|
2094
|
+
body: {
|
|
2095
|
+
name,
|
|
2096
|
+
color
|
|
2097
|
+
}
|
|
2098
|
+
}, "a new label");
|
|
2099
|
+
}
|
|
2100
|
+
},
|
|
2101
|
+
async create(text) {
|
|
2102
|
+
const answer = await send({
|
|
2103
|
+
method: "POST",
|
|
2104
|
+
path: `${base}/issues`,
|
|
2105
|
+
body: {
|
|
2106
|
+
title: text.title,
|
|
2107
|
+
body: text.body,
|
|
2108
|
+
labels: text.labels
|
|
2109
|
+
}
|
|
2110
|
+
}, "a new issue");
|
|
2111
|
+
return issueAnswer(answer, "a new issue").number;
|
|
2112
|
+
},
|
|
2113
|
+
async update(number, change) {
|
|
2114
|
+
return issueAnswer(await send({
|
|
2115
|
+
method: "PATCH",
|
|
2116
|
+
path: `${base}/issues/${String(number)}`,
|
|
2117
|
+
body: patchOf(change)
|
|
2118
|
+
}, "a change of an issue"), "a change of an issue");
|
|
2119
|
+
},
|
|
2120
|
+
async comment(number, text) {
|
|
2121
|
+
await send({
|
|
2122
|
+
method: "POST",
|
|
2123
|
+
path: `${base}/issues/${String(number)}/comments`,
|
|
2124
|
+
body: { body: text }
|
|
2125
|
+
}, "a comment");
|
|
2126
|
+
}
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
export { ATLAS_LIMIT, ATLAS_SCHEMA, ATLAS_SOURCE_ID, ATLAS_URL, BENCH_PACKAGE, BOARD_LIMIT, CLAIM_HOURS, CLAIM_STATUSES, CLONE_FLOOR, GATE_NAMES, GITHUB_SOURCE_ID, GRAMMAR_FILE, HOSTS_AT_ONCE, IMPORT_SOURCE_IDS, IssueApiError, MAP_SOURCE_ID, MUTATION_LANE, NECESSARY_GATES, ONTOLOGY_FOLDER, ONTOLOGY_REPOSITORY, OntologyReadError, PLACES_SHOWN, PROPERTY_PACKAGES, RECORD_SCHEMA_FILE, REPOSITORY_PAGES, RIGS_FILE, RULES_PAGE, SCOPE_MODULUS_LIMIT, SIZES, TARGET_LABEL, USAGE, USER_AGENT, actionComment, applyBoard, applyPlan, canonicalScope, checkMatches, checkOntology, claimCommandOf, claimEnd, claimFails, claimTimeOf, cloneGroups, cloneReport, compareTargets, conventionsVersion, decideClaim, edgesOf, fileUrl, filesToRead, findRoot, gateRepositoriesOf, gatesOf, githubIssueApi, githubRepositoryOf, hasFullScope, idPart, inScope, isEmptyPlan, isExpired, isKindIn, isLive, isPackagePath, isWorkflowPath, issueOfItem, issueText, kindOf, kindOfId, lineageOf, makeId, necessaryChecksOf, npmFactOf, npmLatestUrl, npmPackageId, npmPurl, pathOfId, planBoard, planWrite, politeFetch, publicText, readAtlas, readHomeFacts, readOntology, readScope, readTestGates, recordText, recordsFromAtlas, recordsFromHomes, relationOf, repositoriesOfPages, repositoryId, repositoryPageUrls, resultClaimsOf, rulesUrl, runCli, sameScope, scopeOf, scopeText, targetId, targetOfIssue, targetsOf, treeOf, treeUrl, withTestGates };
|
|
2130
|
+
|
|
2131
|
+
//# sourceMappingURL=index.mjs.map
|