@theholocron/holocron-plugin-github 5.0.0-alpha.54 → 5.0.0-alpha.540
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/README.md +33 -8
- package/dist/index.d.mts +351 -76
- package/dist/index.mjs +3920 -154
- package/package.json +30 -26
package/dist/index.mjs
CHANGED
|
@@ -1,48 +1,74 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
+
import { AuthError, MissingTokenError, ProviderApiError, areaLabelsForFiles, areaLabelsForTitle, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } from "@theholocron/cli";
|
|
2
3
|
import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
|
|
3
|
-
import { AuthError, createFeatureResolver } from "@theholocron/cli";
|
|
4
4
|
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
|
-
|
|
6
|
+
import { findRootSync } from "@theholocron/fs-utils";
|
|
7
|
+
import { ProviderApiError as ProviderApiError$1 } from "@theholocron/http-client";
|
|
8
|
+
import { errorMessage } from "@theholocron/misc-utils";
|
|
9
|
+
// src/auth.ts
|
|
10
|
+
/** Resolves the token for read-only GitHub access (`HOLOCRON_READ_TOKEN`, keyring key `github.read`). */
|
|
7
11
|
const resolveReadToken = createFeatureResolver({
|
|
8
12
|
envName: "HOLOCRON_READ_TOKEN",
|
|
9
13
|
keyringKey: "github.read"
|
|
10
14
|
});
|
|
15
|
+
/** Resolves the token for issue operations (`HOLOCRON_ISSUES_TOKEN`, keyring key `github.issues`). */
|
|
11
16
|
const resolveIssuesToken = createFeatureResolver({
|
|
12
17
|
envName: "HOLOCRON_ISSUES_TOKEN",
|
|
13
18
|
keyringKey: "github.issues"
|
|
14
19
|
});
|
|
20
|
+
/** Resolves the token for syncing repo files and settings (`HOLOCRON_SYNC_TOKEN`, keyring key `github.sync`). */
|
|
15
21
|
const resolveSyncToken = createFeatureResolver({
|
|
16
22
|
envName: "HOLOCRON_SYNC_TOKEN",
|
|
17
23
|
keyringKey: "github.sync"
|
|
18
24
|
});
|
|
25
|
+
/** Resolves the token for release operations (`HOLOCRON_RELEASE_TOKEN`, keyring key `github.release`). */
|
|
19
26
|
const resolveReleaseToken = createFeatureResolver({
|
|
20
27
|
envName: "HOLOCRON_RELEASE_TOKEN",
|
|
21
28
|
keyringKey: "github.release"
|
|
22
29
|
});
|
|
30
|
+
/** Resolves the repo-scoped admin token (`HOLOCRON_ADMIN_TOKEN`, keyring key `github.admin`). */
|
|
23
31
|
const resolveAdminToken = createFeatureResolver({
|
|
24
32
|
envName: "HOLOCRON_ADMIN_TOKEN",
|
|
25
33
|
keyringKey: "github.admin"
|
|
26
34
|
});
|
|
35
|
+
/** Resolves the org-level secrets token (`HOLOCRON_SECRETS_TOKEN`, keyring key `github.secrets`). */
|
|
36
|
+
const resolveSecretsToken = createFeatureResolver({
|
|
37
|
+
envName: "HOLOCRON_SECRETS_TOKEN",
|
|
38
|
+
keyringKey: "github.secrets"
|
|
39
|
+
});
|
|
40
|
+
/** Resolves the token for deployment operations (`HOLOCRON_DEPLOY_TOKEN`, keyring key `github.deploy`). */
|
|
27
41
|
const resolveDeployToken = createFeatureResolver({
|
|
28
42
|
envName: "HOLOCRON_DEPLOY_TOKEN",
|
|
29
43
|
keyringKey: "github.deploy"
|
|
30
44
|
});
|
|
45
|
+
/**
|
|
46
|
+
* Resolves the token for the user-sync files in the org's private config repo (`HOLOCRON_USER_SYNC_TOKEN`, keyring
|
|
47
|
+
* key `github.user-sync`).
|
|
48
|
+
*/
|
|
49
|
+
const resolveUserSyncToken = createFeatureResolver({
|
|
50
|
+
envName: "HOLOCRON_USER_SYNC_TOKEN",
|
|
51
|
+
keyringKey: "github.user-sync"
|
|
52
|
+
});
|
|
53
|
+
/** Resolves the org-level token (`HOLOCRON_ORG_TOKEN`, keyring key `github.org`). */
|
|
31
54
|
const resolveOrgToken = createFeatureResolver({
|
|
32
55
|
envName: "HOLOCRON_ORG_TOKEN",
|
|
33
56
|
keyringKey: "github.org"
|
|
34
57
|
});
|
|
35
|
-
|
|
36
|
-
|
|
58
|
+
// src/capabilities/ci.ts
|
|
59
|
+
/** The GitHub implementation of the `ci` capability, backed by GitHub Actions workflow runs. */
|
|
37
60
|
var GitHubCi = class {
|
|
38
61
|
client;
|
|
39
62
|
opts;
|
|
63
|
+
/** Capability key, always `"ci"`. */
|
|
40
64
|
key = "ci";
|
|
65
|
+
/** Provider name, always `"github"`. */
|
|
41
66
|
providerName = "github";
|
|
42
67
|
constructor(client, opts) {
|
|
43
68
|
this.client = client;
|
|
44
69
|
this.opts = opts;
|
|
45
70
|
}
|
|
71
|
+
/** Lists workflow runs for the repo, optionally filtered by branch, status and limit. */
|
|
46
72
|
async listRuns(filter) {
|
|
47
73
|
return (await this.client.workflows.listRuns(this.opts.repo, {
|
|
48
74
|
branch: filter?.branch,
|
|
@@ -50,6 +76,7 @@ var GitHubCi = class {
|
|
|
50
76
|
status: filter?.status
|
|
51
77
|
})).map((r) => this.mapRun(r));
|
|
52
78
|
}
|
|
79
|
+
/** Fetches one workflow run by id. */
|
|
53
80
|
async getRun(id) {
|
|
54
81
|
const raw = await this.client.workflows.getRun(this.opts.repo, id);
|
|
55
82
|
return this.mapRun(raw);
|
|
@@ -77,17 +104,20 @@ var GitHubCi = class {
|
|
|
77
104
|
}
|
|
78
105
|
}
|
|
79
106
|
};
|
|
80
|
-
|
|
81
|
-
|
|
107
|
+
// src/capabilities/environments.ts
|
|
108
|
+
/** The GitHub implementation of the `environments` capability, managing a repo's deployment environments. */
|
|
82
109
|
var GitHubEnvironments = class {
|
|
83
110
|
client;
|
|
84
111
|
opts;
|
|
112
|
+
/** Capability key, always `"environments"`. */
|
|
85
113
|
key = "environments";
|
|
114
|
+
/** Provider name, always `"github"`. */
|
|
86
115
|
providerName = "github";
|
|
87
116
|
constructor(client, opts) {
|
|
88
117
|
this.client = client;
|
|
89
118
|
this.opts = opts;
|
|
90
119
|
}
|
|
120
|
+
/** Lists the repo's environments with their wait timer, self-review rule and required reviewers. */
|
|
91
121
|
async listEnvironments() {
|
|
92
122
|
return (await this.client.environments.listEnvironments(this.opts.repo)).map((e) => ({
|
|
93
123
|
name: e.name,
|
|
@@ -96,6 +126,7 @@ var GitHubEnvironments = class {
|
|
|
96
126
|
reviewers: this.flattenReviewers(e.protection_rules)
|
|
97
127
|
}));
|
|
98
128
|
}
|
|
129
|
+
/** Creates or updates an environment, sending only the settings the given environment defines. */
|
|
99
130
|
async upsertEnvironment(env) {
|
|
100
131
|
const body = {};
|
|
101
132
|
if (env.waitTimer !== void 0) body.wait_timer = env.waitTimer;
|
|
@@ -106,6 +137,7 @@ var GitHubEnvironments = class {
|
|
|
106
137
|
}));
|
|
107
138
|
await this.client.environments.upsertEnvironment(this.opts.repo, env.name, body);
|
|
108
139
|
}
|
|
140
|
+
/** Deletes the named environment. */
|
|
109
141
|
async deleteEnvironment(name) {
|
|
110
142
|
await this.client.environments.deleteEnvironment(this.opts.repo, name);
|
|
111
143
|
}
|
|
@@ -119,16 +151,847 @@ var GitHubEnvironments = class {
|
|
|
119
151
|
}));
|
|
120
152
|
}
|
|
121
153
|
};
|
|
122
|
-
|
|
123
|
-
|
|
154
|
+
// src/capabilities/issue-field-setter.ts
|
|
155
|
+
/**
|
|
156
|
+
* Sets and clears one organization issue field (Priority, Effort, Start date, Target date) on an issue, for the
|
|
157
|
+
* `issues` capability's `create` and `update` and for `createPrioritySetter()`.
|
|
158
|
+
*
|
|
159
|
+
* The field list is read once per setter. A value is added with `POST`, which leaves the issue's other field values
|
|
160
|
+
* alone (`PUT` replaces all of them, and a multi-select value cannot be sent back with certainty); a value that differs
|
|
161
|
+
* is removed first. A missing field, a missing option or a refusal from GitHub (401, 403, 404, 422) comes back as a
|
|
162
|
+
* `note` for the caller's `dropped` list; a rate limit and every other failure are thrown. Spec
|
|
163
|
+
* `tech-github-issue-priority-field`, #2253, and `tool-work-commands`, #2429.
|
|
164
|
+
*
|
|
165
|
+
* Not verified against the live API: that Effort, Start date and Target date are written the way Priority is.
|
|
166
|
+
*/
|
|
167
|
+
/** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
|
|
168
|
+
function fieldRefusal(err) {
|
|
169
|
+
if (!(err instanceof ProviderApiError)) return void 0;
|
|
170
|
+
if (err.status === void 0 || ![
|
|
171
|
+
401,
|
|
172
|
+
403,
|
|
173
|
+
404,
|
|
174
|
+
422
|
|
175
|
+
].includes(err.status)) return void 0;
|
|
176
|
+
if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
|
|
177
|
+
return `GitHub refused: ${err.status}`;
|
|
178
|
+
}
|
|
179
|
+
const DATA_TYPE = {
|
|
180
|
+
select: "single_select",
|
|
181
|
+
date: "date"
|
|
182
|
+
};
|
|
183
|
+
/** Makes the setter for the issues of `repo` (`owner/name`); the organization's field list is read on first use and kept. */
|
|
184
|
+
function createFieldSetter(client, repo) {
|
|
185
|
+
const org = repo.split("/")[0];
|
|
186
|
+
let fields;
|
|
187
|
+
const listFields = () => fields ??= client.issueFields.list(org).then((list) => list, (err) => {
|
|
188
|
+
const why = fieldRefusal(err);
|
|
189
|
+
if (why === void 0) throw err;
|
|
190
|
+
return why;
|
|
191
|
+
});
|
|
192
|
+
const label = (target) => `${target.name.toLowerCase()} field`;
|
|
193
|
+
const find = async (target) => {
|
|
194
|
+
const list = await listFields();
|
|
195
|
+
if (typeof list === "string") return { note: `${label(target)} (${list})` };
|
|
196
|
+
const field = list.find((f) => f.name.toLowerCase() === target.name.toLowerCase() && f.data_type === DATA_TYPE[target.type]);
|
|
197
|
+
return field ? { field } : { note: `${label(target)} (${org} has no ${target.name} issue field)` };
|
|
198
|
+
};
|
|
199
|
+
const currentOf = async (number, field, target, flags) => {
|
|
200
|
+
if (flags.isNew) return void 0;
|
|
201
|
+
const found = (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
|
|
202
|
+
if (!found) return void 0;
|
|
203
|
+
return target.type === "date" ? String(found.value).slice(0, 10) : found.single_select_option?.name ?? String(found.value);
|
|
204
|
+
};
|
|
205
|
+
return {
|
|
206
|
+
async set(number, target, flags = {}) {
|
|
207
|
+
if (!target.value) return { changed: false };
|
|
208
|
+
const found = await find(target);
|
|
209
|
+
if ("note" in found) return {
|
|
210
|
+
changed: false,
|
|
211
|
+
note: found.note
|
|
212
|
+
};
|
|
213
|
+
const { field } = found;
|
|
214
|
+
let value = target.value;
|
|
215
|
+
if (target.type === "select") {
|
|
216
|
+
const option = field.options?.find((o) => o.name.toLowerCase() === value.toLowerCase());
|
|
217
|
+
if (!option) return {
|
|
218
|
+
changed: false,
|
|
219
|
+
note: `${label(target)} (no "${value}" option)`
|
|
220
|
+
};
|
|
221
|
+
value = option.name;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
const current = await currentOf(number, field, target, flags);
|
|
225
|
+
if (current?.toLowerCase() === value.toLowerCase()) return { changed: false };
|
|
226
|
+
if (flags.dryRun) return { changed: true };
|
|
227
|
+
if (current !== void 0) await client.issueFields.deleteValue(repo, number, field.id);
|
|
228
|
+
await client.issueFields.addValues(repo, number, [{
|
|
229
|
+
field_id: field.id,
|
|
230
|
+
value
|
|
231
|
+
}]);
|
|
232
|
+
return { changed: true };
|
|
233
|
+
} catch (err) {
|
|
234
|
+
const why = fieldRefusal(err);
|
|
235
|
+
if (why === void 0) throw err;
|
|
236
|
+
return {
|
|
237
|
+
changed: false,
|
|
238
|
+
note: `${label(target)} (${why})`
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
async clear(number, target, flags = {}) {
|
|
243
|
+
if (flags.isNew) return { changed: false };
|
|
244
|
+
const found = await find(target);
|
|
245
|
+
if ("note" in found) return {
|
|
246
|
+
changed: false,
|
|
247
|
+
note: found.note
|
|
248
|
+
};
|
|
249
|
+
try {
|
|
250
|
+
if (await currentOf(number, found.field, target, flags) === void 0) return { changed: false };
|
|
251
|
+
if (flags.dryRun) return { changed: true };
|
|
252
|
+
await client.issueFields.deleteValue(repo, number, found.field.id);
|
|
253
|
+
return { changed: true };
|
|
254
|
+
} catch (err) {
|
|
255
|
+
const why = fieldRefusal(err);
|
|
256
|
+
if (why === void 0) throw err;
|
|
257
|
+
return {
|
|
258
|
+
changed: false,
|
|
259
|
+
note: `${label(target)} (${why})`
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
// src/capabilities/issue-kind.ts
|
|
266
|
+
/** The Type name of each core kind; always known, whatever is declared. */
|
|
267
|
+
const CORE_TYPE_NAMES = {
|
|
268
|
+
bug: "Bug",
|
|
269
|
+
feature: "Feature",
|
|
270
|
+
task: "Task"
|
|
271
|
+
};
|
|
272
|
+
/** The kind each label names where there is no Type. */
|
|
273
|
+
const LABEL_KINDS = {
|
|
274
|
+
bug: "bug",
|
|
275
|
+
enhancement: "feature",
|
|
276
|
+
chore: "task"
|
|
277
|
+
};
|
|
278
|
+
/** The core three Types plus the declared ones (in the declaration's spelling); a core name wins over a declared one. */
|
|
279
|
+
function kindNames(declared) {
|
|
280
|
+
const names = new Map(Object.entries(CORE_TYPE_NAMES));
|
|
281
|
+
for (const { name } of declared ?? []) if (!names.has(name.toLowerCase())) names.set(name.toLowerCase(), name);
|
|
282
|
+
return {
|
|
283
|
+
nameOf: (kind) => names.get(kind) ?? kind.charAt(0).toUpperCase() + kind.slice(1),
|
|
284
|
+
kindOf: (typeName) => typeName ? typeName.toLowerCase() : void 0
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/** The names with nothing declared. */
|
|
288
|
+
const CORE_KIND_NAMES = kindNames(void 0);
|
|
289
|
+
/**
|
|
290
|
+
* The kind of an issue: its Type (a Type outside the core three is its lower-case name, so a migration does not lose an
|
|
291
|
+
* Epic), else the one kind its labels name (two different ones name none).
|
|
292
|
+
*/
|
|
293
|
+
function kindOfIssue(issue, names = CORE_KIND_NAMES) {
|
|
294
|
+
const typed = names.kindOf(issue.type?.name);
|
|
295
|
+
if (typed) return typed;
|
|
296
|
+
const named = new Set(issue.labels.flatMap((l) => LABEL_KINDS[l.name.toLowerCase()] ?? []));
|
|
297
|
+
return named.size === 1 ? [...named][0] : void 0;
|
|
298
|
+
}
|
|
299
|
+
/** Whether the issue's Type is already the kind's. */
|
|
300
|
+
function hasKindType(issue, kind, names = CORE_KIND_NAMES) {
|
|
301
|
+
return issue.type?.name?.toLowerCase() === names.nameOf(kind).toLowerCase();
|
|
302
|
+
}
|
|
303
|
+
/** Sets the Type of issue `number`; a refusal is returned as a `dropped` line, anything else (a rate limit) is thrown. */
|
|
304
|
+
async function writeKind(client, repo, number, kind, names = CORE_KIND_NAMES) {
|
|
305
|
+
const name = names.nameOf(kind);
|
|
306
|
+
try {
|
|
307
|
+
await client.issues.updateIssue(repo, number, { type: name });
|
|
308
|
+
return;
|
|
309
|
+
} catch (err) {
|
|
310
|
+
const why = fieldRefusal(err);
|
|
311
|
+
if (why === void 0) throw err;
|
|
312
|
+
return `kind ${name} (${why})`;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
// src/capabilities/issue-priority.ts
|
|
316
|
+
/** The Priority field's option for each level. */
|
|
317
|
+
const PRIORITY_OPTION_NAMES = {
|
|
318
|
+
urgent: "Urgent",
|
|
319
|
+
high: "High",
|
|
320
|
+
medium: "Medium",
|
|
321
|
+
low: "Low"
|
|
322
|
+
};
|
|
323
|
+
/** Makes the Priority setter for the issues of `repo` (`owner/name`). */
|
|
324
|
+
function createPrioritySetter(client, repo) {
|
|
325
|
+
const fields = createFieldSetter(client, repo);
|
|
326
|
+
return { set: (number, level, flags = {}) => !level || level === "none" ? Promise.resolve({ changed: false }) : fields.set(number, {
|
|
327
|
+
name: "Priority",
|
|
328
|
+
type: "select",
|
|
329
|
+
value: PRIORITY_OPTION_NAMES[level]
|
|
330
|
+
}, flags) };
|
|
331
|
+
}
|
|
332
|
+
// src/capabilities/issue-work-fields.ts
|
|
333
|
+
/** The Effort field's option for each effort. */
|
|
334
|
+
const EFFORT_NAMES = {
|
|
335
|
+
high: "High",
|
|
336
|
+
medium: "Medium",
|
|
337
|
+
low: "Low"
|
|
338
|
+
};
|
|
339
|
+
/** Makes the reader for the issues of `repo` (`owner/name`); the organization's field list is read once, on first use. */
|
|
340
|
+
function createWorkFieldReader(client, repo) {
|
|
341
|
+
const org = repo.split("/")[0];
|
|
342
|
+
let fields;
|
|
343
|
+
const listFields = () => fields ??= client.issueFields.list(org).catch((err) => {
|
|
344
|
+
if (fieldRefusal(err) === void 0) throw err;
|
|
345
|
+
return [];
|
|
346
|
+
});
|
|
347
|
+
const idOf = (list, name) => list.find((f) => f.name.toLowerCase() === name)?.id;
|
|
348
|
+
return { async read(number) {
|
|
349
|
+
const list = await listFields();
|
|
350
|
+
const effortId = idOf(list, "effort");
|
|
351
|
+
const startId = idOf(list, "start date");
|
|
352
|
+
const targetId = idOf(list, "target date");
|
|
353
|
+
if (effortId === void 0 && startId === void 0 && targetId === void 0) return {};
|
|
354
|
+
const values = await client.issueFields.values(repo, number).catch((err) => {
|
|
355
|
+
if (fieldRefusal(err) === void 0) throw err;
|
|
356
|
+
return [];
|
|
357
|
+
});
|
|
358
|
+
const valueOf = (id) => values.find((v) => v.issue_field_id === id);
|
|
359
|
+
const effort = (valueOf(effortId)?.single_select_option?.name ?? "").toLowerCase();
|
|
360
|
+
const start = valueOf(startId);
|
|
361
|
+
const target = valueOf(targetId);
|
|
362
|
+
return {
|
|
363
|
+
...effort in EFFORT_NAMES ? { effort } : {},
|
|
364
|
+
...start ? { startDate: String(start.value).slice(0, 10) } : {},
|
|
365
|
+
...target ? { targetDate: String(target.value).slice(0, 10) } : {}
|
|
366
|
+
};
|
|
367
|
+
} };
|
|
368
|
+
}
|
|
369
|
+
/** Sets the work fields the record carries; one it does not carry is not touched. */
|
|
370
|
+
async function writeWorkFields(fields, number, record, flags) {
|
|
371
|
+
const wanted = [
|
|
372
|
+
["effort", {
|
|
373
|
+
name: "Effort",
|
|
374
|
+
type: "select",
|
|
375
|
+
value: record.effort && EFFORT_NAMES[record.effort]
|
|
376
|
+
}],
|
|
377
|
+
["startDate", {
|
|
378
|
+
name: "Start date",
|
|
379
|
+
type: "date",
|
|
380
|
+
value: record.startDate
|
|
381
|
+
}],
|
|
382
|
+
["targetDate", {
|
|
383
|
+
name: "Target date",
|
|
384
|
+
type: "date",
|
|
385
|
+
value: record.targetDate
|
|
386
|
+
}]
|
|
387
|
+
];
|
|
388
|
+
const out = {
|
|
389
|
+
changed: [],
|
|
390
|
+
notes: []
|
|
391
|
+
};
|
|
392
|
+
for (const [label, target] of wanted) {
|
|
393
|
+
const result = await fields.set(number, target, flags);
|
|
394
|
+
if (result.note) out.notes.push(result.note);
|
|
395
|
+
else if (result.changed) out.changed.push(label);
|
|
396
|
+
}
|
|
397
|
+
return out;
|
|
398
|
+
}
|
|
399
|
+
// src/capabilities/issues-migration.ts
|
|
400
|
+
/**
|
|
401
|
+
* Export and import of GitHub issues for `holocron migrate`.
|
|
402
|
+
*
|
|
403
|
+
* GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
|
|
404
|
+
* lost quietly:
|
|
405
|
+
* - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
|
|
406
|
+
* - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
|
|
407
|
+
* author go in the text;
|
|
408
|
+
* - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
|
|
409
|
+
* - an assignee is not mapped (a Linear user is not a GitHub login).
|
|
410
|
+
* - the organization's `Priority` issue field is set from the priority (`issue-priority.ts`), beside the label.
|
|
411
|
+
* A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
|
|
412
|
+
*/
|
|
413
|
+
const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
|
|
414
|
+
const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
|
|
415
|
+
const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
|
|
416
|
+
issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
|
|
417
|
+
/** Splits `priority: high` labels from the rest. */
|
|
418
|
+
function splitLabels(names) {
|
|
419
|
+
let priority;
|
|
420
|
+
const labels = [];
|
|
421
|
+
for (const name of names) {
|
|
422
|
+
const match = PRIORITY_LABEL.exec(name);
|
|
423
|
+
if (match) priority = match[1].toLowerCase();
|
|
424
|
+
else labels.push(name);
|
|
425
|
+
}
|
|
426
|
+
return {
|
|
427
|
+
labels,
|
|
428
|
+
...priority ? { priority } : {}
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
function categoryOf(issue) {
|
|
432
|
+
if (issue.state === "closed") return "done";
|
|
433
|
+
const names = issue.labels.map((l) => l.name.toLowerCase());
|
|
434
|
+
if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
|
|
435
|
+
if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
|
|
436
|
+
return "open";
|
|
437
|
+
}
|
|
438
|
+
/** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
|
|
439
|
+
const EXPORT_CONCURRENCY = 4;
|
|
440
|
+
/** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
|
|
441
|
+
async function mapLimit(items, limit, fn) {
|
|
442
|
+
const results = new Array(items.length);
|
|
443
|
+
let next = 0;
|
|
444
|
+
const worker = async () => {
|
|
445
|
+
while (next < items.length) {
|
|
446
|
+
const at = next++;
|
|
447
|
+
results[at] = await fn(items[at]);
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
451
|
+
return results;
|
|
452
|
+
}
|
|
453
|
+
/** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
|
|
454
|
+
function explainSecondaryLimit(err) {
|
|
455
|
+
if (err instanceof ProviderApiError && (err.status === 403 || err.status === 429) && String(err.details).includes("secondary rate limit")) return /* @__PURE__ */ new Error("GitHub's secondary rate limit stopped the export. It limits bursts of requests, not the hourly quota, and nothing has been written. Wait a couple of minutes and run the command again.");
|
|
456
|
+
return err;
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Reads the issues `selector` names, with their comments, priority label, parent and blockers.
|
|
460
|
+
*
|
|
461
|
+
* With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
|
|
462
|
+
* list of keys is sorted by issue number (which rises with creation in one repository) before anything is fetched, then
|
|
463
|
+
* fetched a few at a time until enough are kept; a listing already carries `created_at`, so it is cut before the
|
|
464
|
+
* per-issue comment and link requests. `info.matched` receives how many the selection matched before the cut.
|
|
465
|
+
*/
|
|
466
|
+
async function exportIssues(client, repo, selector, info = {}, kinds = CORE_KIND_NAMES) {
|
|
467
|
+
return readIssues(client, repo, selector, info, kinds).catch((err) => {
|
|
468
|
+
throw explainSecondaryLimit(err);
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
async function readIssues(client, repo, selector, info, kinds) {
|
|
472
|
+
const [owner = "", name = ""] = repo.split("/", 2);
|
|
473
|
+
const since = selector.since ? Date.parse(selector.since) : void 0;
|
|
474
|
+
const survives = (i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since);
|
|
475
|
+
const { limit, order = "oldest" } = selector;
|
|
476
|
+
let issues;
|
|
477
|
+
if (selector.keys) {
|
|
478
|
+
const fetch = (k) => client.issues.getIssue(repo, parseNumber(k));
|
|
479
|
+
info.matched = selector.keys.length;
|
|
480
|
+
issues = limit === void 0 ? (await mapLimit(selector.keys, EXPORT_CONCURRENCY, fetch)).filter(survives) : await readKeysLimited({
|
|
481
|
+
keys: selector.keys,
|
|
482
|
+
order,
|
|
483
|
+
limit,
|
|
484
|
+
concurrency: EXPORT_CONCURRENCY,
|
|
485
|
+
fetch,
|
|
486
|
+
keep: survives
|
|
487
|
+
});
|
|
488
|
+
} else {
|
|
489
|
+
let raw;
|
|
490
|
+
if (selector.milestone) {
|
|
491
|
+
const milestone = await findMilestone(client, repo, selector.milestone);
|
|
492
|
+
if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
|
|
493
|
+
raw = await listAll(client, repo, { milestone: String(milestone.number) });
|
|
494
|
+
} else if (selector.all) raw = await listAll(client, repo, {});
|
|
495
|
+
else throw new Error("export needs keys, a milestone or all");
|
|
496
|
+
issues = raw.filter(survives);
|
|
497
|
+
info.matched = issues.length;
|
|
498
|
+
if (limit !== void 0) issues = pickByCreation(issues, (i) => i.created_at ?? i.updated_at, order, limit);
|
|
499
|
+
}
|
|
500
|
+
const work = createWorkFieldReader(client, repo);
|
|
501
|
+
const records = [];
|
|
502
|
+
for (const issue of issues) {
|
|
503
|
+
reportProgress(info.onProgress, records.length, issues.length);
|
|
504
|
+
const comments = await client.issues.listComments(repo, issue.number);
|
|
505
|
+
const links = (await client.graphql.query(LINK_QUERY, {
|
|
506
|
+
owner,
|
|
507
|
+
name,
|
|
508
|
+
number: issue.number
|
|
509
|
+
}).catch(() => void 0))?.repository.issue;
|
|
510
|
+
const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
|
|
511
|
+
const body = issue.body?.replace(MARKER, "").trimEnd();
|
|
512
|
+
const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
|
|
513
|
+
const kind = kindOfIssue(issue, kinds);
|
|
514
|
+
const workFields = await work.read(issue.number);
|
|
515
|
+
records.push({
|
|
516
|
+
key: `#${issue.number}`,
|
|
517
|
+
url: issue.html_url,
|
|
518
|
+
title: issue.title,
|
|
519
|
+
...body ? { body } : {},
|
|
520
|
+
statusCategory: categoryOf(issue),
|
|
521
|
+
closed: issue.state === "closed",
|
|
522
|
+
...priority ? { priority } : {},
|
|
523
|
+
labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
|
|
524
|
+
...kind ? { kind } : {},
|
|
525
|
+
...workFields,
|
|
526
|
+
...issue.assignee ? { assignee: {
|
|
527
|
+
id: issue.assignee.login,
|
|
528
|
+
displayName: issue.assignee.name ?? issue.assignee.login,
|
|
529
|
+
...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
|
|
530
|
+
} } : {},
|
|
531
|
+
...issue.milestone ? { milestone: issue.milestone.title } : {},
|
|
532
|
+
...links?.parent ? { parent: `#${links.parent.number}` } : {},
|
|
533
|
+
blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
|
|
534
|
+
comments: comments.map((c) => ({
|
|
535
|
+
...c.user ? { author: c.user.login } : {},
|
|
536
|
+
body: c.body,
|
|
537
|
+
createdAt: c.created_at
|
|
538
|
+
})),
|
|
539
|
+
createdAt: issue.created_at ?? issue.updated_at,
|
|
540
|
+
updatedAt: issue.updated_at,
|
|
541
|
+
...migratedFrom ? { migratedFrom } : {}
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
reportProgress(info.onProgress, records.length, issues.length);
|
|
545
|
+
return records;
|
|
546
|
+
}
|
|
547
|
+
/** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
|
|
548
|
+
async function importIssues(client, repo, records, options = {}, kinds = CORE_KIND_NAMES) {
|
|
549
|
+
const existing = /* @__PURE__ */ new Map();
|
|
550
|
+
for (const issue of await listAll(client, repo, {})) {
|
|
551
|
+
const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
|
|
552
|
+
if (url) existing.set(url, issue.number);
|
|
553
|
+
}
|
|
554
|
+
const priority = createPrioritySetter(client, repo);
|
|
555
|
+
const fields = createFieldSetter(client, repo);
|
|
556
|
+
const results = [];
|
|
557
|
+
const tick = () => reportProgress(options.onProgress, results.length, records.length);
|
|
558
|
+
for (const record of records) {
|
|
559
|
+
const found = existing.get(record.url);
|
|
560
|
+
if (found !== void 0) {
|
|
561
|
+
results.push({
|
|
562
|
+
source: record.key,
|
|
563
|
+
key: `#${found}`,
|
|
564
|
+
created: false,
|
|
565
|
+
dropped: []
|
|
566
|
+
});
|
|
567
|
+
tick();
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
const dropped = droppedFor(record);
|
|
571
|
+
if (options.dryRun) {
|
|
572
|
+
results.push({
|
|
573
|
+
source: record.key,
|
|
574
|
+
created: true,
|
|
575
|
+
dropped
|
|
576
|
+
});
|
|
577
|
+
tick();
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
const number = await createFromRecord(client, repo, record, options);
|
|
581
|
+
const field = await priority.set(number, record.priority, { isNew: true });
|
|
582
|
+
if (field.note) dropped.push(field.note);
|
|
583
|
+
dropped.push(...(await writeWorkFields(fields, number, record, { isNew: true })).notes);
|
|
584
|
+
const kindNote = record.kind ? await writeKind(client, repo, number, record.kind, kinds) : void 0;
|
|
585
|
+
if (kindNote) dropped.push(kindNote);
|
|
586
|
+
results.push({
|
|
587
|
+
source: record.key,
|
|
588
|
+
key: `#${number}`,
|
|
589
|
+
created: true,
|
|
590
|
+
dropped
|
|
591
|
+
});
|
|
592
|
+
tick();
|
|
593
|
+
}
|
|
594
|
+
return results;
|
|
595
|
+
}
|
|
596
|
+
/** What GitHub cannot hold of this record, for the report. */
|
|
597
|
+
function droppedFor(record) {
|
|
598
|
+
const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
|
|
599
|
+
if (record.assignee && !record.assignee.login) dropped.push("assignee (not mapped)");
|
|
600
|
+
if (record.parent) dropped.push("parent (not set on GitHub)");
|
|
601
|
+
if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
|
|
602
|
+
return dropped;
|
|
603
|
+
}
|
|
604
|
+
/** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
|
|
605
|
+
function labelsFor(record) {
|
|
606
|
+
return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
|
|
607
|
+
}
|
|
608
|
+
/** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
|
|
609
|
+
function renderComment(comment) {
|
|
610
|
+
return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
|
|
611
|
+
}
|
|
612
|
+
/** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
|
|
613
|
+
async function createFromRecord(client, repo, record, options) {
|
|
614
|
+
const milestoneName = options.milestone ?? record.milestone;
|
|
615
|
+
const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
|
|
616
|
+
const labels = labelsFor(record);
|
|
617
|
+
const created = await client.issues.createIssue(repo, {
|
|
618
|
+
title: record.title,
|
|
619
|
+
body: withProvenance(record),
|
|
620
|
+
...labels.length > 0 ? { labels } : {},
|
|
621
|
+
...milestone !== void 0 ? { milestone } : {},
|
|
622
|
+
...record.assignee?.login ? { assignees: [record.assignee.login] } : {}
|
|
623
|
+
});
|
|
624
|
+
for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
|
|
625
|
+
if (record.closed) await client.issues.updateIssue(repo, created.number, {
|
|
626
|
+
state: "closed",
|
|
627
|
+
state_reason: "completed"
|
|
628
|
+
});
|
|
629
|
+
return created.number;
|
|
630
|
+
}
|
|
631
|
+
/** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
|
|
632
|
+
function withProvenance(record) {
|
|
633
|
+
return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
|
|
634
|
+
}
|
|
635
|
+
function parseNumber(key) {
|
|
636
|
+
const n = key.trim().replace(/^.*#/, "");
|
|
637
|
+
if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
|
|
638
|
+
return parseInt(n, 10);
|
|
639
|
+
}
|
|
640
|
+
async function listAll(client, repo, extra) {
|
|
641
|
+
const all = [];
|
|
642
|
+
for (let page = 1;; page++) {
|
|
643
|
+
const batch = await client.issues.listIssues(repo, {
|
|
644
|
+
state: "all",
|
|
645
|
+
per_page: 100,
|
|
646
|
+
page,
|
|
647
|
+
...extra
|
|
648
|
+
});
|
|
649
|
+
all.push(...batch);
|
|
650
|
+
if (batch.length < 100) return all;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
async function findMilestone(client, repo, ref) {
|
|
654
|
+
return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
|
|
655
|
+
}
|
|
656
|
+
async function ensureMilestone(client, repo, title) {
|
|
657
|
+
return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
|
|
658
|
+
}
|
|
659
|
+
// src/capabilities/issues-sync.ts
|
|
660
|
+
const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
|
|
661
|
+
/** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
|
|
662
|
+
function isRateLimited(err) {
|
|
663
|
+
return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
|
|
664
|
+
}
|
|
665
|
+
const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
|
|
666
|
+
const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
|
|
667
|
+
/** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
|
|
668
|
+
async function syncIssues(client, repo, records, options = {}, kinds = CORE_KIND_NAMES) {
|
|
669
|
+
const existing = /* @__PURE__ */ new Map();
|
|
670
|
+
for (const issue of await listAll(client, repo, {})) {
|
|
671
|
+
const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
|
|
672
|
+
if (url) existing.set(url, issue);
|
|
673
|
+
}
|
|
674
|
+
const priority = createPrioritySetter(client, repo);
|
|
675
|
+
const fields = createFieldSetter(client, repo);
|
|
676
|
+
const results = [];
|
|
677
|
+
for (const record of records) try {
|
|
678
|
+
const found = existing.get(record.url);
|
|
679
|
+
results.push(found ? await update(client, repo, found, record, options, priority, fields, kinds) : await create(client, repo, record, options, priority, fields, kinds));
|
|
680
|
+
reportProgress(options.onProgress, results.length, records.length);
|
|
681
|
+
} catch (err) {
|
|
682
|
+
if (isRateLimited(err)) return results;
|
|
683
|
+
throw err;
|
|
684
|
+
}
|
|
685
|
+
return results;
|
|
686
|
+
}
|
|
687
|
+
async function create(client, repo, record, options, priority, fields, kinds) {
|
|
688
|
+
const dropped = droppedFor(record);
|
|
689
|
+
if (options.dryRun) return {
|
|
690
|
+
source: record.key,
|
|
691
|
+
created: true,
|
|
692
|
+
updated: false,
|
|
693
|
+
changes: [],
|
|
694
|
+
dropped
|
|
695
|
+
};
|
|
696
|
+
const number = await createFromRecord(client, repo, record, options);
|
|
697
|
+
const field = await priority.set(number, record.priority, { isNew: true });
|
|
698
|
+
if (field.note) dropped.push(field.note);
|
|
699
|
+
dropped.push(...(await writeWorkFields(fields, number, record, { isNew: true })).notes);
|
|
700
|
+
const kindNote = record.kind ? await writeKind(client, repo, number, record.kind, kinds) : void 0;
|
|
701
|
+
if (kindNote) dropped.push(kindNote);
|
|
702
|
+
return {
|
|
703
|
+
source: record.key,
|
|
704
|
+
key: `#${number}`,
|
|
705
|
+
created: true,
|
|
706
|
+
updated: false,
|
|
707
|
+
changes: [],
|
|
708
|
+
dropped
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async function update(client, repo, issue, record, options, priority, fields, kinds) {
|
|
712
|
+
const patch = {};
|
|
713
|
+
const changes = [];
|
|
714
|
+
if (issue.title !== record.title) {
|
|
715
|
+
patch.title = record.title;
|
|
716
|
+
changes.push("title");
|
|
717
|
+
}
|
|
718
|
+
const body = withProvenance(record);
|
|
719
|
+
if (normalize(issue.body) !== normalize(body)) {
|
|
720
|
+
patch.body = body;
|
|
721
|
+
changes.push("description");
|
|
722
|
+
}
|
|
723
|
+
if (issue.state === "closed" !== record.closed) {
|
|
724
|
+
patch.state = record.closed ? "closed" : "open";
|
|
725
|
+
if (record.closed) patch.state_reason = "completed";
|
|
726
|
+
changes.push("state");
|
|
727
|
+
}
|
|
728
|
+
const current = issue.labels.map((l) => l.name);
|
|
729
|
+
const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
|
|
730
|
+
if (sorted(finalLabels) !== sorted(current)) {
|
|
731
|
+
patch.labels = finalLabels;
|
|
732
|
+
changes.push("labels");
|
|
733
|
+
}
|
|
734
|
+
const login = record.assignee?.login;
|
|
735
|
+
if (login && issue.assignee?.login.toLowerCase() !== login.toLowerCase()) {
|
|
736
|
+
patch.assignees = [login];
|
|
737
|
+
changes.push("assignee");
|
|
738
|
+
}
|
|
739
|
+
const field = await priority.set(issue.number, record.priority, { dryRun: options.dryRun });
|
|
740
|
+
if (field.changed) changes.push("priority field");
|
|
741
|
+
const work = await writeWorkFields(fields, issue.number, record, { dryRun: options.dryRun });
|
|
742
|
+
changes.push(...work.changed);
|
|
743
|
+
const kindWrong = record.kind !== void 0 && !hasKindType(issue, record.kind, kinds);
|
|
744
|
+
if (kindWrong) changes.push("kind");
|
|
745
|
+
const kindNote = kindWrong && !options.dryRun ? await writeKind(client, repo, issue.number, record.kind, kinds) : void 0;
|
|
746
|
+
const comments = await client.issues.listComments(repo, issue.number);
|
|
747
|
+
const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
|
|
748
|
+
const missing = record.comments.filter((c) => !seen.has(c.createdAt));
|
|
749
|
+
if (missing.length > 0) changes.push("comments");
|
|
750
|
+
if (!options.dryRun) {
|
|
751
|
+
if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
|
|
752
|
+
for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
|
|
753
|
+
}
|
|
754
|
+
return {
|
|
755
|
+
source: record.key,
|
|
756
|
+
key: `#${issue.number}`,
|
|
757
|
+
created: false,
|
|
758
|
+
updated: changes.length > 0,
|
|
759
|
+
changes,
|
|
760
|
+
dropped: [
|
|
761
|
+
...droppedFor(record),
|
|
762
|
+
...field.note ? [field.note] : [],
|
|
763
|
+
...work.notes,
|
|
764
|
+
...kindNote ? [kindNote] : []
|
|
765
|
+
]
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
// src/capabilities/issues-update.ts
|
|
769
|
+
/** Runs one step; a refusal or a bad key is a `dropped` line, anything else (a rate limit) is thrown. */
|
|
770
|
+
async function guarded(what, out, step) {
|
|
771
|
+
try {
|
|
772
|
+
await step();
|
|
773
|
+
} catch (err) {
|
|
774
|
+
const why = fieldRefusal(err);
|
|
775
|
+
if (why !== void 0) out.dropped.push(`${what} (${why})`);
|
|
776
|
+
else if (!(err instanceof ProviderApiError)) out.dropped.push(`${what} (${err.message})`);
|
|
777
|
+
else throw err;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
const CLEAR_FIELD = {
|
|
781
|
+
priority: {
|
|
782
|
+
name: "Priority",
|
|
783
|
+
type: "select"
|
|
784
|
+
},
|
|
785
|
+
effort: {
|
|
786
|
+
name: "Effort",
|
|
787
|
+
type: "select"
|
|
788
|
+
},
|
|
789
|
+
startDate: {
|
|
790
|
+
name: "Start date",
|
|
791
|
+
type: "date"
|
|
792
|
+
},
|
|
793
|
+
targetDate: {
|
|
794
|
+
name: "Target date",
|
|
795
|
+
type: "date"
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
/**
|
|
799
|
+
* Writes the {@link IssueFields} of an issue, and clears and unblocks as `clear` and `unblock` ask. `issue` is the issue
|
|
800
|
+
* as it is now (its numeric id and Type); `isNew` says it was just made, so nothing is read to compare.
|
|
801
|
+
*/
|
|
802
|
+
async function applyIssueFields(ctx, issue, input, isNew) {
|
|
803
|
+
const { client, repo } = ctx;
|
|
804
|
+
const fields = ctx.fields ??= createFieldSetter(client, repo);
|
|
805
|
+
const out = {
|
|
806
|
+
changed: [],
|
|
807
|
+
dropped: []
|
|
808
|
+
};
|
|
809
|
+
const flags = { isNew };
|
|
810
|
+
const clear = new Set(input.clear ?? []);
|
|
811
|
+
if (input.kind) {
|
|
812
|
+
const name = ctx.kinds.nameOf(input.kind);
|
|
813
|
+
if (issue.type?.name?.toLowerCase() !== name.toLowerCase()) await guarded(`kind ${name}`, out, async () => {
|
|
814
|
+
await client.issues.updateIssue(repo, issue.number, { type: name });
|
|
815
|
+
out.changed.push(`kind: ${name}`);
|
|
816
|
+
});
|
|
817
|
+
} else if (clear.has("kind") && issue.type) await guarded("kind", out, async () => {
|
|
818
|
+
await client.issues.updateIssue(repo, issue.number, { type: null });
|
|
819
|
+
out.changed.push("kind cleared");
|
|
820
|
+
});
|
|
821
|
+
const values = [
|
|
822
|
+
[
|
|
823
|
+
"priority",
|
|
824
|
+
"Priority",
|
|
825
|
+
"select",
|
|
826
|
+
input.priority && input.priority !== "none" ? PRIORITY_OPTION_NAMES[input.priority] : void 0
|
|
827
|
+
],
|
|
828
|
+
[
|
|
829
|
+
"effort",
|
|
830
|
+
"Effort",
|
|
831
|
+
"select",
|
|
832
|
+
input.effort ? EFFORT_NAMES[input.effort] : void 0
|
|
833
|
+
],
|
|
834
|
+
[
|
|
835
|
+
"startDate",
|
|
836
|
+
"Start date",
|
|
837
|
+
"date",
|
|
838
|
+
input.startDate
|
|
839
|
+
],
|
|
840
|
+
[
|
|
841
|
+
"targetDate",
|
|
842
|
+
"Target date",
|
|
843
|
+
"date",
|
|
844
|
+
input.targetDate
|
|
845
|
+
]
|
|
846
|
+
];
|
|
847
|
+
for (const [label, name, type, value] of values) {
|
|
848
|
+
if (!value) continue;
|
|
849
|
+
const result = await fields.set(issue.number, {
|
|
850
|
+
name,
|
|
851
|
+
type,
|
|
852
|
+
value
|
|
853
|
+
}, flags);
|
|
854
|
+
if (result.note) out.dropped.push(result.note);
|
|
855
|
+
else if (result.changed) out.changed.push(`${label}: ${value}`);
|
|
856
|
+
}
|
|
857
|
+
for (const key of clear) {
|
|
858
|
+
const target = CLEAR_FIELD[key];
|
|
859
|
+
if (!target) continue;
|
|
860
|
+
const result = await fields.clear(issue.number, target, flags);
|
|
861
|
+
if (result.note) out.dropped.push(result.note);
|
|
862
|
+
else if (result.changed) out.changed.push(`${key} cleared`);
|
|
863
|
+
}
|
|
864
|
+
if (input.parent) {
|
|
865
|
+
const parentKey = input.parent;
|
|
866
|
+
await guarded(`parent ${parentKey}`, out, async () => {
|
|
867
|
+
const parentNumber = ctx.parseKey(parentKey);
|
|
868
|
+
const current = isNew ? null : await client.issues.getParent(repo, issue.number);
|
|
869
|
+
if (current?.number === parentNumber) return;
|
|
870
|
+
await client.issues.addSubIssue(repo, parentNumber, issue.id, current !== null);
|
|
871
|
+
out.changed.push(`parent: ${parentKey}`);
|
|
872
|
+
});
|
|
873
|
+
} else if (clear.has("parent") && !isNew) await guarded("parent", out, async () => {
|
|
874
|
+
const current = await client.issues.getParent(repo, issue.number);
|
|
875
|
+
if (!current) return;
|
|
876
|
+
await client.issues.removeSubIssue(repo, current.number, issue.id);
|
|
877
|
+
out.changed.push("parent cleared");
|
|
878
|
+
});
|
|
879
|
+
const adds = input.blockedBy ?? [];
|
|
880
|
+
const removes = input.unblock ?? [];
|
|
881
|
+
if (adds.length > 0 || removes.length > 0) {
|
|
882
|
+
let blockers;
|
|
883
|
+
const current = async () => blockers ??= isNew ? [] : await client.issues.listBlockedBy(repo, issue.number);
|
|
884
|
+
for (const key of adds) await guarded(`blocked by ${key}`, out, async () => {
|
|
885
|
+
const number = ctx.parseKey(key);
|
|
886
|
+
if ((await current()).some((b) => b.number === number)) return;
|
|
887
|
+
const blocker = await client.issues.getIssue(repo, number);
|
|
888
|
+
await client.issues.addBlockedBy(repo, issue.number, blocker.id);
|
|
889
|
+
out.changed.push(`blocked by: ${key}`);
|
|
890
|
+
});
|
|
891
|
+
for (const key of removes) await guarded(`unblock ${key}`, out, async () => {
|
|
892
|
+
const number = ctx.parseKey(key);
|
|
893
|
+
const blocker = (await current()).find((b) => b.number === number);
|
|
894
|
+
if (!blocker) return;
|
|
895
|
+
await client.issues.removeBlockedBy(repo, issue.number, blocker.id);
|
|
896
|
+
out.changed.push(`unblocked: ${key}`);
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
return out;
|
|
900
|
+
}
|
|
901
|
+
const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
|
|
902
|
+
/** Changes an issue to match the patch; whatever is already as asked is not written. */
|
|
903
|
+
async function updateGitHubIssue(ctx, key, patch) {
|
|
904
|
+
const { client, repo } = ctx;
|
|
905
|
+
const number = ctx.parseKey(key);
|
|
906
|
+
const issue = await client.issues.getIssue(repo, number);
|
|
907
|
+
const changed = [];
|
|
908
|
+
const clear = new Set(patch.clear ?? []);
|
|
909
|
+
const body = {};
|
|
910
|
+
if (patch.title !== void 0 && patch.title !== issue.title) {
|
|
911
|
+
body.title = patch.title;
|
|
912
|
+
changed.push("title");
|
|
913
|
+
}
|
|
914
|
+
if (patch.body !== void 0 && patch.body !== (issue.body ?? "")) {
|
|
915
|
+
body.body = patch.body;
|
|
916
|
+
changed.push("body");
|
|
917
|
+
}
|
|
918
|
+
if (patch.state && patch.state !== issue.state) {
|
|
919
|
+
body.state = patch.state;
|
|
920
|
+
if (patch.state === "closed") body.state_reason = patch.stateReason ?? "completed";
|
|
921
|
+
changed.push(`state: ${patch.state}`);
|
|
922
|
+
}
|
|
923
|
+
const have = (issue.assignees ?? (issue.assignee ? [issue.assignee] : [])).map((a) => a.login);
|
|
924
|
+
if (patch.assignees?.length) {
|
|
925
|
+
const isMe = (a) => /^@?me$/i.test(a);
|
|
926
|
+
const me = patch.assignees.some(isMe) ? await ctx.myLogin() : void 0;
|
|
927
|
+
const want = [...new Set(patch.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
|
|
928
|
+
if (!sameSet(want.map((a) => a.toLowerCase()), have.map((a) => a.toLowerCase()))) {
|
|
929
|
+
body.assignees = want;
|
|
930
|
+
changed.push(`assignees: ${want.join(", ")}`);
|
|
931
|
+
}
|
|
932
|
+
} else if (clear.has("assignees") && have.length > 0) {
|
|
933
|
+
body.assignees = [];
|
|
934
|
+
changed.push("assignees cleared");
|
|
935
|
+
}
|
|
936
|
+
if (patch.milestone) {
|
|
937
|
+
const milestone = await ctx.resolveMilestone(patch.milestone);
|
|
938
|
+
if (issue.milestone?.number !== milestone) {
|
|
939
|
+
body.milestone = milestone;
|
|
940
|
+
changed.push(`milestone: ${patch.milestone}`);
|
|
941
|
+
}
|
|
942
|
+
} else if (clear.has("milestone") && issue.milestone) {
|
|
943
|
+
body.milestone = null;
|
|
944
|
+
changed.push("milestone cleared");
|
|
945
|
+
}
|
|
946
|
+
if (Object.keys(body).length > 0) await client.issues.updateIssue(repo, number, body);
|
|
947
|
+
const labels = new Set(issue.labels.map((l) => l.name.toLowerCase()));
|
|
948
|
+
const add = [...new Set(patch.addLabels ?? [])].filter((l) => !labels.has(l.toLowerCase()));
|
|
949
|
+
if (add.length > 0) {
|
|
950
|
+
await client.issues.addLabels(repo, number, add);
|
|
951
|
+
changed.push(`labels added: ${add.join(", ")}`);
|
|
952
|
+
}
|
|
953
|
+
for (const label of new Set(patch.removeLabels ?? [])) {
|
|
954
|
+
if (!labels.has(label.toLowerCase())) continue;
|
|
955
|
+
const exact = issue.labels.find((l) => l.name.toLowerCase() === label.toLowerCase()).name;
|
|
956
|
+
await client.issues.removeLabel(repo, number, exact);
|
|
957
|
+
changed.push(`label removed: ${exact}`);
|
|
958
|
+
}
|
|
959
|
+
const fields = await applyIssueFields(ctx, issue, patch, false);
|
|
960
|
+
const all = [...changed, ...fields.changed];
|
|
961
|
+
return {
|
|
962
|
+
key: `#${number}`,
|
|
963
|
+
changed: all,
|
|
964
|
+
...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
// src/capabilities/issues.ts
|
|
968
|
+
/** Issues read per request when `search` has a `text`; GitHub's largest page. */
|
|
969
|
+
const TEXT_PAGE_SIZE = 100;
|
|
970
|
+
/** Pages `search` reads for a `text` before it stops (the 2000 most recently updated issues). */
|
|
971
|
+
const TEXT_MAX_PAGES = 20;
|
|
972
|
+
/** A Type as the capability reports it: GitHub's `null`s are left out. */
|
|
973
|
+
function toTypeInfo(t) {
|
|
974
|
+
return {
|
|
975
|
+
id: t.id,
|
|
976
|
+
name: t.name,
|
|
977
|
+
...t.description ? { description: t.description } : {},
|
|
978
|
+
...t.color ? { color: t.color } : {},
|
|
979
|
+
enabled: t.is_enabled
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
/** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
|
|
124
983
|
var GitHubIssues = class {
|
|
125
984
|
client;
|
|
985
|
+
/** Capability key, always `"issues"`. */
|
|
126
986
|
key = "issues";
|
|
987
|
+
/** Provider name, always `"github"`. */
|
|
127
988
|
providerName = "github";
|
|
128
989
|
owner;
|
|
129
990
|
repoName;
|
|
130
991
|
repo;
|
|
131
992
|
labels;
|
|
993
|
+
kinds;
|
|
994
|
+
orgClient;
|
|
132
995
|
constructor(client, opts) {
|
|
133
996
|
this.client = client;
|
|
134
997
|
const [owner = "", repoName = ""] = opts.repo.split("/", 2);
|
|
@@ -136,6 +999,8 @@ var GitHubIssues = class {
|
|
|
136
999
|
this.repoName = repoName;
|
|
137
1000
|
this.repo = opts.repo;
|
|
138
1001
|
this.labels = opts.labels;
|
|
1002
|
+
this.kinds = kindNames(opts.issueTypes);
|
|
1003
|
+
this.orgClient = opts.orgClient;
|
|
139
1004
|
}
|
|
140
1005
|
async getMyself() {
|
|
141
1006
|
const raw = await this.client.user.getCurrentUser();
|
|
@@ -145,7 +1010,18 @@ var GitHubIssues = class {
|
|
|
145
1010
|
...raw.email ? { emailAddress: raw.email } : {}
|
|
146
1011
|
};
|
|
147
1012
|
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Searches the repo's issues, newest update first, leaving out pull requests.
|
|
1015
|
+
*
|
|
1016
|
+
* With `filter.text`, the issues are paged (newest update first, 100 a page, at most 20 pages) and compared
|
|
1017
|
+
* client-side, without regard to case, until `limit` matches are found or the issues run out. GitHub's issue
|
|
1018
|
+
* search (`GET /search/issues`) is deliberately not used: it indexes the words of a body, so punctuation and an
|
|
1019
|
+
* HTML comment such as `<!-- holocron:idea notes/a.md -->` cannot be relied on to match, it is limited to 30
|
|
1020
|
+
* requests a minute and it is eventually consistent (an issue made a moment ago may be missing). Paging has none
|
|
1021
|
+
* of those limits, at the cost of reading up to 20 pages of a very large repository.
|
|
1022
|
+
*/
|
|
148
1023
|
async search(filter) {
|
|
1024
|
+
if (filter.text) return this.searchText(filter, filter.text);
|
|
149
1025
|
const params = {
|
|
150
1026
|
state: filter.openOnly ? "open" : "all",
|
|
151
1027
|
sort: "updated",
|
|
@@ -164,17 +1040,71 @@ var GitHubIssues = class {
|
|
|
164
1040
|
assignee: params.assignee
|
|
165
1041
|
})).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
|
|
166
1042
|
}
|
|
1043
|
+
async searchText(filter, text) {
|
|
1044
|
+
const needle = text.toLowerCase();
|
|
1045
|
+
const limit = filter.limit ?? 50;
|
|
1046
|
+
const assignee = filter.assignee === "currentUser" ? (await this.getMyself()).id : filter.assignee || void 0;
|
|
1047
|
+
const found = [];
|
|
1048
|
+
for (let page = 1; page <= TEXT_MAX_PAGES; page++) {
|
|
1049
|
+
const raw = await this.client.issues.listIssues(this.repo, {
|
|
1050
|
+
state: filter.openOnly ? "open" : "all",
|
|
1051
|
+
sort: "updated",
|
|
1052
|
+
direction: "desc",
|
|
1053
|
+
per_page: TEXT_PAGE_SIZE,
|
|
1054
|
+
page,
|
|
1055
|
+
filter: "all",
|
|
1056
|
+
...assignee ? { assignee } : {}
|
|
1057
|
+
});
|
|
1058
|
+
for (const issue of raw) {
|
|
1059
|
+
if (issue.pull_request) continue;
|
|
1060
|
+
if (`${issue.title}\n${issue.body ?? ""}`.toLowerCase().includes(needle)) {
|
|
1061
|
+
found.push(this.mapIssue(issue));
|
|
1062
|
+
if (found.length >= limit) return found;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
if (raw.length < TEXT_PAGE_SIZE) break;
|
|
1066
|
+
}
|
|
1067
|
+
return found;
|
|
1068
|
+
}
|
|
1069
|
+
/** Fetches one issue by its key. */
|
|
167
1070
|
async get(key) {
|
|
168
1071
|
const number = parseIssueNumber(key, this.owner, this.repoName);
|
|
169
1072
|
const raw = await this.client.issues.getIssue(this.repo, number);
|
|
170
1073
|
return this.mapIssue(raw);
|
|
171
1074
|
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. Type, Priority,
|
|
1077
|
+
* Effort, the dates, the parent and the blockers are set after the issue exists; what GitHub refuses of them comes
|
|
1078
|
+
* back in `dropped`, never as a failure, because the issue is made by then and its key must not be lost.
|
|
1079
|
+
*/
|
|
172
1080
|
async create(input) {
|
|
173
1081
|
const body = { title: input.summary };
|
|
1082
|
+
if (input.assignees?.length) {
|
|
1083
|
+
const isMe = (a) => /^@?me$/i.test(a);
|
|
1084
|
+
const me = input.assignees.some(isMe) ? (await this.getMyself()).id : void 0;
|
|
1085
|
+
body.assignees = [...new Set(input.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
|
|
1086
|
+
}
|
|
174
1087
|
if (input.body) body.body = input.body;
|
|
175
1088
|
if (input.labels?.length) body.labels = input.labels;
|
|
176
1089
|
if (input.milestone) body.milestone = await this.resolveMilestone(input.milestone);
|
|
177
|
-
|
|
1090
|
+
const raw = await this.client.issues.createIssue(this.repo, body);
|
|
1091
|
+
const key = `#${raw.number}`;
|
|
1092
|
+
const fields = await applyIssueFields(this.fieldContext(), raw, input, true).catch((err) => ({
|
|
1093
|
+
changed: [],
|
|
1094
|
+
dropped: [`fields (not set: ${err.message})`]
|
|
1095
|
+
}));
|
|
1096
|
+
return {
|
|
1097
|
+
key,
|
|
1098
|
+
...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
/** Changes an issue; see {@link updateGitHubIssue}. */
|
|
1102
|
+
update(key, patch) {
|
|
1103
|
+
return updateGitHubIssue({
|
|
1104
|
+
...this.fieldContext(),
|
|
1105
|
+
myLogin: async () => (await this.getMyself()).id,
|
|
1106
|
+
resolveMilestone: (ref) => this.resolveMilestone(ref)
|
|
1107
|
+
}, key, patch);
|
|
178
1108
|
}
|
|
179
1109
|
async transition(key, slot) {
|
|
180
1110
|
const number = parseIssueNumber(key, this.owner, this.repoName);
|
|
@@ -216,10 +1146,12 @@ var GitHubIssues = class {
|
|
|
216
1146
|
via: `label set to ${targetLabel}`
|
|
217
1147
|
};
|
|
218
1148
|
}
|
|
1149
|
+
/** Adds a comment to the issue with the given key. */
|
|
219
1150
|
async comment(key, body) {
|
|
220
1151
|
const number = parseIssueNumber(key, this.owner, this.repoName);
|
|
221
1152
|
await this.client.issues.createComment(this.repo, number, body);
|
|
222
1153
|
}
|
|
1154
|
+
/** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
|
|
223
1155
|
async doctor() {
|
|
224
1156
|
const me = await this.getMyself();
|
|
225
1157
|
const repo = await this.client.repos.getRepo(this.repo);
|
|
@@ -288,6 +1220,58 @@ var GitHubIssues = class {
|
|
|
288
1220
|
lifecycle
|
|
289
1221
|
};
|
|
290
1222
|
}
|
|
1223
|
+
/** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
|
|
1224
|
+
export(selector, info) {
|
|
1225
|
+
return exportIssues(this.client, this.repo, selector, info, this.kinds);
|
|
1226
|
+
}
|
|
1227
|
+
/** Makes the records as issues; one already made by an earlier run is skipped. */
|
|
1228
|
+
import(records, options) {
|
|
1229
|
+
return importIssues(this.client, this.repo, records, options, this.kinds);
|
|
1230
|
+
}
|
|
1231
|
+
/** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
|
|
1232
|
+
sync(records, options) {
|
|
1233
|
+
return syncIssues(this.client, this.repo, records, options, this.kinds);
|
|
1234
|
+
}
|
|
1235
|
+
async listTypes() {
|
|
1236
|
+
const client = this.orgClient?.();
|
|
1237
|
+
return client ? (await client.issueTypes.list(this.owner)).map(toTypeInfo) : void 0;
|
|
1238
|
+
}
|
|
1239
|
+
async createType(type) {
|
|
1240
|
+
const client = this.orgClient?.();
|
|
1241
|
+
if (!client) throw new Error("no organization token (HOLOCRON_ORG_TOKEN) to make an issue Type with");
|
|
1242
|
+
return toTypeInfo(await client.issueTypes.create(this.owner, {
|
|
1243
|
+
name: type.name,
|
|
1244
|
+
is_enabled: type.enabled ?? true,
|
|
1245
|
+
...type.description !== void 0 ? { description: type.description } : {},
|
|
1246
|
+
...type.color !== void 0 ? { color: type.color } : {}
|
|
1247
|
+
}));
|
|
1248
|
+
}
|
|
1249
|
+
async updateType(id, patch) {
|
|
1250
|
+
const client = this.orgClient?.();
|
|
1251
|
+
if (!client) throw new Error("no organization token (HOLOCRON_ORG_TOKEN) to change an issue Type with");
|
|
1252
|
+
const current = (await client.issueTypes.list(this.owner)).find((t) => String(t.id) === String(id));
|
|
1253
|
+
if (!current) throw new Error(`the organization has no issue Type with id ${id}`);
|
|
1254
|
+
const description = patch.description ?? current.description;
|
|
1255
|
+
const color = patch.color ?? current.color;
|
|
1256
|
+
await client.issueTypes.update(this.owner, current.id, {
|
|
1257
|
+
name: current.name,
|
|
1258
|
+
is_enabled: current.is_enabled,
|
|
1259
|
+
...description != null ? { description } : {},
|
|
1260
|
+
...color != null ? { color } : {}
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
fieldSetter;
|
|
1264
|
+
/** What the field writers need; the setter is shared so the organization's field list is read once. */
|
|
1265
|
+
fieldContext() {
|
|
1266
|
+
this.fieldSetter ??= createFieldSetter(this.client, this.repo);
|
|
1267
|
+
return {
|
|
1268
|
+
client: this.client,
|
|
1269
|
+
repo: this.repo,
|
|
1270
|
+
parseKey: (k) => parseIssueNumber(k, this.owner, this.repoName),
|
|
1271
|
+
fields: this.fieldSetter,
|
|
1272
|
+
kinds: this.kinds
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
291
1275
|
async resolveMilestone(ref) {
|
|
292
1276
|
if (/^\d+$/.test(ref)) return parseInt(ref, 10);
|
|
293
1277
|
const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
|
|
@@ -337,127 +1321,1434 @@ function parseIssueNumber(key, owner, repoName) {
|
|
|
337
1321
|
if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
|
|
338
1322
|
return parseInt(num, 10);
|
|
339
1323
|
}
|
|
340
|
-
//#endregion
|
|
341
|
-
//#region src/sodium.ts
|
|
342
1324
|
/**
|
|
343
|
-
*
|
|
344
|
-
*
|
|
345
|
-
* GitHub stores Actions / Codespaces / Dependabot secrets encrypted
|
|
346
|
-
* with a curve25519 public key (returned by the `/actions/secrets/public-key`
|
|
347
|
-
* endpoint). Callers fetch that key, encrypt the plaintext value with
|
|
348
|
-
* `crypto_box_seal`, then PUT the base64-encoded ciphertext + `key_id`.
|
|
349
|
-
*
|
|
350
|
-
* Reference: https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
|
|
351
|
-
*
|
|
352
|
-
* **Why createRequire?** `libsodium-wrappers@0.7.x` ships a broken
|
|
353
|
-
* ESM bundle — the `dist/modules-esm/libsodium-wrappers.mjs` entry
|
|
354
|
-
* imports a sibling `libsodium.mjs` that isn't included in the npm
|
|
355
|
-
* tarball. Native `import` against the package therefore fails.
|
|
356
|
-
* `createRequire` routes through Node's CJS resolver, which honors
|
|
357
|
-
* the `"require"` condition in the package's exports map and loads
|
|
358
|
-
* the self-contained CJS bundle instead. Same API, working module.
|
|
1325
|
+
* One issue's closing pull requests and the aggregate check on each one's newest commit. It is its own small query,
|
|
1326
|
+
* never part of the board's items query: nested under `items(first: 100)` it multiplies past GitHub's resource limit.
|
|
359
1327
|
*/
|
|
360
|
-
const
|
|
1328
|
+
const CLOSING_QUERY = `query($id: ID!) { node(id: $id) { ... on Issue {
|
|
1329
|
+
closedByPullRequestsReferences(first: 5, includeClosedPrs: true) { nodes {
|
|
1330
|
+
number state isDraft repository { nameWithOwner }
|
|
1331
|
+
commits(last: 1) { nodes { commit { checkSuites(first: 30) { nodes {
|
|
1332
|
+
checkRuns(first: 5, filterBy: { checkName: "ci / Required checks" }) { nodes { databaseId status conclusion startedAt } }
|
|
1333
|
+
} } } } }
|
|
1334
|
+
} }
|
|
1335
|
+
} } }`;
|
|
1336
|
+
const FAILED$1 = /* @__PURE__ */ new Set([
|
|
1337
|
+
"FAILURE",
|
|
1338
|
+
"TIMED_OUT",
|
|
1339
|
+
"STARTUP_FAILURE",
|
|
1340
|
+
"ACTION_REQUIRED",
|
|
1341
|
+
"STALE"
|
|
1342
|
+
]);
|
|
361
1343
|
/**
|
|
362
|
-
*
|
|
363
|
-
*
|
|
1344
|
+
* The state of the aggregate check from the runs of that name on one commit. Only the newest run counts (latest
|
|
1345
|
+
* `startedAt`, then id), so a cancelled first batch or a re-run that went green does not hold the verdict red. A run
|
|
1346
|
+
* that is not finished, or that was cancelled, is `pending`; one with no verdict (neutral, skipped) or none posted is `none`.
|
|
364
1347
|
*/
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
1348
|
+
function aggregateChecks(runs) {
|
|
1349
|
+
const newest = [...runs].sort((a, b) => (b.startedAt ?? "").localeCompare(a.startedAt ?? "") || b.databaseId - a.databaseId)[0];
|
|
1350
|
+
if (!newest) return "none";
|
|
1351
|
+
if (newest.status !== "COMPLETED") return "pending";
|
|
1352
|
+
if (newest.conclusion === "SUCCESS") return "success";
|
|
1353
|
+
if (newest.conclusion && FAILED$1.has(newest.conclusion)) return "failure";
|
|
1354
|
+
if (newest.conclusion === "CANCELLED") return "pending";
|
|
1355
|
+
return "none";
|
|
371
1356
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
}
|
|
383
|
-
async listSecrets(scope) {
|
|
384
|
-
return this.client.secrets.listSecrets(this.opts.repo, toGHScope(scope));
|
|
385
|
-
}
|
|
386
|
-
async setSecret(scope, name, value) {
|
|
387
|
-
const ghScope = toGHScope(scope);
|
|
388
|
-
const pk = await this.client.secrets.getPublicKey(this.opts.repo, ghScope);
|
|
389
|
-
const body = {
|
|
390
|
-
encrypted_value: await encryptSecret(pk.key, value),
|
|
391
|
-
key_id: pk.key_id
|
|
1357
|
+
/** The neutral pull requests an issue is closed by; only an open one has its checks read, the others are `none`. */
|
|
1358
|
+
function toBoardPullRequests(nodes, keyOf) {
|
|
1359
|
+
return nodes.map((pr) => {
|
|
1360
|
+
const state = pr.state === "OPEN" ? "open" : pr.state === "MERGED" ? "merged" : "closed";
|
|
1361
|
+
const runs = (pr.commits?.nodes ?? []).flatMap((c) => c.commit.checkSuites.nodes.flatMap((suite) => suite.checkRuns.nodes));
|
|
1362
|
+
return {
|
|
1363
|
+
key: keyOf(pr.repository.nameWithOwner, pr.number),
|
|
1364
|
+
state,
|
|
1365
|
+
draft: pr.isDraft,
|
|
1366
|
+
checks: state === "open" ? aggregateChecks(runs) : "none"
|
|
392
1367
|
};
|
|
393
|
-
|
|
394
|
-
await this.client.secrets.putSecret(this.opts.repo, ghScope, name, body);
|
|
395
|
-
}
|
|
396
|
-
async deleteSecret(scope, name) {
|
|
397
|
-
await this.client.secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
|
|
398
|
-
}
|
|
399
|
-
};
|
|
400
|
-
function toGHScope(scope) {
|
|
401
|
-
if (scope.kind === "organization") return {
|
|
402
|
-
kind: "organization",
|
|
403
|
-
org: scope.name
|
|
404
|
-
};
|
|
405
|
-
return scope;
|
|
1368
|
+
});
|
|
406
1369
|
}
|
|
407
|
-
//#endregion
|
|
408
|
-
//#region src/capabilities/labels.ts
|
|
409
1370
|
/**
|
|
410
|
-
*
|
|
411
|
-
*
|
|
412
|
-
* -
|
|
413
|
-
* - PATCHes labels whose color or description has drifted.
|
|
414
|
-
* - DELETEs labels listed in `stale`.
|
|
415
|
-
* - Leaves unrecognised labels that aren't in `stale` untouched.
|
|
1371
|
+
* Reads the closing pull requests of each issue (by node id) with one small query per issue, a few at a time. A query
|
|
1372
|
+
* that fails is that issue's `problem` and nothing else: the others are read, and the caller leaves the failed one's
|
|
1373
|
+
* pull-request rules unapplied.
|
|
416
1374
|
*/
|
|
417
|
-
async function
|
|
418
|
-
const
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
description: label.description
|
|
430
|
-
});
|
|
431
|
-
created++;
|
|
432
|
-
} else if (current.color !== label.color || (current.description ?? "") !== label.description) {
|
|
433
|
-
await client.labels.updateLabel(repo, label.name, {
|
|
434
|
-
color: label.color,
|
|
435
|
-
description: label.description
|
|
436
|
-
});
|
|
437
|
-
updated++;
|
|
1375
|
+
async function readClosingPullRequests(graphql, contentIds, keyOf) {
|
|
1376
|
+
const results = /* @__PURE__ */ new Map();
|
|
1377
|
+
let next = 0;
|
|
1378
|
+
const worker = async () => {
|
|
1379
|
+
for (let i = next++; i < contentIds.length; i = next++) {
|
|
1380
|
+
const id = contentIds[i];
|
|
1381
|
+
try {
|
|
1382
|
+
const nodes = (await graphql.query(CLOSING_QUERY, { id })).node?.closedByPullRequestsReferences?.nodes;
|
|
1383
|
+
results.set(id, nodes ? { pullRequests: toBoardPullRequests(nodes, keyOf) } : { problem: "GitHub returned no pull request list" });
|
|
1384
|
+
} catch (err) {
|
|
1385
|
+
results.set(id, { problem: err instanceof Error ? err.message : String(err) });
|
|
1386
|
+
}
|
|
438
1387
|
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
deleted++;
|
|
443
|
-
}
|
|
444
|
-
return `${created} created, ${updated} updated, ${deleted} deleted`;
|
|
1388
|
+
};
|
|
1389
|
+
await Promise.all(Array.from({ length: Math.min(4, contentIds.length) }, worker));
|
|
1390
|
+
return results;
|
|
445
1391
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
1392
|
+
// src/capabilities/projects.ts
|
|
1393
|
+
/** The name of the single select field that holds an item's status. */
|
|
1394
|
+
const STATUS_FIELD = "Status";
|
|
1395
|
+
/** The name of the field `move` carries over besides the status. */
|
|
1396
|
+
const PRIORITY_FIELD = "Priority";
|
|
1397
|
+
const P_LEVELS = {
|
|
1398
|
+
p0: "urgent",
|
|
1399
|
+
p1: "high",
|
|
1400
|
+
p2: "medium",
|
|
1401
|
+
p3: "low"
|
|
1402
|
+
};
|
|
1403
|
+
/** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
|
|
1404
|
+
function priorityOf(value) {
|
|
1405
|
+
const name = value?.trim().toLowerCase();
|
|
1406
|
+
if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
|
|
1407
|
+
return name ? P_LEVELS[name] : void 0;
|
|
451
1408
|
}
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
1409
|
+
const PROJECT_FIELDS = "id number title closed url";
|
|
1410
|
+
const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
|
|
1411
|
+
${PROJECT_FIELDS}
|
|
1412
|
+
fields(first: 100) { nodes {
|
|
1413
|
+
... on ProjectV2FieldCommon { id name dataType }
|
|
1414
|
+
... on ProjectV2SingleSelectField { options { id name color description } }
|
|
1415
|
+
} }
|
|
1416
|
+
views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
|
|
1417
|
+
workflows(first: 50) { nodes { id name enabled } }
|
|
1418
|
+
} } }`;
|
|
1419
|
+
const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
|
|
1420
|
+
items(first: 100, after: $after) {
|
|
1421
|
+
pageInfo { hasNextPage endCursor }
|
|
1422
|
+
nodes {
|
|
1423
|
+
id
|
|
1424
|
+
fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
|
|
1425
|
+
content {
|
|
1426
|
+
__typename
|
|
1427
|
+
... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } }
|
|
1428
|
+
... on PullRequest { id number title state repository { nameWithOwner } }
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
} } }`;
|
|
1433
|
+
const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
|
|
1434
|
+
pageInfo { hasNextPage endCursor }
|
|
1435
|
+
nodes { ${PROJECT_FIELDS} }
|
|
1436
|
+
} } }`;
|
|
1437
|
+
const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
|
|
1438
|
+
const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
|
|
1439
|
+
updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
|
|
1440
|
+
}`;
|
|
1441
|
+
const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
|
|
1442
|
+
updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
|
|
1443
|
+
}`;
|
|
1444
|
+
const DATA_TYPES = {
|
|
1445
|
+
single_select: "SINGLE_SELECT",
|
|
1446
|
+
text: "TEXT",
|
|
1447
|
+
number: "NUMBER",
|
|
1448
|
+
date: "DATE",
|
|
1449
|
+
iteration: "ITERATION"
|
|
1450
|
+
};
|
|
1451
|
+
function fieldTypeOf(dataType) {
|
|
1452
|
+
return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
|
|
1453
|
+
}
|
|
1454
|
+
function toSummary(n) {
|
|
1455
|
+
return {
|
|
1456
|
+
id: n.id,
|
|
1457
|
+
number: n.number,
|
|
1458
|
+
name: n.title,
|
|
1459
|
+
url: n.url,
|
|
1460
|
+
closed: n.closed
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
function toOptionInput(o) {
|
|
1464
|
+
return {
|
|
1465
|
+
...o.id ? { id: o.id } : {},
|
|
1466
|
+
name: o.name,
|
|
1467
|
+
color: (o.color ?? "GRAY").toUpperCase(),
|
|
1468
|
+
description: o.description ?? ""
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
/** The GitHub implementation of the `projects` capability, backed by Projects v2. */
|
|
1472
|
+
var GitHubProjects = class {
|
|
1473
|
+
graphql;
|
|
1474
|
+
/** Capability key, always `"projects"`. */
|
|
1475
|
+
key = "projects";
|
|
1476
|
+
/** Provider name, always `"github"`. */
|
|
1477
|
+
providerName = "github";
|
|
1478
|
+
repo;
|
|
1479
|
+
constructor(graphql, opts) {
|
|
1480
|
+
this.graphql = graphql;
|
|
1481
|
+
this.repo = opts.repo;
|
|
1482
|
+
}
|
|
1483
|
+
/** Every board of the organization, open and closed. */
|
|
1484
|
+
async list(owner) {
|
|
1485
|
+
const boards = [];
|
|
1486
|
+
let after = null;
|
|
1487
|
+
for (;;) {
|
|
1488
|
+
const page = (await this.graphql.query(LIST_QUERY, {
|
|
1489
|
+
owner,
|
|
1490
|
+
after
|
|
1491
|
+
})).organization.projectsV2;
|
|
1492
|
+
boards.push(...page.nodes.map(toSummary));
|
|
1493
|
+
if (!page.pageInfo.hasNextPage) return boards;
|
|
1494
|
+
after = page.pageInfo.endCursor;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
/** The open board with exactly this name. */
|
|
1498
|
+
async find(owner, name) {
|
|
1499
|
+
return (await this.list(owner)).find((b) => !b.closed && b.name === name);
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
|
|
1503
|
+
* rules, no items); otherwise the board is created and brought in line with the template.
|
|
1504
|
+
*/
|
|
1505
|
+
async create(owner, name, template) {
|
|
1506
|
+
const ownerId = await this.ownerId(owner);
|
|
1507
|
+
const source = template.source ? await this.find(owner, template.source) : void 0;
|
|
1508
|
+
if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
|
|
1509
|
+
copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
|
|
1510
|
+
}`, {
|
|
1511
|
+
project: source.id,
|
|
1512
|
+
owner: ownerId,
|
|
1513
|
+
title: name
|
|
1514
|
+
})).copyProjectV2.projectV2);
|
|
1515
|
+
const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
|
|
1516
|
+
createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
|
|
1517
|
+
}`, {
|
|
1518
|
+
owner: ownerId,
|
|
1519
|
+
title: name
|
|
1520
|
+
})).createProjectV2.projectV2);
|
|
1521
|
+
await this.ensure(owner, board, template);
|
|
1522
|
+
return board;
|
|
1523
|
+
}
|
|
1524
|
+
/** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
|
|
1525
|
+
async close(_owner, board) {
|
|
1526
|
+
await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
|
|
1527
|
+
}
|
|
1528
|
+
/** The live board: statuses, other fields, views and automation rules. */
|
|
1529
|
+
async read(_owner, board) {
|
|
1530
|
+
const raw = await this.readRaw(board.id);
|
|
1531
|
+
const status = raw.fields.find((f) => f.name === STATUS_FIELD);
|
|
1532
|
+
const fields = [];
|
|
1533
|
+
for (const f of raw.fields) {
|
|
1534
|
+
const type = fieldTypeOf(f.dataType);
|
|
1535
|
+
if (!type || f.name === STATUS_FIELD) continue;
|
|
1536
|
+
fields.push({
|
|
1537
|
+
name: f.name,
|
|
1538
|
+
type,
|
|
1539
|
+
...f.options ? { options: f.options.map((o) => o.name) } : {}
|
|
1540
|
+
});
|
|
1541
|
+
}
|
|
1542
|
+
const views = [];
|
|
1543
|
+
for (const v of raw.views) {
|
|
1544
|
+
const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
|
|
1545
|
+
if (!layout) continue;
|
|
1546
|
+
views.push({
|
|
1547
|
+
name: v.name,
|
|
1548
|
+
layout,
|
|
1549
|
+
...v.filter ? { filter: v.filter } : {},
|
|
1550
|
+
...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
return {
|
|
1554
|
+
board: raw.summary,
|
|
1555
|
+
statuses: (status?.options ?? []).map((o) => o.name),
|
|
1556
|
+
fields,
|
|
1557
|
+
views,
|
|
1558
|
+
rules: raw.rules.map(({ name, enabled }) => ({
|
|
1559
|
+
name,
|
|
1560
|
+
enabled
|
|
1561
|
+
}))
|
|
1562
|
+
};
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
|
|
1566
|
+
* list without ids. Stops (throws) when the status field cannot be read.
|
|
1567
|
+
*/
|
|
1568
|
+
async ensure(_owner, board, template) {
|
|
1569
|
+
const raw = await this.readRaw(board.id);
|
|
1570
|
+
const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
|
|
1571
|
+
if (!status) throw new Error(`cannot read the "${STATUS_FIELD}" field of board "${board.name}"; stopped before any write so no item loses its status`);
|
|
1572
|
+
const changes = [];
|
|
1573
|
+
const todos = [];
|
|
1574
|
+
const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
|
|
1575
|
+
name: s.name,
|
|
1576
|
+
color: s.color,
|
|
1577
|
+
description: s.description
|
|
1578
|
+
})));
|
|
1579
|
+
changes.push(...statusChanges.map((c) => `status ${c}`));
|
|
1580
|
+
for (const want of template.fields) {
|
|
1581
|
+
const have = raw.fields.find((f) => f.name === want.name);
|
|
1582
|
+
if (!have) {
|
|
1583
|
+
await this.createField(board.id, want);
|
|
1584
|
+
changes.push(`field ${want.name} created`);
|
|
1585
|
+
continue;
|
|
1586
|
+
}
|
|
1587
|
+
if (fieldTypeOf(have.dataType) !== want.type) {
|
|
1588
|
+
todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
if (want.type === "single_select" && have.options && want.options) {
|
|
1592
|
+
const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
|
|
1593
|
+
changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
for (const want of template.views) {
|
|
1597
|
+
const have = raw.views.find((v) => v.name === want.name);
|
|
1598
|
+
const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
|
|
1599
|
+
let viewId = have?.id;
|
|
1600
|
+
if (!viewId) {
|
|
1601
|
+
viewId = await this.createView(board.id, want.name, layout);
|
|
1602
|
+
changes.push(`view ${want.name} created`);
|
|
1603
|
+
} else if (have && have.layout !== layout) {
|
|
1604
|
+
await this.updateView(viewId, { layout });
|
|
1605
|
+
changes.push(`view ${want.name} layout set to ${want.layout}`);
|
|
1606
|
+
}
|
|
1607
|
+
if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
|
|
1608
|
+
await this.updateView(viewId, { filter: want.filter });
|
|
1609
|
+
changes.push(`view ${want.name} filter set`);
|
|
1610
|
+
}
|
|
1611
|
+
if (want.groupBy && have?.groupBy[0] !== want.groupBy) todos.push(`group view "${want.name}" by ${want.groupBy}; the API cannot set a view's grouping`);
|
|
1612
|
+
}
|
|
1613
|
+
for (const rule of template.rules ?? []) {
|
|
1614
|
+
const have = raw.rules.find((r) => r.name === rule);
|
|
1615
|
+
if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
|
|
1616
|
+
else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
|
|
1617
|
+
}
|
|
1618
|
+
return {
|
|
1619
|
+
created: false,
|
|
1620
|
+
changes,
|
|
1621
|
+
todos
|
|
1622
|
+
};
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
|
|
1626
|
+
* template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
|
|
1627
|
+
*/
|
|
1628
|
+
async ensureOptions(board, field, wanted) {
|
|
1629
|
+
/* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
|
|
1630
|
+
const existing = field.options ?? [];
|
|
1631
|
+
const next = [];
|
|
1632
|
+
const changes = [];
|
|
1633
|
+
for (const w of wanted) {
|
|
1634
|
+
const have = existing.find((o) => o.name === w.name);
|
|
1635
|
+
if (have) {
|
|
1636
|
+
next.push({
|
|
1637
|
+
id: have.id,
|
|
1638
|
+
name: have.name,
|
|
1639
|
+
color: (w.color ?? have.color).toUpperCase(),
|
|
1640
|
+
description: w.description ?? have.description
|
|
1641
|
+
});
|
|
1642
|
+
if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
|
|
1643
|
+
} else {
|
|
1644
|
+
next.push({
|
|
1645
|
+
name: w.name,
|
|
1646
|
+
color: (w.color ?? "GRAY").toUpperCase(),
|
|
1647
|
+
description: w.description ?? ""
|
|
1648
|
+
});
|
|
1649
|
+
changes.push(`${w.name} added`);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
|
|
1653
|
+
const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
|
|
1654
|
+
if (changes.length === 0 && sameOrder) return [];
|
|
1655
|
+
if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
|
|
1656
|
+
const before = await this.fetchItems(board.id);
|
|
1657
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
1658
|
+
for (const item of before) {
|
|
1659
|
+
const value = item.values[field.name];
|
|
1660
|
+
if (value) snapshot.set(item.id, value);
|
|
1661
|
+
}
|
|
1662
|
+
await this.graphql.query(UPDATE_OPTIONS, {
|
|
1663
|
+
field: field.id,
|
|
1664
|
+
options: next.map(toOptionInput)
|
|
1665
|
+
});
|
|
1666
|
+
const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
|
|
1667
|
+
const afterItems = await this.fetchItems(board.id);
|
|
1668
|
+
const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
|
|
1669
|
+
const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
|
|
1670
|
+
if (lost.length > 0) {
|
|
1671
|
+
let restored = 0;
|
|
1672
|
+
for (const [itemId, name] of lost) {
|
|
1673
|
+
const option = afterField?.options?.find((o) => o.name === name);
|
|
1674
|
+
if (!option) continue;
|
|
1675
|
+
await this.graphql.query(SET_VALUE, {
|
|
1676
|
+
project: board.id,
|
|
1677
|
+
item: itemId,
|
|
1678
|
+
field: field.id,
|
|
1679
|
+
option: option.id
|
|
1680
|
+
});
|
|
1681
|
+
restored++;
|
|
1682
|
+
}
|
|
1683
|
+
throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
|
|
1684
|
+
}
|
|
1685
|
+
return changes;
|
|
1686
|
+
}
|
|
1687
|
+
async createField(projectId, want) {
|
|
1688
|
+
await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
|
|
1689
|
+
createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
|
|
1690
|
+
}`, {
|
|
1691
|
+
project: projectId,
|
|
1692
|
+
name: want.name,
|
|
1693
|
+
type: DATA_TYPES[want.type],
|
|
1694
|
+
options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
async createView(projectId, name, layout) {
|
|
1698
|
+
return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
|
|
1699
|
+
createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
|
|
1700
|
+
}`, {
|
|
1701
|
+
project: projectId,
|
|
1702
|
+
name,
|
|
1703
|
+
layout
|
|
1704
|
+
})).createProjectV2View.projectV2View.id;
|
|
1705
|
+
}
|
|
1706
|
+
async updateView(viewId, change) {
|
|
1707
|
+
await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
|
|
1708
|
+
updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
|
|
1709
|
+
}`, {
|
|
1710
|
+
view: viewId,
|
|
1711
|
+
layout: change.layout,
|
|
1712
|
+
filter: change.filter
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
/**
|
|
1716
|
+
* The board's issues and pull requests with their status, whether they are open and their open blockers. A second step
|
|
1717
|
+
* then reads, one small query per issue, the pull requests that close each open issue a rule could still move (it has a
|
|
1718
|
+
* status that is not `done` or `blocked` and no open blocker), each with the aggregate `ci / Required checks` state of
|
|
1719
|
+
* its head commit. An issue whose read fails keeps no `pullRequests` and carries `pullRequestsProblem` instead.
|
|
1720
|
+
*/
|
|
1721
|
+
async items(_owner, board, template) {
|
|
1722
|
+
const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
|
|
1723
|
+
const raw = await this.fetchItems(board.id);
|
|
1724
|
+
const wanted = raw.filter((i) => {
|
|
1725
|
+
const status = i.values[STATUS_FIELD];
|
|
1726
|
+
const category = status ? categories.get(status) : void 0;
|
|
1727
|
+
return i.issue && i.open && status !== void 0 && i.blockers.length === 0 && category !== "done" && category !== "blocked";
|
|
1728
|
+
});
|
|
1729
|
+
const closing = await readClosingPullRequests(this.graphql, wanted.map((i) => i.contentId), (r, n) => this.keyOf(r, n));
|
|
1730
|
+
return raw.map((i) => {
|
|
1731
|
+
const read = closing.get(i.contentId);
|
|
1732
|
+
const status = i.values[STATUS_FIELD];
|
|
1733
|
+
const category = status ? categories.get(status) : void 0;
|
|
1734
|
+
const priority = priorityOf(i.values[PRIORITY_FIELD]);
|
|
1735
|
+
return {
|
|
1736
|
+
key: this.keyOf(i.repo, i.number),
|
|
1737
|
+
title: i.title,
|
|
1738
|
+
open: i.open,
|
|
1739
|
+
...status ? { status } : {},
|
|
1740
|
+
...category ? { category } : {},
|
|
1741
|
+
blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
|
|
1742
|
+
...priority ? { priority } : {},
|
|
1743
|
+
...read && "pullRequests" in read ? { pullRequests: read.pullRequests } : {},
|
|
1744
|
+
...read && "problem" in read ? { pullRequestsProblem: read.problem } : {}
|
|
1745
|
+
};
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
/** Puts an item in a status; `transitioned` is false when it already is there. */
|
|
1749
|
+
async setStatus(_owner, board, key, status) {
|
|
1750
|
+
const ref = this.parseKey(key);
|
|
1751
|
+
const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
|
|
1752
|
+
const option = field?.options?.find((o) => o.name === status);
|
|
1753
|
+
if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
|
|
1754
|
+
const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
|
|
1755
|
+
if (!item) throw new Error(`${key} is not on board "${board.name}"`);
|
|
1756
|
+
if (item.values[STATUS_FIELD] === status) return {
|
|
1757
|
+
transitioned: false,
|
|
1758
|
+
status
|
|
1759
|
+
};
|
|
1760
|
+
await this.graphql.query(SET_VALUE, {
|
|
1761
|
+
project: board.id,
|
|
1762
|
+
item: item.id,
|
|
1763
|
+
field: field.id,
|
|
1764
|
+
option: option.id
|
|
1765
|
+
});
|
|
1766
|
+
return {
|
|
1767
|
+
transitioned: true,
|
|
1768
|
+
status,
|
|
1769
|
+
via: "project field set"
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
/**
|
|
1773
|
+
* Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
|
|
1774
|
+
* closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
|
|
1775
|
+
*/
|
|
1776
|
+
async move(_owner, from, to, template) {
|
|
1777
|
+
const report = {
|
|
1778
|
+
moved: [],
|
|
1779
|
+
kept: [],
|
|
1780
|
+
left: []
|
|
1781
|
+
};
|
|
1782
|
+
const [source, target, fromRaw, toRaw] = await Promise.all([
|
|
1783
|
+
this.fetchItems(from.id),
|
|
1784
|
+
this.fetchItems(to.id),
|
|
1785
|
+
this.readRaw(from.id),
|
|
1786
|
+
this.readRaw(to.id)
|
|
1787
|
+
]);
|
|
1788
|
+
const done = template.statuses.find((s) => s.category === "done")?.name;
|
|
1789
|
+
const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
|
|
1790
|
+
const carried = [STATUS_FIELD, PRIORITY_FIELD];
|
|
1791
|
+
for (const item of source) {
|
|
1792
|
+
const key = this.keyOf(item.repo, item.number);
|
|
1793
|
+
if (!item.open) {
|
|
1794
|
+
const current = item.values[STATUS_FIELD];
|
|
1795
|
+
if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
|
|
1796
|
+
report.left.push(key);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
let targetItem = target.find((t) => t.contentId === item.contentId);
|
|
1800
|
+
if (targetItem) report.kept.push(key);
|
|
1801
|
+
else {
|
|
1802
|
+
const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
|
|
1803
|
+
project: to.id,
|
|
1804
|
+
content: item.contentId
|
|
1805
|
+
});
|
|
1806
|
+
targetItem = {
|
|
1807
|
+
...item,
|
|
1808
|
+
id: data.addProjectV2ItemById.item.id,
|
|
1809
|
+
values: {}
|
|
1810
|
+
};
|
|
1811
|
+
report.moved.push(key);
|
|
1812
|
+
}
|
|
1813
|
+
for (const name of carried) {
|
|
1814
|
+
const value = item.values[name];
|
|
1815
|
+
if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
return report;
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
|
|
1822
|
+
* through the single select update, only where the item has no value yet. A status or priority with no option on
|
|
1823
|
+
* the board is reported in `dropped`; no option is ever created, so no value is cleared.
|
|
1824
|
+
*/
|
|
1825
|
+
async addItems(_owner, board, items, template) {
|
|
1826
|
+
const raw = await this.readRaw(board.id);
|
|
1827
|
+
const onBoard = await this.fetchItems(board.id);
|
|
1828
|
+
const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
|
|
1829
|
+
const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
|
|
1830
|
+
const results = [];
|
|
1831
|
+
for (const input of items) {
|
|
1832
|
+
const ref = this.parseKey(input.key);
|
|
1833
|
+
let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
|
|
1834
|
+
const added = !current;
|
|
1835
|
+
if (!current) current = {
|
|
1836
|
+
id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
|
|
1837
|
+
project: board.id,
|
|
1838
|
+
content: await this.nodeId(ref)
|
|
1839
|
+
})).addProjectV2ItemById.item.id,
|
|
1840
|
+
contentId: "",
|
|
1841
|
+
repo: ref.repo,
|
|
1842
|
+
number: ref.number,
|
|
1843
|
+
title: "",
|
|
1844
|
+
open: true,
|
|
1845
|
+
issue: false,
|
|
1846
|
+
values: {},
|
|
1847
|
+
blockers: []
|
|
1848
|
+
};
|
|
1849
|
+
const dropped = [];
|
|
1850
|
+
if (input.status !== void 0 || input.category !== void 0) {
|
|
1851
|
+
const name = this.statusFor(input, template, statusField?.options);
|
|
1852
|
+
if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
|
|
1853
|
+
else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
|
|
1854
|
+
}
|
|
1855
|
+
if (input.priority !== void 0 && input.priority !== "none") {
|
|
1856
|
+
const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
|
|
1857
|
+
if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
|
|
1858
|
+
else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
|
|
1859
|
+
}
|
|
1860
|
+
results.push({
|
|
1861
|
+
key: input.key,
|
|
1862
|
+
added,
|
|
1863
|
+
dropped
|
|
1864
|
+
});
|
|
1865
|
+
}
|
|
1866
|
+
return results;
|
|
1867
|
+
}
|
|
1868
|
+
/** The board's own status for an input: the option named like its status, else the template's status of its category. */
|
|
1869
|
+
statusFor(input, template, options) {
|
|
1870
|
+
const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
|
|
1871
|
+
const named = input.status === void 0 ? void 0 : has(input.status);
|
|
1872
|
+
if (named) return named;
|
|
1873
|
+
const byCategory = template.statuses.find((s) => s.category === input.category);
|
|
1874
|
+
return byCategory ? has(byCategory.name) : void 0;
|
|
1875
|
+
}
|
|
1876
|
+
/** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
|
|
1877
|
+
async nodeId(ref) {
|
|
1878
|
+
const [owner, name] = ref.repo.split("/");
|
|
1879
|
+
const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
|
|
1880
|
+
owner,
|
|
1881
|
+
name,
|
|
1882
|
+
number: ref.number
|
|
1883
|
+
})).repository?.issue?.id;
|
|
1884
|
+
if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
|
|
1885
|
+
return id;
|
|
1886
|
+
}
|
|
1887
|
+
/** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
|
|
1888
|
+
async whoami() {
|
|
1889
|
+
try {
|
|
1890
|
+
return {
|
|
1891
|
+
ok: true,
|
|
1892
|
+
boards: (await this.list(this.repo.split("/")[0] ?? "")).length
|
|
1893
|
+
};
|
|
1894
|
+
} catch {
|
|
1895
|
+
return {
|
|
1896
|
+
ok: false,
|
|
1897
|
+
boards: 0
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
/** Sets a single select value by option name; a field or option the board lacks is skipped. */
|
|
1902
|
+
async setOption(projectId, raw, itemId, fieldName, optionName) {
|
|
1903
|
+
const field = raw.fields.find((f) => f.name === fieldName && f.options);
|
|
1904
|
+
const option = field?.options?.find((o) => o.name === optionName);
|
|
1905
|
+
if (!field || !option) return;
|
|
1906
|
+
await this.graphql.query(SET_VALUE, {
|
|
1907
|
+
project: projectId,
|
|
1908
|
+
item: itemId,
|
|
1909
|
+
field: field.id,
|
|
1910
|
+
option: option.id
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
async ownerId(owner) {
|
|
1914
|
+
return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
|
|
1915
|
+
}
|
|
1916
|
+
async readRaw(id) {
|
|
1917
|
+
const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
|
|
1918
|
+
if (!n) throw new Error(`board ${id} not found`);
|
|
1919
|
+
return {
|
|
1920
|
+
summary: toSummary(n),
|
|
1921
|
+
fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
|
|
1922
|
+
id: f.id,
|
|
1923
|
+
name: f.name,
|
|
1924
|
+
dataType: f.dataType,
|
|
1925
|
+
...f.options ? { options: f.options } : {}
|
|
1926
|
+
})),
|
|
1927
|
+
views: n.views.nodes.map((v) => ({
|
|
1928
|
+
id: v.id,
|
|
1929
|
+
name: v.name,
|
|
1930
|
+
layout: v.layout,
|
|
1931
|
+
filter: v.filter,
|
|
1932
|
+
groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
|
|
1933
|
+
})),
|
|
1934
|
+
rules: n.workflows.nodes.map((w) => ({
|
|
1935
|
+
id: w.id,
|
|
1936
|
+
name: w.name,
|
|
1937
|
+
enabled: w.enabled
|
|
1938
|
+
}))
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
async fetchItems(id) {
|
|
1942
|
+
const items = [];
|
|
1943
|
+
let after = null;
|
|
1944
|
+
for (;;) {
|
|
1945
|
+
const page = (await this.graphql.query(ITEMS_QUERY, {
|
|
1946
|
+
id,
|
|
1947
|
+
after
|
|
1948
|
+
})).node.items;
|
|
1949
|
+
for (const n of page.nodes) {
|
|
1950
|
+
const c = n.content;
|
|
1951
|
+
if (!c || !c.repository) continue;
|
|
1952
|
+
const values = {};
|
|
1953
|
+
for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
|
|
1954
|
+
items.push({
|
|
1955
|
+
id: n.id,
|
|
1956
|
+
contentId: c.id,
|
|
1957
|
+
repo: c.repository.nameWithOwner,
|
|
1958
|
+
number: c.number,
|
|
1959
|
+
title: c.title,
|
|
1960
|
+
open: c.state === "OPEN",
|
|
1961
|
+
issue: c.__typename === "Issue",
|
|
1962
|
+
values,
|
|
1963
|
+
blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
|
|
1964
|
+
repo: b.repository.nameWithOwner,
|
|
1965
|
+
number: b.number
|
|
1966
|
+
}))
|
|
1967
|
+
});
|
|
1968
|
+
}
|
|
1969
|
+
if (!page.pageInfo.hasNextPage) return items;
|
|
1970
|
+
after = page.pageInfo.endCursor;
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
keyOf(repo, number) {
|
|
1974
|
+
return repo === this.repo ? `#${number}` : `${repo}#${number}`;
|
|
1975
|
+
}
|
|
1976
|
+
parseKey(key) {
|
|
1977
|
+
const m = /^(?:([^#\s]+))?#?(\d+)$/.exec(key.trim());
|
|
1978
|
+
const hasRepo = key.includes("#") && m?.[1];
|
|
1979
|
+
if (!m) throw new Error(`not an issue key: ${key}`);
|
|
1980
|
+
return {
|
|
1981
|
+
repo: hasRepo ? m[1] : this.repo,
|
|
1982
|
+
number: Number(m[2])
|
|
1983
|
+
};
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
// src/sodium.ts
|
|
1987
|
+
/**
|
|
1988
|
+
* libsodium sealed-box encryption for GitHub Actions secrets.
|
|
1989
|
+
*
|
|
1990
|
+
* GitHub stores Actions / Codespaces / Dependabot secrets encrypted
|
|
1991
|
+
* with a curve25519 public key (returned by the `/actions/secrets/public-key`
|
|
1992
|
+
* endpoint). Callers fetch that key, encrypt the plaintext value with
|
|
1993
|
+
* `crypto_box_seal`, then PUT the base64-encoded ciphertext + `key_id`.
|
|
1994
|
+
*
|
|
1995
|
+
* Reference: https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
|
|
1996
|
+
*
|
|
1997
|
+
* **Why createRequire?** `libsodium-wrappers@0.7.x` ships a broken
|
|
1998
|
+
* ESM bundle — the `dist/modules-esm/libsodium-wrappers.mjs` entry
|
|
1999
|
+
* imports a sibling `libsodium.mjs` that isn't included in the npm
|
|
2000
|
+
* tarball. Native `import` against the package therefore fails.
|
|
2001
|
+
* `createRequire` routes through Node's CJS resolver, which honors
|
|
2002
|
+
* the `"require"` condition in the package's exports map and loads
|
|
2003
|
+
* the self-contained CJS bundle instead. Same API, working module.
|
|
2004
|
+
*/
|
|
2005
|
+
const sodium = createRequire(import.meta.url)("libsodium-wrappers");
|
|
2006
|
+
/**
|
|
2007
|
+
* Encrypt `value` for the given GitHub-provided base64 public key.
|
|
2008
|
+
* Returns the base64 ciphertext to send as `encrypted_value`.
|
|
2009
|
+
*/
|
|
2010
|
+
async function encryptSecret(publicKeyBase64, value) {
|
|
2011
|
+
await sodium.ready;
|
|
2012
|
+
const publicKey = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
|
|
2013
|
+
const plaintext = sodium.from_string(value);
|
|
2014
|
+
const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
|
|
2015
|
+
return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
|
|
2016
|
+
}
|
|
2017
|
+
// src/capabilities/secrets.ts
|
|
2018
|
+
/** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
|
|
2019
|
+
var GitHubSecrets = class {
|
|
2020
|
+
client;
|
|
2021
|
+
opts;
|
|
2022
|
+
orgClient;
|
|
2023
|
+
/** Capability key, always `"secrets"`. */
|
|
2024
|
+
key = "secrets";
|
|
2025
|
+
/** Provider name, always `"github"`. */
|
|
2026
|
+
providerName = "github";
|
|
2027
|
+
/**
|
|
2028
|
+
* `client` handles repo and environment scopes; `orgClient`, when given, handles
|
|
2029
|
+
* the organization scope. They differ when a dedicated org-only token exists:
|
|
2030
|
+
* it can write org secrets but not repo ones, and `github.admin` is the reverse.
|
|
2031
|
+
*/
|
|
2032
|
+
constructor(client, opts, orgClient) {
|
|
2033
|
+
this.client = client;
|
|
2034
|
+
this.opts = opts;
|
|
2035
|
+
this.orgClient = orgClient;
|
|
2036
|
+
}
|
|
2037
|
+
/** Repository name to numeric id, so one run asks GitHub once per repository however many secrets name it. */
|
|
2038
|
+
repoIds = /* @__PURE__ */ new Map();
|
|
2039
|
+
clientFor(scope) {
|
|
2040
|
+
return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
|
|
2041
|
+
}
|
|
2042
|
+
async listSecrets(scope) {
|
|
2043
|
+
return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
|
|
2044
|
+
}
|
|
2045
|
+
async setSecret(scope, name, value) {
|
|
2046
|
+
const ghScope = toGHScope(scope);
|
|
2047
|
+
const client = this.clientFor(scope);
|
|
2048
|
+
const readers = scope.kind === "organization" ? await this.readers(scope) : {};
|
|
2049
|
+
const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
|
|
2050
|
+
const body = {
|
|
2051
|
+
encrypted_value: await encryptSecret(pk.key, value),
|
|
2052
|
+
key_id: pk.key_id
|
|
2053
|
+
};
|
|
2054
|
+
Object.assign(body, readers);
|
|
2055
|
+
await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
2058
|
+
* Who can read each organization secret, by name (never a value): `selected` ones come with the names of their
|
|
2059
|
+
* repositories. Any other scope has no visibility and gives `{}`.
|
|
2060
|
+
*/
|
|
2061
|
+
async listSecretAccess(scope) {
|
|
2062
|
+
if (scope.kind !== "organization") return {};
|
|
2063
|
+
const client = this.clientFor(scope);
|
|
2064
|
+
const found = {};
|
|
2065
|
+
for (const info of await client.secrets.listOrgSecretInfo(scope.name)) found[info.name] = info.visibility === "selected" ? {
|
|
2066
|
+
visibility: "selected",
|
|
2067
|
+
repos: await client.secrets.listSelectedRepositories(scope.name, info.name)
|
|
2068
|
+
} : { visibility: info.visibility };
|
|
2069
|
+
return found;
|
|
2070
|
+
}
|
|
2071
|
+
/** The `visibility` (and repository ids) of an organization write. No `visibility` keeps the older default, `all`. */
|
|
2072
|
+
async readers(scope) {
|
|
2073
|
+
const visibility = scope.visibility ?? "all";
|
|
2074
|
+
if (visibility !== "selected") return { visibility };
|
|
2075
|
+
if (!scope.repos?.length) throw new Error(`organization secret with visibility "selected" needs a non-empty repos list`);
|
|
2076
|
+
const ids = [];
|
|
2077
|
+
for (const name of scope.repos) ids.push(await this.repoId(scope.name, name));
|
|
2078
|
+
return {
|
|
2079
|
+
visibility,
|
|
2080
|
+
selected_repository_ids: ids
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
repoId(org, name) {
|
|
2084
|
+
const full = `${org}/${name}`;
|
|
2085
|
+
let id = this.repoIds.get(full);
|
|
2086
|
+
if (!id) {
|
|
2087
|
+
id = this.client.repos.getRepo(full).then((repo) => repo.id, (err) => {
|
|
2088
|
+
throw new Error(`could not resolve repository ${full}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2089
|
+
});
|
|
2090
|
+
this.repoIds.set(full, id);
|
|
2091
|
+
}
|
|
2092
|
+
return id;
|
|
2093
|
+
}
|
|
2094
|
+
/** Deletes the named secret in the given scope. */
|
|
2095
|
+
async deleteSecret(scope, name) {
|
|
2096
|
+
await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
2099
|
+
function toGHScope(scope) {
|
|
2100
|
+
if (scope.kind === "organization") return {
|
|
2101
|
+
kind: "organization",
|
|
2102
|
+
org: scope.name
|
|
2103
|
+
};
|
|
2104
|
+
return scope;
|
|
2105
|
+
}
|
|
2106
|
+
// src/capabilities/check-runs.ts
|
|
2107
|
+
/** Every check run on a commit in the plain shape the CLI reads (the aggregate's own included). */
|
|
2108
|
+
async function readCheckRuns(client, repo, ref) {
|
|
2109
|
+
return (await client.checks.listCheckRunsForRef(repo, ref)).map((run) => ({
|
|
2110
|
+
id: run.id,
|
|
2111
|
+
name: run.name,
|
|
2112
|
+
status: run.status,
|
|
2113
|
+
conclusion: run.conclusion,
|
|
2114
|
+
startedAt: run.started_at ?? null,
|
|
2115
|
+
url: run.details_url ?? run.html_url,
|
|
2116
|
+
appSlug: run.app?.slug ?? null
|
|
2117
|
+
}));
|
|
2118
|
+
}
|
|
2119
|
+
/** The commit statuses on a commit, newest first, in the plain shape the CLI reads. */
|
|
2120
|
+
async function readCommitStatuses(client, repo, ref) {
|
|
2121
|
+
return (await client.statuses.listCommitStatuses(repo, ref)).map((status) => ({
|
|
2122
|
+
context: status.context,
|
|
2123
|
+
state: status.state,
|
|
2124
|
+
url: status.target_url
|
|
2125
|
+
}));
|
|
2126
|
+
}
|
|
2127
|
+
/** GitHub's `output` for a write: the title and summary, and the details only when there are some. */
|
|
2128
|
+
function outputFor(write) {
|
|
2129
|
+
return {
|
|
2130
|
+
title: write.title,
|
|
2131
|
+
summary: write.summary,
|
|
2132
|
+
...write.text === "" ? {} : { text: write.text }
|
|
2133
|
+
};
|
|
2134
|
+
}
|
|
2135
|
+
/** Posts a check run on a commit and returns its id. */
|
|
2136
|
+
async function postCheckRun(client, repo, sha, name, write) {
|
|
2137
|
+
return (await client.checks.createCheckRun(repo, {
|
|
2138
|
+
name,
|
|
2139
|
+
head_sha: sha,
|
|
2140
|
+
status: write.status,
|
|
2141
|
+
...write.conclusion === void 0 ? {} : { conclusion: write.conclusion },
|
|
2142
|
+
output: outputFor(write),
|
|
2143
|
+
...write.startedAt === void 0 ? {} : { started_at: write.startedAt }
|
|
2144
|
+
})).id;
|
|
2145
|
+
}
|
|
2146
|
+
/** Changes a check run: its state, verdict and output. */
|
|
2147
|
+
async function patchCheckRun(client, repo, id, write) {
|
|
2148
|
+
await client.checks.updateCheckRun(repo, id, {
|
|
2149
|
+
status: write.status,
|
|
2150
|
+
...write.conclusion === void 0 ? {} : { conclusion: write.conclusion },
|
|
2151
|
+
output: outputFor(write)
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
// src/capabilities/files.ts
|
|
2155
|
+
/** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
|
|
2156
|
+
/** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
|
|
2157
|
+
function noAccess(repo, action, cause) {
|
|
2158
|
+
return new Error(`the token cannot ${action} files in ${repo} (403): give the user-sync token (HOLOCRON_USER_SYNC_TOKEN, or holocron new token github.user-sync) access to that repository with Contents: ${action === "read" ? "read" : "read and write"}`, { cause });
|
|
2159
|
+
}
|
|
2160
|
+
async function readRepoFile(client, repo, path) {
|
|
2161
|
+
try {
|
|
2162
|
+
const file = await client.git.getContents(repo, path);
|
|
2163
|
+
if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
|
|
2164
|
+
return {
|
|
2165
|
+
content: Buffer.from(file.content, "base64").toString("utf-8"),
|
|
2166
|
+
version: file.sha
|
|
2167
|
+
};
|
|
2168
|
+
} catch (err) {
|
|
2169
|
+
if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
|
|
2170
|
+
if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
|
|
2171
|
+
}
|
|
2172
|
+
try {
|
|
2173
|
+
await client.repos.getRepo(repo);
|
|
2174
|
+
} catch (err) {
|
|
2175
|
+
if (err instanceof ProviderApiError && err.status === 404) throw new Error(`${repo} was not found: it does not exist, or the token cannot see it`, { cause: err });
|
|
2176
|
+
throw err;
|
|
2177
|
+
}
|
|
2178
|
+
return null;
|
|
2179
|
+
}
|
|
2180
|
+
/** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
|
|
2181
|
+
async function writeRepoFile(client, repo, path, content, opts) {
|
|
2182
|
+
try {
|
|
2183
|
+
await client.git.putContents(repo, path, {
|
|
2184
|
+
message: opts.message,
|
|
2185
|
+
content,
|
|
2186
|
+
...opts.version ? { sha: opts.version } : {}
|
|
2187
|
+
});
|
|
2188
|
+
} catch (err) {
|
|
2189
|
+
if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
|
|
2190
|
+
throw err;
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
// src/capabilities/labels.ts
|
|
2194
|
+
/**
|
|
2195
|
+
* Idempotently synchronise a repo's labels to the canonical set.
|
|
2196
|
+
*
|
|
2197
|
+
* - Creates labels that are missing.
|
|
2198
|
+
* - PATCHes labels whose color or description has drifted.
|
|
2199
|
+
* - DELETEs labels listed in `stale`.
|
|
2200
|
+
* - Leaves unrecognised labels that aren't in `stale` untouched.
|
|
2201
|
+
*/
|
|
2202
|
+
async function syncLabels(client, repo, canonical, stale) {
|
|
2203
|
+
const existing = await client.labels.listLabels(repo);
|
|
2204
|
+
const existingMap = new Map(existing.map((l) => [l.name.toLowerCase(), l]));
|
|
2205
|
+
let created = 0;
|
|
2206
|
+
let updated = 0;
|
|
2207
|
+
let deleted = 0;
|
|
2208
|
+
for (const label of canonical) {
|
|
2209
|
+
const current = existingMap.get(label.name);
|
|
2210
|
+
if (!current) {
|
|
2211
|
+
await client.labels.createLabel(repo, {
|
|
2212
|
+
name: label.name,
|
|
2213
|
+
color: label.color,
|
|
2214
|
+
description: label.description
|
|
2215
|
+
});
|
|
2216
|
+
created++;
|
|
2217
|
+
} else if (current.color !== label.color || (current.description ?? "") !== label.description) {
|
|
2218
|
+
await client.labels.updateLabel(repo, label.name, {
|
|
2219
|
+
color: label.color,
|
|
2220
|
+
description: label.description
|
|
2221
|
+
});
|
|
2222
|
+
updated++;
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
for (const staleName of stale) if (existingMap.has(staleName)) {
|
|
2226
|
+
await client.labels.deleteLabel(repo, staleName);
|
|
2227
|
+
deleted++;
|
|
2228
|
+
}
|
|
2229
|
+
return `${created} created, ${updated} updated, ${deleted} deleted`;
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* Make the labels a repo lacks and change nothing else: an existing label (found without regard to case) keeps its
|
|
2233
|
+
* colour and description, and nothing is deleted. Used for the `area:<name>` family, which is not in the canonical set.
|
|
2234
|
+
*/
|
|
2235
|
+
async function ensureLabels(client, repo, labels) {
|
|
2236
|
+
const existing = await client.labels.listLabels(repo);
|
|
2237
|
+
const have = new Set(existing.map((l) => l.name.toLowerCase()));
|
|
2238
|
+
let created = 0;
|
|
2239
|
+
for (const label of labels) {
|
|
2240
|
+
if (have.has(label.name.toLowerCase())) continue;
|
|
2241
|
+
await client.labels.createLabel(repo, {
|
|
2242
|
+
name: label.name,
|
|
2243
|
+
color: label.color,
|
|
2244
|
+
description: label.description
|
|
2245
|
+
});
|
|
2246
|
+
created++;
|
|
2247
|
+
}
|
|
2248
|
+
return `${created} created, ${labels.length - created} already there`;
|
|
2249
|
+
}
|
|
2250
|
+
// src/capabilities/property-fix-hints.ts
|
|
2251
|
+
/** GitHub's wording when a custom property value is not one the organization's definition allows. */
|
|
2252
|
+
const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
|
|
2253
|
+
/**
|
|
2254
|
+
* What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
|
|
2255
|
+
* read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
|
|
2256
|
+
* belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
|
|
2257
|
+
* make its own value allowed. Empty when GitHub's message names no such value.
|
|
2258
|
+
*/
|
|
2259
|
+
function propertyFixHints(githubMessage) {
|
|
2260
|
+
const byProperty = /* @__PURE__ */ new Map();
|
|
2261
|
+
for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
|
|
2262
|
+
const values = byProperty.get(property) ?? [];
|
|
2263
|
+
if (!values.includes(value)) values.push(value);
|
|
2264
|
+
byProperty.set(property, values);
|
|
2265
|
+
}
|
|
2266
|
+
return [...byProperty].map(([property, values]) => `add ${values.map((v) => `"${v}"`).join(", ")} to the allowed values of the organization custom property ${property} (the organization's Settings, Custom properties), then run setup again`);
|
|
2267
|
+
}
|
|
2268
|
+
// src/capabilities/rejected-properties.ts
|
|
2269
|
+
/** The values `setup` sends for `true_false` properties; anything else is rejected. */
|
|
2270
|
+
const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
|
|
2271
|
+
/**
|
|
2272
|
+
* What is wrong with `values` when compared with the organization's property definitions, one sentence per
|
|
2273
|
+
* problem, in the order the properties are given: a property the organization does not define, a value a
|
|
2274
|
+
* `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
|
|
2275
|
+
* `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
|
|
2276
|
+
*/
|
|
2277
|
+
function rejectedProperties(values, schema) {
|
|
2278
|
+
const byName = new Map(schema.map((property) => [property.property_name, property]));
|
|
2279
|
+
const problems = [];
|
|
2280
|
+
for (const [name, value] of Object.entries(values)) {
|
|
2281
|
+
const definition = byName.get(name);
|
|
2282
|
+
if (!definition) {
|
|
2283
|
+
problems.push(`${name} is not a custom property of the organization`);
|
|
2284
|
+
continue;
|
|
2285
|
+
}
|
|
2286
|
+
const sent = Array.isArray(value) ? value : [value];
|
|
2287
|
+
if (definition.value_type === "true_false") {
|
|
2288
|
+
for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
|
|
2289
|
+
continue;
|
|
2290
|
+
}
|
|
2291
|
+
const allowed = definition.allowed_values ?? [];
|
|
2292
|
+
if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
|
|
2293
|
+
for (const item of sent.filter((item) => !allowed.includes(item))) problems.push(`${name} has "${item}", which is not one of its allowed values (${allowed.join(", ")})`);
|
|
2294
|
+
}
|
|
2295
|
+
return problems;
|
|
2296
|
+
}
|
|
2297
|
+
// src/capabilities/properties.ts
|
|
2298
|
+
/** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
|
|
2299
|
+
function githubMessage(details) {
|
|
2300
|
+
const raw = String(details ?? "").trim();
|
|
2301
|
+
try {
|
|
2302
|
+
const body = JSON.parse(raw);
|
|
2303
|
+
const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
|
|
2304
|
+
const message = typeof body.message === "string" ? body.message : raw;
|
|
2305
|
+
return errors ? `${message}: ${errors}` : message;
|
|
2306
|
+
} catch {
|
|
2307
|
+
return raw.slice(0, 300);
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
/** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
|
|
2311
|
+
async function orgSchema(client, repo) {
|
|
2312
|
+
try {
|
|
2313
|
+
return await client.properties.orgSchema(repo.split("/")[0]);
|
|
2314
|
+
} catch {
|
|
2315
|
+
return;
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
/**
|
|
2319
|
+
* The values `values` holds that the organization's property definitions do not allow, one sentence each, or
|
|
2320
|
+
* `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
|
|
2321
|
+
* the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
|
|
2322
|
+
* definitions is an organization permission a repository token often lacks. Read-only.
|
|
2323
|
+
*/
|
|
2324
|
+
async function checkPropertyValues(client, repo, values) {
|
|
2325
|
+
const schema = await orgSchema(client, repo);
|
|
2326
|
+
return schema ? rejectedProperties(values, schema) : void 0;
|
|
2327
|
+
}
|
|
2328
|
+
/**
|
|
2329
|
+
* Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
|
|
2330
|
+
* about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
|
|
2331
|
+
* organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
|
|
2332
|
+
* does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
|
|
2333
|
+
* request, so none of the properties is set.
|
|
2334
|
+
*/
|
|
2335
|
+
async function syncProperties(client, repo, values, schemaClient = client) {
|
|
2336
|
+
try {
|
|
2337
|
+
await client.properties.setProperties(repo, values);
|
|
2338
|
+
} catch (err) {
|
|
2339
|
+
if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
|
|
2340
|
+
const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
|
|
2341
|
+
const said = githubMessage(err.details);
|
|
2342
|
+
const fixes = propertyFixHints(said);
|
|
2343
|
+
throw new Error(`GitHub refused the custom properties (422), so none was set: ${problems.length > 0 ? problems.join("; ") : "no value differs from the organization's definitions, or they could not be read"}. GitHub said: ${said}${fixes.length > 0 ? `. To fix it: ${fixes.join("; ")}` : ""}`, { cause: err });
|
|
2344
|
+
}
|
|
2345
|
+
return `${Object.keys(values).length} properties set`;
|
|
2346
|
+
}
|
|
2347
|
+
/** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
|
|
2348
|
+
async function getOrgPropertyValues(client, repo, name) {
|
|
2349
|
+
return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
|
|
2353
|
+
* definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
|
|
2354
|
+
* and nothing removed. A write is made only when something is missing.
|
|
2355
|
+
*/
|
|
2356
|
+
async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = true) {
|
|
2357
|
+
const org = repo.split("/")[0];
|
|
2358
|
+
const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
|
|
2359
|
+
if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
|
|
2360
|
+
if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
|
|
2361
|
+
const have = new Set(current.allowed_values);
|
|
2362
|
+
const added = [...new Set(values)].filter((v) => !have.has(v));
|
|
2363
|
+
if (added.length === 0) return [];
|
|
2364
|
+
try {
|
|
2365
|
+
await client.properties.setOrgProperty(org, {
|
|
2366
|
+
...current,
|
|
2367
|
+
allowed_values: [...current.allowed_values, ...added]
|
|
2368
|
+
});
|
|
2369
|
+
} catch (err) {
|
|
2370
|
+
if (!(err instanceof ProviderApiError$1) || err.status !== 403 && err.status !== 401) throw err;
|
|
2371
|
+
const token = viaOrgToken ? "the organization token (HOLOCRON_ORG_TOKEN, or the token passed with --token)" : "the admin token, because no organization token was found (set HOLOCRON_ORG_TOKEN or pass --token)";
|
|
2372
|
+
throw new Error(`GitHub refused to change the "${name}" definition (${err.status}): it needs the organization permission Custom properties: Read and write (admin) on ${org}, and this ran with ${token}`, { cause: err });
|
|
2373
|
+
}
|
|
2374
|
+
return added;
|
|
2375
|
+
}
|
|
2376
|
+
// src/capabilities/pull-request-checks.ts
|
|
2377
|
+
/** The check run the aggregate `ci` workflow posts on a pull request's head commit. */
|
|
2378
|
+
const AGGREGATE_CHECK = "ci / Required checks";
|
|
2379
|
+
const FAILED = /* @__PURE__ */ new Set([
|
|
2380
|
+
"failure",
|
|
2381
|
+
"timed_out",
|
|
2382
|
+
"startup_failure",
|
|
2383
|
+
"action_required",
|
|
2384
|
+
"stale"
|
|
2385
|
+
]);
|
|
2386
|
+
const newestFirst = (a, b) => (b.started_at ?? "").localeCompare(a.started_at ?? "") || b.id - a.id;
|
|
2387
|
+
/** The aggregate's verdict from its runs: only the newest counts; a cancelled or unfinished run is `pending`. */
|
|
2388
|
+
function aggregateState(runs) {
|
|
2389
|
+
const newest = [...runs].sort(newestFirst)[0];
|
|
2390
|
+
if (!newest) return "none";
|
|
2391
|
+
if (newest.status !== "completed") return "pending";
|
|
2392
|
+
if (newest.conclusion === "success") return "success";
|
|
2393
|
+
if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
|
|
2394
|
+
if (newest.conclusion === "cancelled") return "pending";
|
|
2395
|
+
return "none";
|
|
2396
|
+
}
|
|
2397
|
+
/**
|
|
2398
|
+
* The aggregate check of a pull request's newest commit and the checks that failed on it, read now (never cached, so a
|
|
2399
|
+
* caller that polls sees each change). The newest run of each name counts, so a job that failed and was re-run to green
|
|
2400
|
+
* is not listed.
|
|
2401
|
+
*/
|
|
2402
|
+
async function readPullRequestChecks(client, repo, number) {
|
|
2403
|
+
const sha = (await client.pulls.getPullRequest(repo, number)).head.sha;
|
|
2404
|
+
const runs = await client.checks.listCheckRunsForRef(repo, sha);
|
|
2405
|
+
const newest = /* @__PURE__ */ new Map();
|
|
2406
|
+
for (const run of [...runs].sort(newestFirst)) if (!newest.has(run.name)) newest.set(run.name, run);
|
|
2407
|
+
return {
|
|
2408
|
+
state: aggregateState(runs.filter((r) => r.name === AGGREGATE_CHECK)),
|
|
2409
|
+
sha,
|
|
2410
|
+
failing: [...newest.values()].filter((r) => r.status === "completed" && r.conclusion !== null && FAILED.has(r.conclusion)).map((r) => ({
|
|
2411
|
+
name: r.name,
|
|
2412
|
+
url: r.details_url ?? r.html_url
|
|
2413
|
+
}))
|
|
2414
|
+
};
|
|
2415
|
+
}
|
|
2416
|
+
// src/capabilities/pull-requests.ts
|
|
2417
|
+
/** The GitHub pull request as the neutral {@link PullRequest}. */
|
|
2418
|
+
function toPullRequest(raw) {
|
|
2419
|
+
return {
|
|
2420
|
+
number: raw.number,
|
|
2421
|
+
title: raw.title,
|
|
2422
|
+
state: raw.state,
|
|
2423
|
+
merged: raw.merged_at !== null,
|
|
2424
|
+
branch: raw.head.ref,
|
|
2425
|
+
headSha: raw.head.sha,
|
|
2426
|
+
url: raw.html_url
|
|
2427
|
+
};
|
|
2428
|
+
}
|
|
2429
|
+
/** Whether a body already holds a closing or referencing line for the issue (any keyword, any case). */
|
|
2430
|
+
function names(body, issue) {
|
|
2431
|
+
const escaped = issue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2432
|
+
return new RegExp(`\\b(closes?|fix(es)?|resolves?|refs?)\\s+${escaped}(?![\\w-])`, "i").test(body);
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* The body with the link line the issue's closing reference needs. GitHub reads `Closes #12` itself, so the link is
|
|
2436
|
+
* text, not a call; a body that already names the issue is left alone.
|
|
2437
|
+
*/
|
|
2438
|
+
function withLink(body, link) {
|
|
2439
|
+
if (!link) return body;
|
|
2440
|
+
const issue = link.issue.trim();
|
|
2441
|
+
const ref = /^\d+$/.test(issue) ? `#${issue}` : issue;
|
|
2442
|
+
const text = body ?? "";
|
|
2443
|
+
if (names(text, ref)) return body;
|
|
2444
|
+
const line = `${link.keyword ?? "Refs"} ${ref}`;
|
|
2445
|
+
return text.trim() === "" ? line : `${text.replace(/\s+$/, "")}\n\n${line}`;
|
|
2446
|
+
}
|
|
2447
|
+
/** Puts the pull request (by node id) on each board of the organization found by title; a board not found or refused is returned by name. */
|
|
2448
|
+
async function addToBoards(client, repo, nodeId, titles) {
|
|
2449
|
+
const dropped = [];
|
|
2450
|
+
const owner = repo.slice(0, repo.indexOf("/"));
|
|
2451
|
+
let boards;
|
|
2452
|
+
try {
|
|
2453
|
+
boards = (await client.graphql.query(`query($owner: String!) { organization(login: $owner) { projectsV2(first: 100) { nodes { id title closed } } } }`, { owner })).organization;
|
|
2454
|
+
} catch {
|
|
2455
|
+
return titles.map((t) => `project ${t}`);
|
|
2456
|
+
}
|
|
2457
|
+
for (const title of titles) {
|
|
2458
|
+
const board = boards?.projectsV2.nodes.find((b) => b.title === title && !b.closed);
|
|
2459
|
+
if (!board) {
|
|
2460
|
+
dropped.push(`project ${title}`);
|
|
2461
|
+
continue;
|
|
2462
|
+
}
|
|
2463
|
+
try {
|
|
2464
|
+
await client.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
|
|
2465
|
+
project: board.id,
|
|
2466
|
+
content: nodeId
|
|
2467
|
+
});
|
|
2468
|
+
} catch {
|
|
2469
|
+
dropped.push(`project ${title}`);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
return dropped;
|
|
2473
|
+
}
|
|
2474
|
+
/**
|
|
2475
|
+
* Puts the fields an issue and its pull request share on the pull request (GitHub serves a pull request through
|
|
2476
|
+
* the issues API for these): labels and assignees are added to what is there, a milestone is found by title and
|
|
2477
|
+
* boards by title. What cannot be applied comes back by name; nothing is created or cleared.
|
|
2478
|
+
*/
|
|
2479
|
+
async function applyFields(client, repo, pr, fields) {
|
|
2480
|
+
const dropped = [];
|
|
2481
|
+
const { number } = pr;
|
|
2482
|
+
if (fields.labels?.length) await client.issues.addLabels(repo, number, fields.labels);
|
|
2483
|
+
for (const label of fields.removeLabels ?? []) try {
|
|
2484
|
+
await client.issues.removeLabel(repo, number, label);
|
|
2485
|
+
} catch {}
|
|
2486
|
+
const patch = {};
|
|
2487
|
+
if (fields.assignees?.length) {
|
|
2488
|
+
const have = ((await client.issues.getIssue(repo, number)).assignees ?? []).map((a) => a.login);
|
|
2489
|
+
const want = fields.assignees.map((a) => a.replace(/^@/, ""));
|
|
2490
|
+
const next = [.../* @__PURE__ */ new Set([...have, ...want])];
|
|
2491
|
+
if (next.length !== have.length) patch.assignees = next;
|
|
2492
|
+
}
|
|
2493
|
+
if (fields.milestone) {
|
|
2494
|
+
const found = (await client.issues.listMilestones(repo, { state: "open" })).find((m) => m.title === fields.milestone);
|
|
2495
|
+
if (found) patch.milestone = found.number;
|
|
2496
|
+
else dropped.push(`milestone ${fields.milestone}`);
|
|
2497
|
+
}
|
|
2498
|
+
if (Object.keys(patch).length) await client.issues.updateIssue(repo, number, patch);
|
|
2499
|
+
if (fields.projects?.length) {
|
|
2500
|
+
if (pr.node_id) dropped.push(...await addToBoards(client, repo, pr.node_id, fields.projects));
|
|
2501
|
+
else dropped.push(...fields.projects.map((t) => `project ${t}`));
|
|
2502
|
+
}
|
|
2503
|
+
return dropped;
|
|
2504
|
+
}
|
|
2505
|
+
/** Opens a draft pull request, or returns the open one for the same head, and applies the mirrored fields. */
|
|
2506
|
+
async function createPullRequest(client, repo, input) {
|
|
2507
|
+
const existing = (await client.pulls.listOpenByHead(repo, input.head))[0];
|
|
2508
|
+
const created = !existing;
|
|
2509
|
+
const raw = existing ?? await client.pulls.createPullRequest(repo, {
|
|
2510
|
+
title: input.title,
|
|
2511
|
+
head: input.head,
|
|
2512
|
+
base: input.base,
|
|
2513
|
+
body: withLink(input.body, input.link),
|
|
2514
|
+
draft: input.draft ?? true
|
|
2515
|
+
});
|
|
2516
|
+
const dropped = await applyFields(client, repo, raw, input);
|
|
2517
|
+
return {
|
|
2518
|
+
pullRequest: toPullRequest(raw),
|
|
2519
|
+
created,
|
|
2520
|
+
draft: raw.draft ?? false,
|
|
2521
|
+
dropped
|
|
2522
|
+
};
|
|
2523
|
+
}
|
|
2524
|
+
/** Changes a pull request's own fields, then the mirrored ones. A patch that names none of the own fields makes no PATCH. */
|
|
2525
|
+
async function updatePullRequest(client, repo, number, patch) {
|
|
2526
|
+
const own = {};
|
|
2527
|
+
if (patch.title !== void 0) own.title = patch.title;
|
|
2528
|
+
if (patch.body !== void 0) own.body = patch.body;
|
|
2529
|
+
if (patch.base !== void 0) own.base = patch.base;
|
|
2530
|
+
if (patch.state !== void 0) own.state = patch.state;
|
|
2531
|
+
const raw = Object.keys(own).length ? await client.pulls.updatePullRequest(repo, number, own) : await client.pulls.getPullRequest(repo, number);
|
|
2532
|
+
const dropped = await applyFields(client, repo, raw, patch);
|
|
2533
|
+
return {
|
|
2534
|
+
pullRequest: toPullRequest(raw),
|
|
2535
|
+
created: false,
|
|
2536
|
+
draft: raw.draft ?? false,
|
|
2537
|
+
dropped
|
|
2538
|
+
};
|
|
2539
|
+
}
|
|
2540
|
+
/** Takes a draft out of draft; `false` when it was not a draft or is not open. */
|
|
2541
|
+
async function markReady(client, repo, number) {
|
|
2542
|
+
const raw = await client.pulls.getPullRequest(repo, number);
|
|
2543
|
+
if (!raw.draft || raw.state !== "open") return false;
|
|
2544
|
+
if (!raw.node_id) throw new Error(`pull request ${repo}#${number} has no node id to mark ready`);
|
|
2545
|
+
await client.pulls.markReadyForReview(raw.node_id);
|
|
2546
|
+
return true;
|
|
2547
|
+
}
|
|
2548
|
+
// src/capabilities/read-repo.ts
|
|
2549
|
+
/** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
|
|
2550
|
+
const SETTING_KEYS = [
|
|
2551
|
+
"allow_squash_merge",
|
|
2552
|
+
"allow_merge_commit",
|
|
2553
|
+
"allow_rebase_merge",
|
|
2554
|
+
"allow_auto_merge",
|
|
2555
|
+
"allow_update_branch",
|
|
2556
|
+
"delete_branch_on_merge",
|
|
2557
|
+
"has_issues",
|
|
2558
|
+
"has_discussions",
|
|
2559
|
+
"has_projects",
|
|
2560
|
+
"has_wiki"
|
|
2561
|
+
];
|
|
2562
|
+
/** The repository's description, homepage, default branch, topics and settings, from one read. */
|
|
2563
|
+
async function readRepoInfo(client, repo) {
|
|
2564
|
+
const data = await client.repos.getRepo(repo);
|
|
2565
|
+
const settings = { default_branch: data.default_branch };
|
|
2566
|
+
for (const key of SETTING_KEYS) {
|
|
2567
|
+
const value = data[key];
|
|
2568
|
+
if (value !== void 0) settings[key] = value;
|
|
2569
|
+
}
|
|
2570
|
+
return {
|
|
2571
|
+
description: data.description ?? null,
|
|
2572
|
+
homepage: data.homepage ?? null,
|
|
2573
|
+
defaultBranch: data.default_branch,
|
|
2574
|
+
topics: data.topics ?? [],
|
|
2575
|
+
settings
|
|
2576
|
+
};
|
|
2577
|
+
}
|
|
2578
|
+
/** A ruleset reduced to what `setup` writes: its enforcement, rule types, required status checks and the app a check is pinned to. */
|
|
2579
|
+
function toRulesetDetail(data) {
|
|
2580
|
+
const rules = data.rules ?? [];
|
|
2581
|
+
const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
|
|
2582
|
+
const entries = Array.isArray(checks) ? checks : [];
|
|
2583
|
+
const sources = {};
|
|
2584
|
+
for (const entry of entries) if (typeof entry.integration_id === "number") sources[String(entry.context)] = entry.integration_id;
|
|
2585
|
+
return {
|
|
2586
|
+
name: data.name,
|
|
2587
|
+
enforcement: data.enforcement,
|
|
2588
|
+
ruleTypes: rules.map((r) => r.type),
|
|
2589
|
+
requiredChecks: entries.map((c) => String(c.context)),
|
|
2590
|
+
...Object.keys(sources).length > 0 ? { requiredCheckSources: sources } : {}
|
|
2591
|
+
};
|
|
2592
|
+
}
|
|
2593
|
+
/** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
|
|
2594
|
+
async function readable(read) {
|
|
2595
|
+
try {
|
|
2596
|
+
return await read();
|
|
2597
|
+
} catch (err) {
|
|
2598
|
+
if (err instanceof ProviderApiError$1) return void 0;
|
|
2599
|
+
throw err;
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
/** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
|
|
2603
|
+
async function readSecurity(client, repo) {
|
|
2604
|
+
const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
|
|
2605
|
+
readable(() => client.repos.getRepo(repo)),
|
|
2606
|
+
readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
|
|
2607
|
+
readable(() => client.security.automatedSecurityFixesEnabled(repo)),
|
|
2608
|
+
readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
|
|
2609
|
+
readable(() => client.security.codeScanningDefaultSetupState(repo))
|
|
2610
|
+
]);
|
|
2611
|
+
const analysis = data?.security_and_analysis;
|
|
2612
|
+
const on = (feature) => {
|
|
2613
|
+
const status = analysis?.[feature]?.status;
|
|
2614
|
+
return status === void 0 ? void 0 : status === "enabled";
|
|
2615
|
+
};
|
|
2616
|
+
const found = {
|
|
2617
|
+
vulnerabilityAlerts: alerts,
|
|
2618
|
+
automatedSecurityFixes: fixes,
|
|
2619
|
+
secretScanning: on("secret_scanning"),
|
|
2620
|
+
secretScanningPushProtection: on("secret_scanning_push_protection"),
|
|
2621
|
+
privateVulnerabilityReporting: reporting,
|
|
2622
|
+
codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
|
|
2623
|
+
};
|
|
2624
|
+
return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
|
|
2625
|
+
}
|
|
2626
|
+
// src/capabilities/relay-source.ts
|
|
2627
|
+
/** The events a webhook subscribes to when the layout names none: the one the Dependabot relay source carries. */
|
|
2628
|
+
const DEFAULT_RELAY_EVENTS = ["dependabot_alert"];
|
|
2629
|
+
/** A repository name, `owner/name`, made of the characters GitHub allows. */
|
|
2630
|
+
const REPOSITORY$1 = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
2631
|
+
/** An organization login. */
|
|
2632
|
+
const ORGANIZATION = /^[A-Za-z0-9][A-Za-z0-9-]*$/;
|
|
2633
|
+
/**
|
|
2634
|
+
* Where a relay source's one webhook lives. A webhook has one URL, so a source covers one place, not a list: a single
|
|
2635
|
+
* repository (`scope: ["owner/name"]`, or the plugin's own repository when `scope` is absent) or an organization
|
|
2636
|
+
* (`options: { org: "name" }` with no `scope`). Both together, more than one repository and anything that is not
|
|
2637
|
+
* `owner/name` are a problem the caller reports, never a guess.
|
|
2638
|
+
*/
|
|
2639
|
+
function relayTarget(input, defaultRepo) {
|
|
2640
|
+
const org = input.options?.org;
|
|
2641
|
+
if (org !== void 0) {
|
|
2642
|
+
if (typeof org !== "string" || !ORGANIZATION.test(org)) return { problem: `relay source ${input.source}: \`options.org\` must be an organization login` };
|
|
2643
|
+
if (input.scope !== void 0 && input.scope.length > 0) return { problem: `relay source ${input.source}: name a repository in \`scope\` or an organization in \`options.org\`, not both` };
|
|
2644
|
+
return {
|
|
2645
|
+
scope: {
|
|
2646
|
+
kind: "organization",
|
|
2647
|
+
org
|
|
2648
|
+
},
|
|
2649
|
+
label: `organization ${org}`
|
|
2650
|
+
};
|
|
2651
|
+
}
|
|
2652
|
+
const scope = input.scope ?? [];
|
|
2653
|
+
if (scope.length > 1) return { problem: `relay source ${input.source}: a webhook has one URL, so \`scope\` names one repository, not ${scope.length}; use \`options.org\` for an organization` };
|
|
2654
|
+
const repo = scope[0] ?? defaultRepo;
|
|
2655
|
+
if (!REPOSITORY$1.test(repo)) return { problem: `relay source ${input.source}: \`scope\` must be one repository as \`owner/name\`${scope.length === 0 ? " (the plugin has no repository to default to)" : ""}` };
|
|
2656
|
+
return {
|
|
2657
|
+
scope: {
|
|
2658
|
+
kind: "repo",
|
|
2659
|
+
repo
|
|
2660
|
+
},
|
|
2661
|
+
label: `repository ${repo}`
|
|
2662
|
+
};
|
|
2663
|
+
}
|
|
2664
|
+
/** Whether two event lists subscribe to the same events. */
|
|
2665
|
+
function sameEvents(a, b) {
|
|
2666
|
+
return a.length === b.length && [...a].sort().every((event, i) => event === [...b].sort()[i]);
|
|
2667
|
+
}
|
|
2668
|
+
/** The sentence for a token GitHub refuses, which GitHub answers as a 403 or, for a hidden resource, a 404. */
|
|
2669
|
+
function accessTodo(label, scope) {
|
|
2670
|
+
return `GitHub refused the webhook call for ${label}: the token needs ${scope.kind === "organization" ? "Organization permission Webhooks: read and write (classic: admin:org_hook)" : "Repository permission Webhooks: read and write (classic: admin:repo_hook)"}, or add the webhook in the settings yourself and set the secret on the Worker`;
|
|
2671
|
+
}
|
|
2672
|
+
/**
|
|
2673
|
+
* Makes the GitHub webhook for a relay source (spec `tech-relay-sources`, issue #2531). The webhook is found by its
|
|
2674
|
+
* `config.url`; when absent it is made with the secret the caller offers (GitHub never returns it, so it is returned
|
|
2675
|
+
* only now), and an existing one has only its events and `active` flag brought in line. Nothing is deleted and an
|
|
2676
|
+
* adopted webhook keeps the secret the Worker has.
|
|
2677
|
+
*/
|
|
2678
|
+
async function ensureRelaySource(client, defaultRepo, input) {
|
|
2679
|
+
const target = relayTarget(input, defaultRepo);
|
|
2680
|
+
if ("problem" in target) return {
|
|
2681
|
+
created: false,
|
|
2682
|
+
updated: [],
|
|
2683
|
+
todo: [target.problem]
|
|
2684
|
+
};
|
|
2685
|
+
const events = input.events && input.events.length > 0 ? input.events : DEFAULT_RELAY_EVENTS;
|
|
2686
|
+
try {
|
|
2687
|
+
const found = (await client.hooks.listHooks(target.scope)).find((hook) => hook.config.url === input.url);
|
|
2688
|
+
if (!found) {
|
|
2689
|
+
if (!input.secret) return {
|
|
2690
|
+
created: false,
|
|
2691
|
+
updated: [],
|
|
2692
|
+
todo: [`no signing secret was offered for the ${target.label} webhook, so none was made`]
|
|
2693
|
+
};
|
|
2694
|
+
await client.hooks.createHook(target.scope, {
|
|
2695
|
+
url: input.url,
|
|
2696
|
+
secret: input.secret,
|
|
2697
|
+
events
|
|
2698
|
+
});
|
|
2699
|
+
return {
|
|
2700
|
+
created: true,
|
|
2701
|
+
updated: [],
|
|
2702
|
+
secret: input.secret
|
|
2703
|
+
};
|
|
2704
|
+
}
|
|
2705
|
+
const updated = [];
|
|
2706
|
+
const patch = {};
|
|
2707
|
+
if (!sameEvents(found.events, events)) {
|
|
2708
|
+
patch.events = events;
|
|
2709
|
+
updated.push("events");
|
|
2710
|
+
}
|
|
2711
|
+
if (!found.active) {
|
|
2712
|
+
patch.active = true;
|
|
2713
|
+
updated.push("active");
|
|
2714
|
+
}
|
|
2715
|
+
if (updated.length > 0) await client.hooks.updateHook(target.scope, found.id, patch);
|
|
2716
|
+
return {
|
|
2717
|
+
created: false,
|
|
2718
|
+
updated
|
|
2719
|
+
};
|
|
2720
|
+
} catch (err) {
|
|
2721
|
+
if (err instanceof ProviderApiError && (err.status === 403 || err.status === 404)) return {
|
|
2722
|
+
created: false,
|
|
2723
|
+
updated: [],
|
|
2724
|
+
todo: [accessTodo(target.label, target.scope)]
|
|
2725
|
+
};
|
|
2726
|
+
throw err;
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
/** Reads the webhook back without changing anything: whether it exists, is active and what it subscribes to. The secret is never readable. */
|
|
2730
|
+
async function inspectRelaySource(client, defaultRepo, input) {
|
|
2731
|
+
const target = relayTarget(input, defaultRepo);
|
|
2732
|
+
if ("problem" in target) throw new Error(target.problem);
|
|
2733
|
+
const found = (await client.hooks.listHooks(target.scope)).find((hook) => hook.config.url === input.url);
|
|
2734
|
+
if (!found) return { exists: false };
|
|
2735
|
+
return {
|
|
2736
|
+
exists: true,
|
|
2737
|
+
enabled: found.active,
|
|
2738
|
+
events: found.events,
|
|
2739
|
+
...target.scope.kind === "repo" ? { scope: [target.scope.repo] } : {}
|
|
2740
|
+
};
|
|
2741
|
+
}
|
|
2742
|
+
// src/capabilities/teams.ts
|
|
2743
|
+
/** Turns a team entry into slug and permission form; a bare slug gets `push`. */
|
|
2744
|
+
function normalizeTeamEntry(entry) {
|
|
2745
|
+
if (typeof entry === "string") return {
|
|
456
2746
|
slug: entry,
|
|
457
2747
|
permission: "push"
|
|
458
2748
|
};
|
|
459
2749
|
return entry;
|
|
460
2750
|
}
|
|
2751
|
+
/** Grants each team access to the repo and reports the outcome; throws when every team fails. */
|
|
461
2752
|
async function syncTeams(client, repo, teams) {
|
|
462
2753
|
const [org = "", name = ""] = repo.split("/", 2);
|
|
463
2754
|
const normalized = teams.map(normalizeTeamEntry);
|
|
@@ -470,17 +2761,121 @@ async function syncTeams(client, repo, teams) {
|
|
|
470
2761
|
}
|
|
471
2762
|
return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
|
|
472
2763
|
}
|
|
473
|
-
|
|
474
|
-
//#region src/capabilities/topics.ts
|
|
2764
|
+
// src/capabilities/topics.ts
|
|
475
2765
|
async function syncTopics(client, repo, topics) {
|
|
476
2766
|
await client.topics.setTopics(repo, topics);
|
|
477
2767
|
return `${topics.length} topics set`;
|
|
478
2768
|
}
|
|
479
|
-
|
|
480
|
-
|
|
2769
|
+
// src/capabilities/variables.ts
|
|
2770
|
+
/** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
|
|
2771
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
2772
|
+
/** Longest name GitHub accepts. */
|
|
2773
|
+
const MAX_NAME = 256;
|
|
2774
|
+
function assertNames(names) {
|
|
2775
|
+
for (const name of names) if (!NAME.test(name) || name.length > MAX_NAME || name.toUpperCase().startsWith("GITHUB_")) throw new Error(`invalid variable name ${JSON.stringify(name)}: use letters, digits and underscores (at most ${MAX_NAME}), not starting with a digit or GITHUB_`);
|
|
2776
|
+
}
|
|
2777
|
+
/** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
|
|
2778
|
+
const key = (name) => name.toUpperCase();
|
|
2779
|
+
/**
|
|
2780
|
+
* Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
|
|
2781
|
+
* already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
|
|
2782
|
+
* organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
|
|
2783
|
+
* Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
|
|
2784
|
+
*/
|
|
2785
|
+
async function reconcile(client, repo, scope, wanted, opts) {
|
|
2786
|
+
assertNames(wanted.map((w) => w.name));
|
|
2787
|
+
const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
|
|
2788
|
+
const counts = {
|
|
2789
|
+
created: 0,
|
|
2790
|
+
updated: 0,
|
|
2791
|
+
unchanged: 0,
|
|
2792
|
+
deleted: 0
|
|
2793
|
+
};
|
|
2794
|
+
for (const want of wanted) {
|
|
2795
|
+
const have = existing.get(key(want.name));
|
|
2796
|
+
const body = {
|
|
2797
|
+
name: want.name,
|
|
2798
|
+
value: want.value
|
|
2799
|
+
};
|
|
2800
|
+
if (want.visibility) body["visibility"] = want.visibility;
|
|
2801
|
+
if (!have) {
|
|
2802
|
+
if (opts.dryRun) {
|
|
2803
|
+
counts.created++;
|
|
2804
|
+
continue;
|
|
2805
|
+
}
|
|
2806
|
+
try {
|
|
2807
|
+
await client.variables.createVariable(repo, scope, body);
|
|
2808
|
+
counts.created++;
|
|
2809
|
+
continue;
|
|
2810
|
+
} catch (err) {
|
|
2811
|
+
if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
|
|
2812
|
+
}
|
|
2813
|
+
} else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
|
|
2814
|
+
counts.unchanged++;
|
|
2815
|
+
continue;
|
|
2816
|
+
}
|
|
2817
|
+
if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
|
|
2818
|
+
counts.updated++;
|
|
2819
|
+
}
|
|
2820
|
+
const declared = new Set(wanted.map((w) => key(w.name)));
|
|
2821
|
+
const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
|
|
2822
|
+
const unmanaged = undeclared.filter((v) => v.visibility === "selected");
|
|
2823
|
+
if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
|
|
2824
|
+
if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
|
|
2825
|
+
counts.deleted++;
|
|
2826
|
+
}
|
|
2827
|
+
const parts = opts.dryRun ? [
|
|
2828
|
+
`would create ${counts.created}`,
|
|
2829
|
+
`would update ${counts.updated}`,
|
|
2830
|
+
`${counts.unchanged} unchanged`
|
|
2831
|
+
] : [
|
|
2832
|
+
`${counts.created} created`,
|
|
2833
|
+
`${counts.updated} updated`,
|
|
2834
|
+
`${counts.unchanged} unchanged`
|
|
2835
|
+
];
|
|
2836
|
+
if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
|
|
2837
|
+
const left = opts.prune ? unmanaged : undeclared;
|
|
2838
|
+
if (left.length > 0) {
|
|
2839
|
+
const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
|
|
2840
|
+
parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
|
|
2841
|
+
}
|
|
2842
|
+
return parts.join(", ");
|
|
2843
|
+
}
|
|
2844
|
+
/** Reconcile a repository's Actions variables. */
|
|
2845
|
+
function syncVariables(client, repo, variables, opts = {}) {
|
|
2846
|
+
return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
|
|
2847
|
+
name,
|
|
2848
|
+
value
|
|
2849
|
+
})), {
|
|
2850
|
+
prune: opts.prune === true,
|
|
2851
|
+
dryRun: opts.dryRun === true
|
|
2852
|
+
});
|
|
2853
|
+
}
|
|
2854
|
+
/** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
|
|
2855
|
+
function syncOrgVariables(client, repo, org, variables, opts = {}) {
|
|
2856
|
+
const wanted = Object.entries(variables).map(([name, v]) => ({
|
|
2857
|
+
name,
|
|
2858
|
+
value: v.value,
|
|
2859
|
+
visibility: v.visibility
|
|
2860
|
+
}));
|
|
2861
|
+
return reconcile(client, repo, {
|
|
2862
|
+
kind: "organization",
|
|
2863
|
+
org
|
|
2864
|
+
}, wanted, {
|
|
2865
|
+
prune: opts.prune === true,
|
|
2866
|
+
dryRun: opts.dryRun === true
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
// src/capabilities/source.ts
|
|
2870
|
+
/**
|
|
2871
|
+
* The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
|
|
2872
|
+
* features and local workflow files.
|
|
2873
|
+
*/
|
|
481
2874
|
var GitHubSource = class {
|
|
482
2875
|
client;
|
|
2876
|
+
/** Capability key, always `"source"`. */
|
|
483
2877
|
key = "source";
|
|
2878
|
+
/** Provider name, always `"github"`. */
|
|
484
2879
|
providerName = "github";
|
|
485
2880
|
owner;
|
|
486
2881
|
name;
|
|
@@ -488,6 +2883,7 @@ var GitHubSource = class {
|
|
|
488
2883
|
repoRoot;
|
|
489
2884
|
workflowDir;
|
|
490
2885
|
orgClient;
|
|
2886
|
+
userSyncClient;
|
|
491
2887
|
baseUrl;
|
|
492
2888
|
fetchImpl;
|
|
493
2889
|
constructor(client, opts) {
|
|
@@ -496,15 +2892,35 @@ var GitHubSource = class {
|
|
|
496
2892
|
this.owner = owner;
|
|
497
2893
|
this.name = name;
|
|
498
2894
|
this.repo = opts.repo;
|
|
499
|
-
this.repoRoot = opts.repoRoot
|
|
500
|
-
|
|
2895
|
+
this.repoRoot = findRootSync(opts.repoRoot, ".git", {
|
|
2896
|
+
fallback: "start",
|
|
2897
|
+
realpath: true
|
|
2898
|
+
});
|
|
2899
|
+
this.workflowDir = join(this.repoRoot, ".github", "workflows");
|
|
501
2900
|
this.orgClient = opts.orgClient;
|
|
2901
|
+
this.userSyncClient = opts.userSyncClient;
|
|
502
2902
|
this.baseUrl = opts.baseUrl;
|
|
503
2903
|
this.fetchImpl = opts.fetch;
|
|
504
2904
|
}
|
|
2905
|
+
/**
|
|
2906
|
+
* Makes the GitHub webhook for a relay source: on one repository with the admin token, or on the organization
|
|
2907
|
+
* (`options.org`) with the organization token. Found by URL, events and `active` brought in line, nothing deleted.
|
|
2908
|
+
*/
|
|
2909
|
+
async ensureRelaySource(input) {
|
|
2910
|
+
return ensureRelaySource(this.relayClient(input), this.repo, input);
|
|
2911
|
+
}
|
|
2912
|
+
/** Reads the relay source's webhook back, changing nothing. GitHub never returns the secret, so `hasSecret` is left out. */
|
|
2913
|
+
async inspectRelaySource(input) {
|
|
2914
|
+
return inspectRelaySource(this.relayClient(input), this.repo, input);
|
|
2915
|
+
}
|
|
2916
|
+
/** The organization token for an organization's webhook, the repository one otherwise. */
|
|
2917
|
+
relayClient(input) {
|
|
2918
|
+
return input.options?.org !== void 0 ? this.orgClient ?? this.client : this.client;
|
|
2919
|
+
}
|
|
505
2920
|
async whoami() {
|
|
506
2921
|
return { login: (await this.client.user.getCurrentUser()).login };
|
|
507
2922
|
}
|
|
2923
|
+
/** Returns the repo's owner, name and default branch. */
|
|
508
2924
|
async getRepo() {
|
|
509
2925
|
const data = await this.client.repos.getRepo(this.repo);
|
|
510
2926
|
return {
|
|
@@ -513,27 +2929,34 @@ var GitHubSource = class {
|
|
|
513
2929
|
defaultBranch: data.default_branch
|
|
514
2930
|
};
|
|
515
2931
|
}
|
|
2932
|
+
/** Lists the repo's rulesets. */
|
|
516
2933
|
async listRulesets() {
|
|
517
2934
|
return this.client.rulesets.listRulesets(this.repo);
|
|
518
2935
|
}
|
|
2936
|
+
/** Creates a ruleset from the given payload. */
|
|
519
2937
|
async createRuleset(payload) {
|
|
520
2938
|
return this.client.rulesets.createRuleset(this.repo, payload);
|
|
521
2939
|
}
|
|
2940
|
+
/** Updates the ruleset with the given id from the payload. */
|
|
522
2941
|
async updateRuleset(id, payload) {
|
|
523
2942
|
return this.client.rulesets.updateRuleset(this.repo, id, payload);
|
|
524
2943
|
}
|
|
2944
|
+
/** Updates the repo's settings. */
|
|
525
2945
|
async updateRepoSettings(settings) {
|
|
526
2946
|
await this.client.repos.updateRepo(this.repo, settings);
|
|
527
2947
|
}
|
|
528
2948
|
async protectBranch(branch, payload) {
|
|
529
2949
|
await this.client.branches.protectBranch(this.repo, branch, payload);
|
|
530
2950
|
}
|
|
2951
|
+
/** Enables Dependabot vulnerability alerts. */
|
|
531
2952
|
async enableVulnerabilityAlerts() {
|
|
532
2953
|
await this.client.security.enableVulnerabilityAlerts(this.repo);
|
|
533
2954
|
}
|
|
2955
|
+
/** Enables Dependabot automated security fixes. */
|
|
534
2956
|
async enableAutomatedSecurityFixes() {
|
|
535
2957
|
await this.client.security.enableAutomatedSecurityFixes(this.repo);
|
|
536
2958
|
}
|
|
2959
|
+
/** Enables secret scanning. */
|
|
537
2960
|
async enableSecretScanning() {
|
|
538
2961
|
await this.client.security.enableSecretScanning(this.repo);
|
|
539
2962
|
}
|
|
@@ -546,9 +2969,11 @@ var GitHubSource = class {
|
|
|
546
2969
|
async enableDependencyGraph() {
|
|
547
2970
|
await this.client.security.enableDependencyGraph(this.repo);
|
|
548
2971
|
}
|
|
2972
|
+
/** Enables private vulnerability reporting. */
|
|
549
2973
|
async enablePrivateVulnerabilityReporting() {
|
|
550
2974
|
await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
|
|
551
2975
|
}
|
|
2976
|
+
/** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
|
|
552
2977
|
async listWorkflowFiles() {
|
|
553
2978
|
try {
|
|
554
2979
|
return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
|
|
@@ -557,6 +2982,7 @@ var GitHubSource = class {
|
|
|
557
2982
|
throw err;
|
|
558
2983
|
}
|
|
559
2984
|
}
|
|
2985
|
+
/** Reads a workflow file's text, or `null` when it does not exist. */
|
|
560
2986
|
async readWorkflowFile(name) {
|
|
561
2987
|
try {
|
|
562
2988
|
return await readFile(join(this.workflowDir, name), "utf8");
|
|
@@ -565,10 +2991,12 @@ var GitHubSource = class {
|
|
|
565
2991
|
throw err;
|
|
566
2992
|
}
|
|
567
2993
|
}
|
|
2994
|
+
/** Writes a workflow file, creating `.github/workflows` first when needed. */
|
|
568
2995
|
async writeWorkflowFile(name, contents) {
|
|
569
2996
|
await ensureDir(this.workflowDir);
|
|
570
2997
|
await writeFile(join(this.workflowDir, name), contents, "utf8");
|
|
571
2998
|
}
|
|
2999
|
+
/** Removes a workflow file; a file that is already gone is not an error. */
|
|
572
3000
|
async removeWorkflowFile(name) {
|
|
573
3001
|
try {
|
|
574
3002
|
await rm(join(this.workflowDir, name));
|
|
@@ -585,15 +3013,87 @@ var GitHubSource = class {
|
|
|
585
3013
|
async syncLabels(canonical, stale) {
|
|
586
3014
|
return syncLabels(this.client, this.repo, canonical, stale);
|
|
587
3015
|
}
|
|
3016
|
+
async ensureLabels(labels) {
|
|
3017
|
+
return ensureLabels(this.client, this.repo, labels);
|
|
3018
|
+
}
|
|
588
3019
|
async syncProperties(values) {
|
|
589
|
-
return syncProperties(this.client, this.repo, values);
|
|
3020
|
+
return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
|
|
3021
|
+
}
|
|
3022
|
+
async getOrgPropertyValues(name) {
|
|
3023
|
+
return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
|
|
3024
|
+
}
|
|
3025
|
+
async addOrgPropertyValues(name, values) {
|
|
3026
|
+
return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values, this.orgClient !== void 0);
|
|
3027
|
+
}
|
|
3028
|
+
async checkPropertyValues(values) {
|
|
3029
|
+
return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
|
|
590
3030
|
}
|
|
591
3031
|
async syncTeams(teams) {
|
|
592
3032
|
return syncTeams(this.orgClient ?? this.client, this.repo, teams);
|
|
593
3033
|
}
|
|
3034
|
+
async teamMembers(teamSlug, org = this.owner) {
|
|
3035
|
+
return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
|
|
3036
|
+
id: String(m.id),
|
|
3037
|
+
login: m.login
|
|
3038
|
+
}));
|
|
3039
|
+
}
|
|
3040
|
+
async readFile(path, repo = this.repo) {
|
|
3041
|
+
return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
|
|
3042
|
+
}
|
|
3043
|
+
async writeFile(path, content, opts) {
|
|
3044
|
+
return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
|
|
3045
|
+
}
|
|
594
3046
|
async syncTopics(topics) {
|
|
595
3047
|
return syncTopics(this.client, this.repo, topics);
|
|
596
3048
|
}
|
|
3049
|
+
async syncVariables(variables, opts) {
|
|
3050
|
+
return syncVariables(this.client, this.repo, variables, opts);
|
|
3051
|
+
}
|
|
3052
|
+
async syncOrgVariables(org, variables, opts) {
|
|
3053
|
+
if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
|
|
3054
|
+
return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
|
|
3055
|
+
}
|
|
3056
|
+
async listVariables() {
|
|
3057
|
+
const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
|
|
3058
|
+
return Object.fromEntries(found.map((v) => [v.name, v.value]));
|
|
3059
|
+
}
|
|
3060
|
+
async listOrgVariables(org) {
|
|
3061
|
+
if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
|
|
3062
|
+
const found = await this.orgClient.variables.listVariables(this.repo, {
|
|
3063
|
+
kind: "organization",
|
|
3064
|
+
org
|
|
3065
|
+
});
|
|
3066
|
+
return Object.fromEntries(found.map((v) => [v.name, {
|
|
3067
|
+
value: v.value,
|
|
3068
|
+
visibility: v.visibility ?? "all"
|
|
3069
|
+
}]));
|
|
3070
|
+
}
|
|
3071
|
+
async getRepoInfo() {
|
|
3072
|
+
return readRepoInfo(this.client, this.repo);
|
|
3073
|
+
}
|
|
3074
|
+
async getProperties() {
|
|
3075
|
+
const found = await this.client.properties.getValues(this.repo);
|
|
3076
|
+
return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
|
|
3077
|
+
}
|
|
3078
|
+
async listLabels() {
|
|
3079
|
+
return (await this.client.labels.listLabels(this.repo)).map((l) => ({
|
|
3080
|
+
name: l.name,
|
|
3081
|
+
color: l.color,
|
|
3082
|
+
description: l.description ?? ""
|
|
3083
|
+
}));
|
|
3084
|
+
}
|
|
3085
|
+
async listTeamAccess() {
|
|
3086
|
+
return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
|
|
3087
|
+
slug: t.slug,
|
|
3088
|
+
permission: t.permission
|
|
3089
|
+
}));
|
|
3090
|
+
}
|
|
3091
|
+
async getRulesetDetail(id) {
|
|
3092
|
+
return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
|
|
3093
|
+
}
|
|
3094
|
+
async getSecurity() {
|
|
3095
|
+
return readSecurity(this.client, this.repo);
|
|
3096
|
+
}
|
|
597
3097
|
async syncDescription(description) {
|
|
598
3098
|
await this.client.repos.updateRepo(this.repo, { description });
|
|
599
3099
|
return "description updated";
|
|
@@ -603,15 +3103,55 @@ var GitHubSource = class {
|
|
|
603
3103
|
return "homepage updated";
|
|
604
3104
|
}
|
|
605
3105
|
async getPullRequest(number, repo) {
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
3106
|
+
return toPullRequest(await this.client.pulls.getPullRequest(repo ?? this.repo, number));
|
|
3107
|
+
}
|
|
3108
|
+
async listPullRequests(state, repo) {
|
|
3109
|
+
return (await this.client.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
|
|
3110
|
+
}
|
|
3111
|
+
async listBranches(repo) {
|
|
3112
|
+
return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
|
|
3113
|
+
name: b.name,
|
|
3114
|
+
sha: b.commit.sha
|
|
3115
|
+
}));
|
|
3116
|
+
}
|
|
3117
|
+
async deleteBranch(name, repo) {
|
|
3118
|
+
try {
|
|
3119
|
+
await this.client.branches.removeBranch(repo ?? this.repo, name);
|
|
3120
|
+
} catch (err) {
|
|
3121
|
+
if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
|
|
3122
|
+
throw err;
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
async listPullRequestCommits(number, repo) {
|
|
3126
|
+
return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
|
|
3127
|
+
}
|
|
3128
|
+
async listPullRequestFiles(number, repo) {
|
|
3129
|
+
const files = await this.client.pulls.listFiles(repo ?? this.repo, number);
|
|
3130
|
+
return [...new Set(files.flatMap((f) => f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]))];
|
|
3131
|
+
}
|
|
3132
|
+
async createPullRequest(input, repo) {
|
|
3133
|
+
return createPullRequest(this.client, repo ?? this.repo, input);
|
|
3134
|
+
}
|
|
3135
|
+
async updatePullRequest(number, patch, repo) {
|
|
3136
|
+
return updatePullRequest(this.client, repo ?? this.repo, number, patch);
|
|
3137
|
+
}
|
|
3138
|
+
async markReady(number, repo) {
|
|
3139
|
+
return markReady(this.client, repo ?? this.repo, number);
|
|
3140
|
+
}
|
|
3141
|
+
async getPullRequestChecks(number, repo) {
|
|
3142
|
+
return readPullRequestChecks(this.client, repo ?? this.repo, number);
|
|
3143
|
+
}
|
|
3144
|
+
async listCheckRuns(ref, repo) {
|
|
3145
|
+
return readCheckRuns(this.client, repo ?? this.repo, ref);
|
|
3146
|
+
}
|
|
3147
|
+
async listCommitStatuses(ref, repo) {
|
|
3148
|
+
return readCommitStatuses(this.client, repo ?? this.repo, ref);
|
|
3149
|
+
}
|
|
3150
|
+
async createCheckRun(sha, name, write, repo) {
|
|
3151
|
+
return postCheckRun(this.client, repo ?? this.repo, sha, name, write);
|
|
3152
|
+
}
|
|
3153
|
+
async updateCheckRun(id, write, repo) {
|
|
3154
|
+
return patchCheckRun(this.client, repo ?? this.repo, id, write);
|
|
615
3155
|
}
|
|
616
3156
|
async configurePages(config, token) {
|
|
617
3157
|
const pagesClient = createGitHubClient$1({
|
|
@@ -650,18 +3190,1164 @@ async function ensureDir(path) {
|
|
|
650
3190
|
throw err;
|
|
651
3191
|
}
|
|
652
3192
|
}
|
|
653
|
-
|
|
654
|
-
|
|
3193
|
+
// src/probes/issue-types/github-api.ts
|
|
3194
|
+
const PAGE = 100;
|
|
3195
|
+
const PROJECTS_OF = `query($ids: [ID!]!) { nodes(ids: $ids) { ... on Issue { id projectItems(first: 20) { nodes { project { id } } } } } }`;
|
|
3196
|
+
const ADD_ITEM = `mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`;
|
|
3197
|
+
const ISSUE_TYPES = `query($org: String!) { organization(login: $org) { issueTypes(first: 50) { nodes { name } } } }`;
|
|
3198
|
+
function toItem(issue) {
|
|
3199
|
+
return {
|
|
3200
|
+
number: issue.number,
|
|
3201
|
+
title: issue.title,
|
|
3202
|
+
state: issue.state,
|
|
3203
|
+
labels: issue.labels.map((l) => l.name),
|
|
3204
|
+
type: issue.type?.name ?? null,
|
|
3205
|
+
milestone: issue.milestone ?? null,
|
|
3206
|
+
nodeId: issue.node_id ?? "",
|
|
3207
|
+
isPullRequest: issue.pull_request !== void 0,
|
|
3208
|
+
createdAt: issue.created_at ?? ""
|
|
3209
|
+
};
|
|
3210
|
+
}
|
|
3211
|
+
/**
|
|
3212
|
+
* The backfill's reads and writes over the GitHub client. `client` reads and writes issues (the `github.issues` token);
|
|
3213
|
+
* `orgClient` reads and writes the organization's projects (the `github.org` token). Each method is the one call, or the
|
|
3214
|
+
* fixed few, its name says, so the probe's logic is tested against a fake of {@link BackfillApi} and this stays thin.
|
|
3215
|
+
*/
|
|
3216
|
+
function createBackfillApi(client, orgClient, repo) {
|
|
3217
|
+
const org = repo.split("/")[0];
|
|
3218
|
+
const projects = new GitHubProjects(orgClient.graphql, { repo });
|
|
3219
|
+
let fieldList;
|
|
3220
|
+
const fields = async () => fieldList ??= client.issueFields.list(org);
|
|
3221
|
+
return {
|
|
3222
|
+
async list(page) {
|
|
3223
|
+
return (await client.issues.listIssues(repo, {
|
|
3224
|
+
state: "all",
|
|
3225
|
+
sort: "created",
|
|
3226
|
+
direction: "asc",
|
|
3227
|
+
per_page: PAGE,
|
|
3228
|
+
page
|
|
3229
|
+
})).map(toItem);
|
|
3230
|
+
},
|
|
3231
|
+
async get(number) {
|
|
3232
|
+
return toItem(await client.issues.getIssue(repo, number));
|
|
3233
|
+
},
|
|
3234
|
+
async parent(number) {
|
|
3235
|
+
const parent = await client.issues.getParent(repo, number);
|
|
3236
|
+
return parent ? {
|
|
3237
|
+
number: parent.number,
|
|
3238
|
+
milestone: parent.milestone?.number ?? null
|
|
3239
|
+
} : null;
|
|
3240
|
+
},
|
|
3241
|
+
async labelNames() {
|
|
3242
|
+
return new Set((await client.labels.listLabels(repo)).map((l) => l.name.toLowerCase()));
|
|
3243
|
+
},
|
|
3244
|
+
async milestoneNumber(title) {
|
|
3245
|
+
return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => m.title.toLowerCase() === title.toLowerCase())?.number;
|
|
3246
|
+
},
|
|
3247
|
+
async projectId(title) {
|
|
3248
|
+
return (await projects.find(org, title))?.id;
|
|
3249
|
+
},
|
|
3250
|
+
async projectsOf(nodeIds) {
|
|
3251
|
+
const data = await orgClient.graphql.query(PROJECTS_OF, { ids: nodeIds });
|
|
3252
|
+
const out = /* @__PURE__ */ new Map();
|
|
3253
|
+
for (const node of data.nodes) if (node?.id) out.set(node.id, (node.projectItems?.nodes ?? []).map((i) => i.project.id));
|
|
3254
|
+
return out;
|
|
3255
|
+
},
|
|
3256
|
+
async fieldNames() {
|
|
3257
|
+
try {
|
|
3258
|
+
return new Set((await fields()).map((f) => f.name.toLowerCase()));
|
|
3259
|
+
} catch (err) {
|
|
3260
|
+
const why = fieldRefusal(err);
|
|
3261
|
+
if (why === void 0) throw err;
|
|
3262
|
+
return why;
|
|
3263
|
+
}
|
|
3264
|
+
},
|
|
3265
|
+
async fieldValues(number) {
|
|
3266
|
+
const byId = new Map((await fields()).map((f) => [f.id, f.name.toLowerCase()]));
|
|
3267
|
+
const values = await client.issueFields.values(repo, number);
|
|
3268
|
+
return new Set(values.map((v) => v.issue_field_name?.toLowerCase() ?? byId.get(v.issue_field_id) ?? ""));
|
|
3269
|
+
},
|
|
3270
|
+
async files(number) {
|
|
3271
|
+
return (await client.pulls.listFiles(repo, number)).map((f) => f.filename);
|
|
3272
|
+
},
|
|
3273
|
+
async typeNames() {
|
|
3274
|
+
const data = await orgClient.graphql.query(ISSUE_TYPES, { org });
|
|
3275
|
+
return new Set((data.organization?.issueTypes?.nodes ?? []).map((t) => t.name));
|
|
3276
|
+
},
|
|
3277
|
+
async readFile(path) {
|
|
3278
|
+
return (await readRepoFile(client, repo, path))?.content ?? null;
|
|
3279
|
+
},
|
|
3280
|
+
async setType(number, type) {
|
|
3281
|
+
await client.issues.updateIssue(repo, number, { type });
|
|
3282
|
+
},
|
|
3283
|
+
async addLabels(number, labels) {
|
|
3284
|
+
await client.issues.addLabels(repo, number, labels);
|
|
3285
|
+
},
|
|
3286
|
+
async setMilestone(number, milestone) {
|
|
3287
|
+
await client.issues.updateIssue(repo, number, { milestone });
|
|
3288
|
+
},
|
|
3289
|
+
async addToProject(projectId, nodeId) {
|
|
3290
|
+
await orgClient.graphql.query(ADD_ITEM, {
|
|
3291
|
+
project: projectId,
|
|
3292
|
+
content: nodeId
|
|
3293
|
+
});
|
|
3294
|
+
}
|
|
3295
|
+
};
|
|
3296
|
+
}
|
|
3297
|
+
// src/probes/issue-types/gather.ts
|
|
3298
|
+
/** Whether a day (`YYYY-MM-DD`) is before the start of the window. */
|
|
3299
|
+
const before = (item, since) => since !== void 0 && item.createdAt.slice(0, 10) < since;
|
|
3300
|
+
/** The issues named by `--issues`, past the cursor, at most `limit` of them. */
|
|
3301
|
+
async function named(api, options, isRateLimited) {
|
|
3302
|
+
const numbers = [...new Set(options.issues)].sort((a, b) => a - b).filter((n) => n > options.after);
|
|
3303
|
+
const out = {
|
|
3304
|
+
items: [],
|
|
3305
|
+
more: numbers.length > options.limit,
|
|
3306
|
+
rateLimited: false,
|
|
3307
|
+
pullRequestsSkipped: 0
|
|
3308
|
+
};
|
|
3309
|
+
for (const number of numbers.slice(0, options.limit)) try {
|
|
3310
|
+
const item = await api.get(number);
|
|
3311
|
+
if (item.isPullRequest && !options.pullRequests) out.pullRequestsSkipped++;
|
|
3312
|
+
else out.items.push(item);
|
|
3313
|
+
} catch (err) {
|
|
3314
|
+
if (!isRateLimited(err)) throw err;
|
|
3315
|
+
return {
|
|
3316
|
+
...out,
|
|
3317
|
+
more: true,
|
|
3318
|
+
rateLimited: true
|
|
3319
|
+
};
|
|
3320
|
+
}
|
|
3321
|
+
return out;
|
|
3322
|
+
}
|
|
3323
|
+
/**
|
|
3324
|
+
* The items one run looks at: with `--issues` those numbers, otherwise every issue of the repository oldest first, a
|
|
3325
|
+
* page at a time, past the `--after` cursor and on or after `--since`, until `--limit` are kept. Issue numbers rise with
|
|
3326
|
+
* creation, so the last number read is a cursor the next run can resume from. A rate limit ends the read with what it has.
|
|
3327
|
+
*/
|
|
3328
|
+
async function gather(api, options, isRateLimited) {
|
|
3329
|
+
if (options.issues) return named(api, options, isRateLimited);
|
|
3330
|
+
const out = {
|
|
3331
|
+
items: [],
|
|
3332
|
+
more: false,
|
|
3333
|
+
rateLimited: false,
|
|
3334
|
+
pullRequestsSkipped: 0
|
|
3335
|
+
};
|
|
3336
|
+
try {
|
|
3337
|
+
for (let page = 1;; page++) {
|
|
3338
|
+
const batch = await api.list(page);
|
|
3339
|
+
if (batch.length === 0) return out;
|
|
3340
|
+
for (const item of batch) {
|
|
3341
|
+
if (item.number <= options.after || before(item, options.since)) continue;
|
|
3342
|
+
if (item.isPullRequest && !options.pullRequests) {
|
|
3343
|
+
out.pullRequestsSkipped++;
|
|
3344
|
+
continue;
|
|
3345
|
+
}
|
|
3346
|
+
if (out.items.length >= options.limit) return {
|
|
3347
|
+
...out,
|
|
3348
|
+
more: true
|
|
3349
|
+
};
|
|
3350
|
+
out.items.push(item);
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
} catch (err) {
|
|
3354
|
+
if (!isRateLimited(err)) throw err;
|
|
3355
|
+
return {
|
|
3356
|
+
...out,
|
|
3357
|
+
more: true,
|
|
3358
|
+
rateLimited: true
|
|
3359
|
+
};
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
// src/probes/issue-types/kinds.ts
|
|
3363
|
+
/** The kind labels and the Type each one means (spec `tech-github-area-labels`, decision 3). */
|
|
3364
|
+
const DEFAULT_MAIN_KINDS = {
|
|
3365
|
+
bug: "Bug",
|
|
3366
|
+
enhancement: "Feature",
|
|
3367
|
+
chore: "Task"
|
|
3368
|
+
};
|
|
3369
|
+
/** The other kind labels, which mean Task only when none of the main ones is on the issue (issue #2494). */
|
|
3370
|
+
const DEFAULT_FALLBACK_KINDS = Object.fromEntries([
|
|
3371
|
+
"ci",
|
|
3372
|
+
"documentation",
|
|
3373
|
+
"refactor",
|
|
3374
|
+
"test",
|
|
3375
|
+
"performance",
|
|
3376
|
+
"dependencies"
|
|
3377
|
+
].map((label) => [label, "Task"]));
|
|
3378
|
+
const lowered = (table) => Object.fromEntries(Object.entries(table).map(([label, type]) => [label.toLowerCase(), type]));
|
|
3379
|
+
/** The tables a run uses: what `repo.labels` sets, else the defaults, table by table. */
|
|
3380
|
+
function resolveKinds(config) {
|
|
3381
|
+
return {
|
|
3382
|
+
main: config.kinds ? lowered(config.kinds) : DEFAULT_MAIN_KINDS,
|
|
3383
|
+
fallback: config.fallbackKinds ? lowered(config.fallbackKinds) : DEFAULT_FALLBACK_KINDS
|
|
3384
|
+
};
|
|
3385
|
+
}
|
|
3386
|
+
/** The Types the tables name that `known` (the organization's Types) lacks, each with the labels that use it. */
|
|
3387
|
+
function unknownTypes(kinds, known) {
|
|
3388
|
+
const byType = /* @__PURE__ */ new Map();
|
|
3389
|
+
for (const [label, type] of [...Object.entries(kinds.main), ...Object.entries(kinds.fallback)]) if (!known.has(type)) byType.set(type, [...byType.get(type) ?? [], label]);
|
|
3390
|
+
return [...byType].map(([type, labels]) => ({
|
|
3391
|
+
type,
|
|
3392
|
+
labels
|
|
3393
|
+
}));
|
|
3394
|
+
}
|
|
3395
|
+
// src/probes/issue-types/plan-type.ts
|
|
3396
|
+
/** The labels of an issue that `table` knows, each once (lower case), in the issue's order. */
|
|
3397
|
+
const matching = (labels, table) => [...new Set(labels.map((l) => l.toLowerCase()).filter((l) => Object.hasOwn(table, l)))];
|
|
3398
|
+
/**
|
|
3399
|
+
* The Type an issue gets from its kind labels. One that has a Type keeps it, whatever its labels say. Otherwise the main
|
|
3400
|
+
* table decides (`bug`, `enhancement`, `chore` by default), and only an issue with none of those looks at the fallback
|
|
3401
|
+
* table (`ci`, `documentation`, `refactor`, `test`, `performance`, `dependencies`, all Task by default; #2494). Labels
|
|
3402
|
+
* that point to one Type set it, however many they are; labels that point to two different Types are `ambiguous` and left
|
|
3403
|
+
* for a person (the spec's rule: the probe never picks between two kinds); one with no label in either table has no source.
|
|
3404
|
+
*/
|
|
3405
|
+
function planType(item, kinds) {
|
|
3406
|
+
if (item.type) return { skip: "typed" };
|
|
3407
|
+
for (const table of [kinds.main, kinds.fallback]) {
|
|
3408
|
+
const found = matching(item.labels, table);
|
|
3409
|
+
if (found.length === 0) continue;
|
|
3410
|
+
if (new Set(found.map((l) => table[l])).size > 1) return {
|
|
3411
|
+
skip: "ambiguous",
|
|
3412
|
+
labels: found
|
|
3413
|
+
};
|
|
3414
|
+
return { set: table[found[0]] };
|
|
3415
|
+
}
|
|
3416
|
+
return { skip: "no-kind-label" };
|
|
3417
|
+
}
|
|
3418
|
+
// src/probes/issue-types/report.ts
|
|
3419
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
3420
|
+
const GROUPS = [
|
|
3421
|
+
["project", "a project"],
|
|
3422
|
+
["milestone", "a milestone"],
|
|
3423
|
+
["priority", "a Priority"],
|
|
3424
|
+
["effort", "an Effort"]
|
|
3425
|
+
];
|
|
3426
|
+
/** The command the maintainer runs to continue, from the cursor. */
|
|
3427
|
+
function resumeCommand(options, cursor) {
|
|
3428
|
+
const flags = ["--after", String(cursor)];
|
|
3429
|
+
if (options.issues) flags.push("--issues", options.issues.join(","));
|
|
3430
|
+
if (options.since) flags.push("--since", options.since);
|
|
3431
|
+
flags.push("--limit", String(options.limit));
|
|
3432
|
+
if (options.repo) flags.push("--repo", options.repo);
|
|
3433
|
+
if (options.milestone) flags.push("--milestone", options.milestone);
|
|
3434
|
+
if (options.project) flags.push("--project", options.project);
|
|
3435
|
+
if (options.pullRequests) flags.push("--pull-requests");
|
|
3436
|
+
return `holocron probe github issue-types -- ${flags.join(" ")}`;
|
|
3437
|
+
}
|
|
3438
|
+
/** Prints the counts, what was left for a person, the lists of what is still missing and how to go on. */
|
|
3439
|
+
function reportBackfill(ctx, input) {
|
|
3440
|
+
const { tally, options, dryRun, more, rateLimited, fields } = input;
|
|
3441
|
+
const verb = dryRun ? "would be set" : "set";
|
|
3442
|
+
ctx.say({
|
|
3443
|
+
status: "heading",
|
|
3444
|
+
label: "Backfill"
|
|
3445
|
+
});
|
|
3446
|
+
const passed = tally.pullRequestsSkipped;
|
|
3447
|
+
ctx.say({
|
|
3448
|
+
status: "info",
|
|
3449
|
+
label: "summary",
|
|
3450
|
+
detail: `read ${plural(tally.examined, "item")}` + (tally.pullRequestsRead > 0 ? ` (${plural(tally.pullRequestsRead, "pull request")})` : "") + `; ${dryRun ? "would change" : "changed"} ${tally.changed}; passed over ${plural(passed, "pull request")}${passed > 0 ? " (give --pull-requests to include them)" : ""}; ${plural(tally.failed, "failure")}` + (more ? `; ${rateLimited ? "stopped by GitHub's rate limit" : `stopped at the limit of ${options.limit}`}, more remain` : "; the window is finished")
|
|
3451
|
+
});
|
|
3452
|
+
const types = Object.entries(tally.typeSet).map(([name, n]) => `${name} ${n}`).join(", ");
|
|
3453
|
+
ctx.say({
|
|
3454
|
+
status: "info",
|
|
3455
|
+
label: "Type",
|
|
3456
|
+
detail: `${types || "none"} ${verb}; ${tally.typed} already typed, ${tally.noKind} with no label that maps to a Type, ${tally.ambiguous.length} with two kind labels`
|
|
3457
|
+
});
|
|
3458
|
+
for (const a of tally.ambiguous) ctx.say({
|
|
3459
|
+
status: "info",
|
|
3460
|
+
label: `#${a.number}`,
|
|
3461
|
+
detail: `has ${a.labels.join(" and ")}: left for a person to choose`
|
|
3462
|
+
});
|
|
3463
|
+
ctx.say({
|
|
3464
|
+
status: "info",
|
|
3465
|
+
label: "area labels",
|
|
3466
|
+
detail: `added to ${plural(tally.areaLabelsAdded, "item")}`
|
|
3467
|
+
});
|
|
3468
|
+
for (const label of tally.missingAreaLabels) ctx.say({
|
|
3469
|
+
status: "info",
|
|
3470
|
+
label,
|
|
3471
|
+
detail: "wanted but the repository has no such label: run `holocron setup` first"
|
|
3472
|
+
});
|
|
3473
|
+
ctx.say({
|
|
3474
|
+
status: "info",
|
|
3475
|
+
label: "milestone",
|
|
3476
|
+
detail: `${verb} on ${tally.milestoneSet.parent + tally.milestoneSet.explicit} (${tally.milestoneSet.parent} from a parent, ${tally.milestoneSet.explicit} from --milestone)`
|
|
3477
|
+
});
|
|
3478
|
+
ctx.say({
|
|
3479
|
+
status: "info",
|
|
3480
|
+
label: "project",
|
|
3481
|
+
detail: `${plural(tally.projectSet, "issue")} ${dryRun ? "would be added" : "added"} from --project`
|
|
3482
|
+
});
|
|
3483
|
+
ctx.say({
|
|
3484
|
+
status: "heading",
|
|
3485
|
+
label: `Still lacking, among the ${plural(tally.examined, "item")} read${dryRun ? ", after the changes above" : ""}`
|
|
3486
|
+
});
|
|
3487
|
+
if (tally.skippedFields !== void 0) ctx.say({
|
|
3488
|
+
status: "fail",
|
|
3489
|
+
label: "Priority, Effort",
|
|
3490
|
+
detail: `NOT checked, so the lists below are incomplete: the token (github.issues) was refused reading the organization issue fields (${tally.skippedFields})`
|
|
3491
|
+
});
|
|
3492
|
+
for (const [group, noun] of GROUPS) {
|
|
3493
|
+
if (!(group === "project" || group === "milestone" || fields.includes(group))) continue;
|
|
3494
|
+
const items = tally.lacking[group];
|
|
3495
|
+
ctx.say({
|
|
3496
|
+
status: "info",
|
|
3497
|
+
label: `without ${noun}`,
|
|
3498
|
+
detail: `${items.length} of ${plural(tally.examined, "item")} read`
|
|
3499
|
+
});
|
|
3500
|
+
for (const item of items) ctx.say({
|
|
3501
|
+
status: "info",
|
|
3502
|
+
label: `#${item.number}`,
|
|
3503
|
+
detail: `${item.state}: ${item.title}`
|
|
3504
|
+
});
|
|
3505
|
+
}
|
|
3506
|
+
if (more && tally.last !== void 0) ctx.say({
|
|
3507
|
+
status: "info",
|
|
3508
|
+
label: "resume",
|
|
3509
|
+
detail: `${rateLimited ? "GitHub's rate limit stopped the run" : "the limit was reached"}; to continue: ${resumeCommand(options, tally.last)}`
|
|
3510
|
+
});
|
|
3511
|
+
else if (more) ctx.say({
|
|
3512
|
+
status: "info",
|
|
3513
|
+
label: "resume",
|
|
3514
|
+
detail: "GitHub's rate limit stopped the run before it finished one item; run it again later"
|
|
3515
|
+
});
|
|
3516
|
+
else ctx.say({
|
|
3517
|
+
status: "info",
|
|
3518
|
+
label: "resume",
|
|
3519
|
+
detail: "the window is finished"
|
|
3520
|
+
});
|
|
3521
|
+
}
|
|
3522
|
+
// src/probes/issue-types/backfill.ts
|
|
3523
|
+
/** The numbers the report is made of. */
|
|
3524
|
+
const emptyTally = () => ({
|
|
3525
|
+
examined: 0,
|
|
3526
|
+
pullRequestsSkipped: 0,
|
|
3527
|
+
typeSet: {},
|
|
3528
|
+
typed: 0,
|
|
3529
|
+
noKind: 0,
|
|
3530
|
+
ambiguous: [],
|
|
3531
|
+
areaLabelsAdded: 0,
|
|
3532
|
+
missingAreaLabels: /* @__PURE__ */ new Set(),
|
|
3533
|
+
milestoneSet: {
|
|
3534
|
+
parent: 0,
|
|
3535
|
+
explicit: 0
|
|
3536
|
+
},
|
|
3537
|
+
projectSet: 0,
|
|
3538
|
+
lacking: {
|
|
3539
|
+
project: [],
|
|
3540
|
+
milestone: [],
|
|
3541
|
+
priority: [],
|
|
3542
|
+
effort: []
|
|
3543
|
+
},
|
|
3544
|
+
failed: 0,
|
|
3545
|
+
changed: 0,
|
|
3546
|
+
pullRequestsRead: 0,
|
|
3547
|
+
last: void 0,
|
|
3548
|
+
skippedFields: void 0
|
|
3549
|
+
});
|
|
3550
|
+
/** How many changes the tally holds, to tell whether one item added any. */
|
|
3551
|
+
const changes = (t) => Object.values(t.typeSet).reduce((a, b) => a + b, 0) + t.areaLabelsAdded + t.milestoneSet.parent + t.milestoneSet.explicit + t.projectSet;
|
|
3552
|
+
/** How an issue is named in a row. */
|
|
3553
|
+
const labelOf = (item) => `#${item.number}`;
|
|
3554
|
+
/** Reads what the run needs before it starts: labels, the named milestone and project, the organization's issue fields. Says why and returns nothing when a name does not exist. */
|
|
3555
|
+
async function prepare(run, tally) {
|
|
3556
|
+
const { api, ctx, options } = run;
|
|
3557
|
+
const known = await api.typeNames();
|
|
3558
|
+
const unknown = unknownTypes(run.kinds, known);
|
|
3559
|
+
for (const { type, labels } of unknown) ctx.say({
|
|
3560
|
+
status: "fail",
|
|
3561
|
+
label: "Type",
|
|
3562
|
+
detail: `${type} (for ${labels.join(", ")}) is not an issue Type of this organization; its Types are ${[...known].join(", ") || "none"}`
|
|
3563
|
+
});
|
|
3564
|
+
if (unknown.length > 0) return void 0;
|
|
3565
|
+
const setup = {
|
|
3566
|
+
labelNames: await api.labelNames(),
|
|
3567
|
+
fields: []
|
|
3568
|
+
};
|
|
3569
|
+
if (options.milestone !== void 0) {
|
|
3570
|
+
setup.milestone = await api.milestoneNumber(options.milestone);
|
|
3571
|
+
if (setup.milestone === void 0) {
|
|
3572
|
+
ctx.say({
|
|
3573
|
+
status: "fail",
|
|
3574
|
+
label: "milestone",
|
|
3575
|
+
detail: `${options.milestone} is not a milestone of this repository`
|
|
3576
|
+
});
|
|
3577
|
+
return;
|
|
3578
|
+
}
|
|
3579
|
+
}
|
|
3580
|
+
if (options.project !== void 0) {
|
|
3581
|
+
setup.projectId = await api.projectId(options.project);
|
|
3582
|
+
if (setup.projectId === void 0) {
|
|
3583
|
+
ctx.say({
|
|
3584
|
+
status: "fail",
|
|
3585
|
+
label: "project",
|
|
3586
|
+
detail: `${options.project} is not a project of this organization`
|
|
3587
|
+
});
|
|
3588
|
+
return;
|
|
3589
|
+
}
|
|
3590
|
+
}
|
|
3591
|
+
const names = await api.fieldNames();
|
|
3592
|
+
if (typeof names === "string") tally.skippedFields = names;
|
|
3593
|
+
else setup.fields = ["priority", "effort"].filter((f) => names.has(f));
|
|
3594
|
+
return setup;
|
|
3595
|
+
}
|
|
3596
|
+
/** Does one issue or pull request; throws for a rate limit or a failed request, which the caller tells apart. */
|
|
3597
|
+
async function handle(run, setup, tally, item, projects) {
|
|
3598
|
+
const { api, ctx, areas, options } = run;
|
|
3599
|
+
const n = item.number;
|
|
3600
|
+
const wanted = item.isPullRequest ? areaLabelsForFiles(await api.files(n), areas.areas) : areaLabelsForTitle(item.title, areas.scopes);
|
|
3601
|
+
const have = new Set(item.labels.map((l) => l.toLowerCase()));
|
|
3602
|
+
const add = [];
|
|
3603
|
+
for (const label of wanted) {
|
|
3604
|
+
if (have.has(label.toLowerCase())) continue;
|
|
3605
|
+
if (setup.labelNames.has(label.toLowerCase())) add.push(label);
|
|
3606
|
+
else tally.missingAreaLabels.add(label);
|
|
3607
|
+
}
|
|
3608
|
+
if (add.length > 0) {
|
|
3609
|
+
await ctx.write(`add ${add.join(", ")} to ${labelOf(item)}`, () => api.addLabels(n, add));
|
|
3610
|
+
tally.areaLabelsAdded++;
|
|
3611
|
+
}
|
|
3612
|
+
if (item.isPullRequest) return;
|
|
3613
|
+
const type = planType(item, run.kinds);
|
|
3614
|
+
if ("set" in type) {
|
|
3615
|
+
await ctx.write(`set Type ${type.set} on ${labelOf(item)}`, () => api.setType(n, type.set));
|
|
3616
|
+
tally.typeSet[type.set] = (tally.typeSet[type.set] ?? 0) + 1;
|
|
3617
|
+
} else if (type.skip === "typed") tally.typed++;
|
|
3618
|
+
else if (type.skip === "no-kind-label") tally.noKind++;
|
|
3619
|
+
else tally.ambiguous.push({
|
|
3620
|
+
number: n,
|
|
3621
|
+
labels: type.labels
|
|
3622
|
+
});
|
|
3623
|
+
let milestone = item.milestone !== null;
|
|
3624
|
+
if (!milestone) {
|
|
3625
|
+
const parent = await api.parent(n);
|
|
3626
|
+
const fromParent = parent?.milestone;
|
|
3627
|
+
const target = fromParent ?? setup.milestone;
|
|
3628
|
+
if (target !== void 0) {
|
|
3629
|
+
const source = typeof fromParent === "number" ? "parent" : "explicit";
|
|
3630
|
+
const why = source === "parent" ? `from its parent #${parent?.number}` : `from --milestone ${options.milestone}`;
|
|
3631
|
+
await ctx.write(`set milestone on ${labelOf(item)} ${why}`, () => api.setMilestone(n, target));
|
|
3632
|
+
tally.milestoneSet[source]++;
|
|
3633
|
+
milestone = true;
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
3636
|
+
if (!milestone) tally.lacking.milestone.push(item);
|
|
3637
|
+
let onProject = projects.length > 0;
|
|
3638
|
+
if (!onProject && setup.projectId !== void 0) {
|
|
3639
|
+
const id = setup.projectId;
|
|
3640
|
+
await ctx.write(`add ${labelOf(item)} to project ${options.project}`, () => api.addToProject(id, item.nodeId));
|
|
3641
|
+
tally.projectSet++;
|
|
3642
|
+
onProject = true;
|
|
3643
|
+
}
|
|
3644
|
+
if (!onProject) tally.lacking.project.push(item);
|
|
3645
|
+
if (setup.fields.length > 0) {
|
|
3646
|
+
const values = await api.fieldValues(n);
|
|
3647
|
+
for (const field of setup.fields) if (!values.has(field)) tally.lacking[field].push(item);
|
|
3648
|
+
}
|
|
3649
|
+
}
|
|
3650
|
+
/**
|
|
3651
|
+
* The backfill of `holocron probe github issue-types` (spec `tech-github-area-labels`, rollout item 5): reads a window of
|
|
3652
|
+
* issues, and for each adds what it can derive and nothing else.
|
|
3653
|
+
*
|
|
3654
|
+
* - **Type** from the kind labels (`bug`, `enhancement`, `chore`, else Task for `ci`, `documentation`, `refactor`, `test`,
|
|
3655
|
+
* `performance`, `dependencies`); one that has a Type keeps it, one with two kind labels
|
|
3656
|
+
* is listed and left.
|
|
3657
|
+
* - **Area labels** from the title's scope, or, for a pull request with `--pull-requests`, from its changed files; only
|
|
3658
|
+
* added, and only when the label exists (`holocron setup` makes them).
|
|
3659
|
+
* - **Milestone** from the issue's parent, else `--milestone` for an issue in the window named by `--issues` or `--since`.
|
|
3660
|
+
* - **Project** from `--project` for such an issue that is on no project.
|
|
3661
|
+
*
|
|
3662
|
+
* Nothing is overwritten and no label is removed. Priority and Effort are never set, only listed when missing. Every
|
|
3663
|
+
* change goes through `ctx.write`, so `--dry-run` says `would ...` and writes nothing. A rate limit ends the run with the
|
|
3664
|
+
* cursor to resume from; any other failure is a row for that issue and the run goes on.
|
|
3665
|
+
*/
|
|
3666
|
+
async function runBackfill(run) {
|
|
3667
|
+
const { ctx, api, options } = run;
|
|
3668
|
+
const tally = emptyTally();
|
|
3669
|
+
const setup = await prepare(run, tally);
|
|
3670
|
+
if (!setup) return;
|
|
3671
|
+
const read = await gather(api, options, run.isRateLimited);
|
|
3672
|
+
tally.pullRequestsSkipped = read.pullRequestsSkipped;
|
|
3673
|
+
const projects = /* @__PURE__ */ new Map();
|
|
3674
|
+
const ids = read.items.filter((i) => !i.isPullRequest).map((i) => i.nodeId);
|
|
3675
|
+
try {
|
|
3676
|
+
for (let at = 0; at < ids.length; at += 100) for (const [id, found] of await api.projectsOf(ids.slice(at, at + 100))) projects.set(id, found);
|
|
3677
|
+
} catch (err) {
|
|
3678
|
+
if (!run.isRateLimited(err)) throw err;
|
|
3679
|
+
read.rateLimited = true;
|
|
3680
|
+
read.more = true;
|
|
3681
|
+
read.items.length = 0;
|
|
3682
|
+
}
|
|
3683
|
+
let stopped = read.rateLimited;
|
|
3684
|
+
for (const item of read.items) {
|
|
3685
|
+
const before = changes(tally);
|
|
3686
|
+
try {
|
|
3687
|
+
await handle(run, setup, tally, item, projects.get(item.nodeId) ?? []);
|
|
3688
|
+
if (changes(tally) > before) tally.changed++;
|
|
3689
|
+
} catch (err) {
|
|
3690
|
+
if (run.isRateLimited(err)) {
|
|
3691
|
+
stopped = true;
|
|
3692
|
+
break;
|
|
3693
|
+
}
|
|
3694
|
+
ctx.say({
|
|
3695
|
+
status: "fail",
|
|
3696
|
+
label: labelOf(item),
|
|
3697
|
+
detail: errorMessage(err)
|
|
3698
|
+
});
|
|
3699
|
+
tally.failed++;
|
|
3700
|
+
}
|
|
3701
|
+
tally.examined++;
|
|
3702
|
+
if (item.isPullRequest) tally.pullRequestsRead++;
|
|
3703
|
+
tally.last = item.number;
|
|
3704
|
+
}
|
|
3705
|
+
reportBackfill(ctx, {
|
|
3706
|
+
tally,
|
|
3707
|
+
options,
|
|
3708
|
+
dryRun: ctx.dryRun,
|
|
3709
|
+
more: read.more || stopped,
|
|
3710
|
+
rateLimited: stopped,
|
|
3711
|
+
fields: setup.fields
|
|
3712
|
+
});
|
|
3713
|
+
}
|
|
3714
|
+
const VALUED = [
|
|
3715
|
+
"--issues",
|
|
3716
|
+
"--since",
|
|
3717
|
+
"--after",
|
|
3718
|
+
"--limit",
|
|
3719
|
+
"--milestone",
|
|
3720
|
+
"--project",
|
|
3721
|
+
"--repo"
|
|
3722
|
+
];
|
|
3723
|
+
const INTEGER = /^\d+$/;
|
|
3724
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
3725
|
+
const MAX_RANGE = 1e3;
|
|
3726
|
+
const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
3727
|
+
/** `12,15,20-23` to `[12, 15, 20, 21, 22, 23]`, or `undefined` for text that is not such a list. */
|
|
3728
|
+
function numbersOf(text) {
|
|
3729
|
+
const out = [];
|
|
3730
|
+
for (const part of text.split(",")) {
|
|
3731
|
+
const [from, to, ...rest] = part.trim().split("-");
|
|
3732
|
+
if (rest.length > 0 || !INTEGER.test(from)) return void 0;
|
|
3733
|
+
const end = to === void 0 ? Number(from) : INTEGER.test(to) ? Number(to) : -1;
|
|
3734
|
+
if (end < Number(from) || end - Number(from) > MAX_RANGE) return void 0;
|
|
3735
|
+
for (let n = Number(from); n <= end; n++) out.push(n);
|
|
3736
|
+
}
|
|
3737
|
+
return out;
|
|
3738
|
+
}
|
|
3739
|
+
/** The words after `issue-types`, read into options, or the one thing wrong with them. */
|
|
3740
|
+
function parseArgs(args) {
|
|
3741
|
+
const options = {
|
|
3742
|
+
after: 0,
|
|
3743
|
+
limit: 100,
|
|
3744
|
+
pullRequests: false,
|
|
3745
|
+
repos: []
|
|
3746
|
+
};
|
|
3747
|
+
for (let i = 0; i < args.length; i++) {
|
|
3748
|
+
const flag = args[i];
|
|
3749
|
+
if (flag === "--pull-requests") {
|
|
3750
|
+
options.pullRequests = true;
|
|
3751
|
+
continue;
|
|
3752
|
+
}
|
|
3753
|
+
if (!VALUED.includes(flag)) return {
|
|
3754
|
+
ok: false,
|
|
3755
|
+
message: `unknown argument ${flag}`
|
|
3756
|
+
};
|
|
3757
|
+
const value = args[++i];
|
|
3758
|
+
if (value === void 0 || value.startsWith("--")) return {
|
|
3759
|
+
ok: false,
|
|
3760
|
+
message: `${flag} needs a value`
|
|
3761
|
+
};
|
|
3762
|
+
if (flag === "--issues") {
|
|
3763
|
+
const issues = numbersOf(value);
|
|
3764
|
+
if (!issues) return {
|
|
3765
|
+
ok: false,
|
|
3766
|
+
message: `--issues takes numbers and ranges such as 12,15,20-25, not ${value}`
|
|
3767
|
+
};
|
|
3768
|
+
options.issues = issues;
|
|
3769
|
+
} else if (flag === "--since") {
|
|
3770
|
+
if (!DAY.test(value)) return {
|
|
3771
|
+
ok: false,
|
|
3772
|
+
message: `--since takes a day as YYYY-MM-DD, not ${value}`
|
|
3773
|
+
};
|
|
3774
|
+
options.since = value;
|
|
3775
|
+
} else if (flag === "--after") {
|
|
3776
|
+
if (!INTEGER.test(value)) return {
|
|
3777
|
+
ok: false,
|
|
3778
|
+
message: `--after takes a whole number, not ${value}`
|
|
3779
|
+
};
|
|
3780
|
+
options.after = Number(value);
|
|
3781
|
+
} else if (flag === "--limit") {
|
|
3782
|
+
if (!INTEGER.test(value) || Number(value) < 1) return {
|
|
3783
|
+
ok: false,
|
|
3784
|
+
message: `--limit takes a whole number of at least 1, not ${value}`
|
|
3785
|
+
};
|
|
3786
|
+
options.limit = Number(value);
|
|
3787
|
+
} else if (flag === "--repo") {
|
|
3788
|
+
if (!REPOSITORY.test(value)) return {
|
|
3789
|
+
ok: false,
|
|
3790
|
+
message: `--repo takes owner/name, not ${value}`
|
|
3791
|
+
};
|
|
3792
|
+
if (!options.repos.includes(value)) options.repos.push(value);
|
|
3793
|
+
} else if (flag === "--milestone") options.milestone = value;
|
|
3794
|
+
else options.project = value;
|
|
3795
|
+
}
|
|
3796
|
+
if ((options.milestone || options.project) && !options.issues && !options.since) return {
|
|
3797
|
+
ok: false,
|
|
3798
|
+
message: "--milestone and --project need a window to apply to: name it with --issues or --since"
|
|
3799
|
+
};
|
|
3800
|
+
if (options.repos.length > 1 && (options.issues || options.after > 0)) return {
|
|
3801
|
+
ok: false,
|
|
3802
|
+
message: "--issues and --after are numbers of one repository, so they cannot go with more than one --repo"
|
|
3803
|
+
};
|
|
3804
|
+
return {
|
|
3805
|
+
ok: true,
|
|
3806
|
+
options
|
|
3807
|
+
};
|
|
3808
|
+
}
|
|
3809
|
+
// src/probes/issue-types/repo-areas.ts
|
|
3810
|
+
/** Where a repository without a `package.json` declares `repo.labels` (the `repo` area file, spec `tech-holocron-directory`). */
|
|
3811
|
+
const AREA_FILE_JSON = ".holocron/repo.json";
|
|
3812
|
+
const AREA_FILE_TS = ".holocron/repo.ts";
|
|
3813
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3814
|
+
/** `repo.labels.areas` and `scopes` as the mapping reads them, or `undefined` for a shape it cannot use. */
|
|
3815
|
+
function areaMap(labels) {
|
|
3816
|
+
if (!isRecord(labels) || !isRecord(labels.areas) || Object.keys(labels.areas).length === 0) return void 0;
|
|
3817
|
+
const areas = labels.areas;
|
|
3818
|
+
if (!Object.values(areas).every((p) => Array.isArray(p) && p.every((x) => typeof x === "string"))) return void 0;
|
|
3819
|
+
const scopes = isRecord(labels.scopes) ? labels.scopes : {};
|
|
3820
|
+
if (!Object.values(scopes).every((a) => typeof a === "string")) return void 0;
|
|
3821
|
+
return {
|
|
3822
|
+
areas,
|
|
3823
|
+
scopes
|
|
3824
|
+
};
|
|
3825
|
+
}
|
|
3826
|
+
const none = (detail) => ({
|
|
3827
|
+
areas: {},
|
|
3828
|
+
row: {
|
|
3829
|
+
status: "info",
|
|
3830
|
+
label: "area labels",
|
|
3831
|
+
detail
|
|
3832
|
+
}
|
|
3833
|
+
});
|
|
3834
|
+
/**
|
|
3835
|
+
* The area labels another repository declares (spec `tech-backfill-config-mapping`), read from its own
|
|
3836
|
+
* `.holocron/repo.json`. A `.holocron/repo.ts` is TypeScript, which only Sentinel's remote config reader evaluates and a
|
|
3837
|
+
* plugin cannot reach, so that repository gets a skipped row and no area step; so does one with no declaration. Never
|
|
3838
|
+
* throws for a missing or unusable file: the Type step of the repository still runs.
|
|
3839
|
+
*/
|
|
3840
|
+
async function readRepoAreas(api) {
|
|
3841
|
+
const json = await api.readFile(AREA_FILE_JSON);
|
|
3842
|
+
if (json !== null) {
|
|
3843
|
+
let parsed;
|
|
3844
|
+
try {
|
|
3845
|
+
parsed = JSON.parse(json);
|
|
3846
|
+
} catch (err) {
|
|
3847
|
+
return {
|
|
3848
|
+
areas: {},
|
|
3849
|
+
row: {
|
|
3850
|
+
status: "fail",
|
|
3851
|
+
label: "area labels",
|
|
3852
|
+
detail: `${AREA_FILE_JSON} is not JSON (${errorMessage(err)})`
|
|
3853
|
+
}
|
|
3854
|
+
};
|
|
3855
|
+
}
|
|
3856
|
+
const found = areaMap(isRecord(parsed) ? parsed.labels : void 0);
|
|
3857
|
+
return found ? {
|
|
3858
|
+
areas: found,
|
|
3859
|
+
row: {
|
|
3860
|
+
status: "info",
|
|
3861
|
+
label: "area labels",
|
|
3862
|
+
detail: `read from ${AREA_FILE_JSON}`
|
|
3863
|
+
}
|
|
3864
|
+
} : none(`skipped: ${AREA_FILE_JSON} declares no usable \`labels.areas\`, so no area labels are added`);
|
|
3865
|
+
}
|
|
3866
|
+
if (await api.readFile(AREA_FILE_TS) !== null) return none(`skipped: its areas are in ${AREA_FILE_TS}, which is TypeScript the probe cannot evaluate (only Sentinel's config reader does); no area labels are added`);
|
|
3867
|
+
return none(`skipped: it has no ${AREA_FILE_JSON} or ${AREA_FILE_TS}, so no area labels are added`);
|
|
3868
|
+
}
|
|
3869
|
+
// src/probes/issue-types/issue-types.ts
|
|
3870
|
+
/**
|
|
3871
|
+
* `holocron probe github issue-types`: the one-time backfill of spec `tech-github-area-labels` (rollout item 5), a writer
|
|
3872
|
+
* the maintainer runs. It sets the Type of an issue from its kind labels, adds `area:<name>` labels, fills a milestone
|
|
3873
|
+
* and a project where a source exists, and ends with the list of every issue it read that still lacks a project, a
|
|
3874
|
+
* milestone, a Priority or an Effort. See `backfill.ts` for the rules. Run it with `--dry-run` first.
|
|
3875
|
+
*
|
|
3876
|
+
* The kind labels and the repositories come from `repo.labels` (`kinds`, `fallbackKinds`, `repos`) and `--repo`, and a
|
|
3877
|
+
* repository other than this one has its area labels read from its own `.holocron/repo.json` (spec
|
|
3878
|
+
* `tech-backfill-config-mapping`).
|
|
3879
|
+
*
|
|
3880
|
+
* Not verified against the live API: writing an issue's Type, adding an issue to a project, reading the organization's
|
|
3881
|
+
* issue Types, and the endpoints that read an issue's field values and parent.
|
|
3882
|
+
*/
|
|
3883
|
+
function issueTypesProbe(ctx) {
|
|
3884
|
+
return {
|
|
3885
|
+
summary: "Backfill issues: set Type from the kind labels, add area labels, fill milestone and project where a source exists, and list what still lacks a project, milestone, Priority or Effort. Never overwrites a value. Run with --dry-run first.",
|
|
3886
|
+
writes: true,
|
|
3887
|
+
async run(probe) {
|
|
3888
|
+
const parsed = parseArgs(probe.args ?? []);
|
|
3889
|
+
if (!parsed.ok) {
|
|
3890
|
+
probe.say({
|
|
3891
|
+
status: "fail",
|
|
3892
|
+
label: "arguments",
|
|
3893
|
+
detail: parsed.message
|
|
3894
|
+
});
|
|
3895
|
+
return;
|
|
3896
|
+
}
|
|
3897
|
+
const named = parsed.options.repos;
|
|
3898
|
+
const repos = named.length > 0 ? named : ctx.config.repos?.length ? ctx.config.repos : [ctx.repo];
|
|
3899
|
+
const kinds = resolveKinds(ctx.config);
|
|
3900
|
+
for (const repo of repos) {
|
|
3901
|
+
if (repos.length > 1) probe.say({
|
|
3902
|
+
status: "heading",
|
|
3903
|
+
label: repo
|
|
3904
|
+
});
|
|
3905
|
+
try {
|
|
3906
|
+
const api = ctx.makeApi(repo);
|
|
3907
|
+
let areas = ctx.config;
|
|
3908
|
+
if (repo.toLowerCase() !== ctx.repo.toLowerCase()) {
|
|
3909
|
+
const found = await readRepoAreas(api);
|
|
3910
|
+
probe.say(found.row);
|
|
3911
|
+
areas = found.areas;
|
|
3912
|
+
}
|
|
3913
|
+
await runBackfill({
|
|
3914
|
+
ctx: probe,
|
|
3915
|
+
api,
|
|
3916
|
+
options: {
|
|
3917
|
+
...parsed.options,
|
|
3918
|
+
repo: named.length > 0 || repos.length > 1 ? repo : void 0
|
|
3919
|
+
},
|
|
3920
|
+
areas,
|
|
3921
|
+
kinds,
|
|
3922
|
+
isRateLimited
|
|
3923
|
+
});
|
|
3924
|
+
} catch (err) {
|
|
3925
|
+
probe.say({
|
|
3926
|
+
status: "fail",
|
|
3927
|
+
label: "issue-types",
|
|
3928
|
+
detail: errorMessage(err)
|
|
3929
|
+
});
|
|
3930
|
+
}
|
|
3931
|
+
}
|
|
3932
|
+
}
|
|
3933
|
+
};
|
|
3934
|
+
}
|
|
3935
|
+
// src/probes/token/expectations.ts
|
|
3936
|
+
/** The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI. */
|
|
3937
|
+
function everywhere(rules) {
|
|
3938
|
+
return { permissions: {
|
|
3939
|
+
local: rules,
|
|
3940
|
+
dev: rules,
|
|
3941
|
+
ci: rules
|
|
3942
|
+
} };
|
|
3943
|
+
}
|
|
3944
|
+
/**
|
|
3945
|
+
* `rules` everywhere, plus a permission only a person at a terminal needs: `local` and `dev` must have `held`, and `ci`
|
|
3946
|
+
* must not have `ci` (a workflow's token needs no more than it uses).
|
|
3947
|
+
*/
|
|
3948
|
+
function withoutInCi(rules, held, ci) {
|
|
3949
|
+
return { permissions: {
|
|
3950
|
+
local: {
|
|
3951
|
+
...rules,
|
|
3952
|
+
...held
|
|
3953
|
+
},
|
|
3954
|
+
dev: {
|
|
3955
|
+
...rules,
|
|
3956
|
+
...held
|
|
3957
|
+
},
|
|
3958
|
+
ci: {
|
|
3959
|
+
...rules,
|
|
3960
|
+
...ci
|
|
3961
|
+
}
|
|
3962
|
+
} };
|
|
3963
|
+
}
|
|
3964
|
+
/**
|
|
3965
|
+
* What each GitHub token is meant to carry, by its `envName`, the same as the GitHub tokens table in
|
|
3966
|
+
* `docs/src/content/docs/tokens.mdx`. This is the plugin's `tokens` declaration, read through `tokenExpectations()`;
|
|
3967
|
+
* change it and that table together.
|
|
3968
|
+
*
|
|
3969
|
+
* Every token CI uses (the `sync-repo`, `sync-secrets`, `reconcile-projects` and `check-tokens` workflows read all of
|
|
3970
|
+
* them) is declared with the same permissions in `local`, `dev` and `ci`, so the probe checks that a `ci` token is no
|
|
3971
|
+
* broader than its `dev` one rather than assuming a split the workflows do not allow. The release token is held by CI
|
|
3972
|
+
* only, so it has no `local` or `dev` entry. A narrow token must not reach administration or secrets; the admin token
|
|
3973
|
+
* must not reach organization secrets (that is `HOLOCRON_SECRETS_TOKEN`'s alone).
|
|
3974
|
+
*/
|
|
3975
|
+
const EXPECTED = {
|
|
3976
|
+
HOLOCRON_READ_TOKEN: everywhere({
|
|
3977
|
+
contents: "required",
|
|
3978
|
+
actions: "required",
|
|
3979
|
+
administration: "absent",
|
|
3980
|
+
secrets: "absent",
|
|
3981
|
+
environments: "absent"
|
|
3982
|
+
}),
|
|
3983
|
+
HOLOCRON_ISSUES_TOKEN: everywhere({
|
|
3984
|
+
issues: "required",
|
|
3985
|
+
administration: "absent",
|
|
3986
|
+
secrets: "absent",
|
|
3987
|
+
environments: "absent"
|
|
3988
|
+
}),
|
|
3989
|
+
HOLOCRON_SYNC_TOKEN: everywhere({
|
|
3990
|
+
actions: "required",
|
|
3991
|
+
contents: "required",
|
|
3992
|
+
"pull-requests": "required",
|
|
3993
|
+
administration: "absent",
|
|
3994
|
+
secrets: "absent"
|
|
3995
|
+
}),
|
|
3996
|
+
HOLOCRON_RELEASE_TOKEN: { permissions: { ci: {
|
|
3997
|
+
contents: "required",
|
|
3998
|
+
issues: "required",
|
|
3999
|
+
"pull-requests": "required",
|
|
4000
|
+
administration: "absent",
|
|
4001
|
+
secrets: "absent"
|
|
4002
|
+
} } },
|
|
4003
|
+
HOLOCRON_ADMIN_TOKEN: withoutInCi({
|
|
4004
|
+
administration: "required",
|
|
4005
|
+
secrets: "required",
|
|
4006
|
+
environments: "required",
|
|
4007
|
+
issues: "required",
|
|
4008
|
+
"custom-properties": "required",
|
|
4009
|
+
"actions-variables": "required",
|
|
4010
|
+
"org-secrets": "absent"
|
|
4011
|
+
}, { webhooks: "required" }, { webhooks: "absent" }),
|
|
4012
|
+
HOLOCRON_SECRETS_TOKEN: everywhere({
|
|
4013
|
+
"org-secrets": "required",
|
|
4014
|
+
administration: "absent"
|
|
4015
|
+
}),
|
|
4016
|
+
HOLOCRON_DEPLOY_TOKEN: everywhere({
|
|
4017
|
+
pages: "required",
|
|
4018
|
+
administration: "required",
|
|
4019
|
+
secrets: "absent",
|
|
4020
|
+
"org-secrets": "absent"
|
|
4021
|
+
}),
|
|
4022
|
+
HOLOCRON_USER_SYNC_TOKEN: everywhere({
|
|
4023
|
+
"user-sync-contents": "required",
|
|
4024
|
+
administration: "absent",
|
|
4025
|
+
secrets: "absent"
|
|
4026
|
+
}),
|
|
4027
|
+
HOLOCRON_ORG_TOKEN: withoutInCi({
|
|
4028
|
+
administration: "required",
|
|
4029
|
+
"org-members": "required",
|
|
4030
|
+
"org-variables": "required",
|
|
4031
|
+
"org-secrets": "absent"
|
|
4032
|
+
}, { "org-webhooks": "required" }, { "org-webhooks": "absent" })
|
|
4033
|
+
};
|
|
4034
|
+
// src/tokens.ts
|
|
4035
|
+
/** Adds what a layer's token must and must not be able to do (`EXPECTED`, by `envName`) to a token. */
|
|
4036
|
+
function declared(token) {
|
|
4037
|
+
return {
|
|
4038
|
+
...token,
|
|
4039
|
+
expect: EXPECTED[token.envName]
|
|
4040
|
+
};
|
|
4041
|
+
}
|
|
4042
|
+
/**
|
|
4043
|
+
* Every token this plugin takes, for `holocron doctor tokens`, with what each layer's token must and must not be able
|
|
4044
|
+
* to do. The release token is `optional`: only CI's release workflow reads it (from the org secret), so a development
|
|
4045
|
+
* environment has no reason to hold it.
|
|
4046
|
+
*/
|
|
4047
|
+
const tokens = [
|
|
4048
|
+
declared(resolveReadToken.token),
|
|
4049
|
+
declared(resolveIssuesToken.token),
|
|
4050
|
+
declared(resolveSyncToken.token),
|
|
4051
|
+
declared({
|
|
4052
|
+
...resolveReleaseToken.token,
|
|
4053
|
+
optional: true
|
|
4054
|
+
}),
|
|
4055
|
+
declared(resolveAdminToken.token),
|
|
4056
|
+
declared(resolveSecretsToken.token),
|
|
4057
|
+
declared(resolveDeployToken.token),
|
|
4058
|
+
declared(resolveUserSyncToken.token),
|
|
4059
|
+
declared(resolveOrgToken.token)
|
|
4060
|
+
];
|
|
4061
|
+
// src/probes/token/parse-token-args.ts
|
|
4062
|
+
/** Reads the words after the probe name: `--layer <word>` and `--token-name <VAR>`, in either spelling. */
|
|
4063
|
+
function parseTokenArgs(args) {
|
|
4064
|
+
let layer;
|
|
4065
|
+
let tokenName;
|
|
4066
|
+
for (let i = 0; i < args.length; i++) {
|
|
4067
|
+
const arg = args[i];
|
|
4068
|
+
if (arg === "--layer") layer = args[++i];
|
|
4069
|
+
else if (arg.startsWith("--layer=")) layer = arg.slice(8);
|
|
4070
|
+
else if (arg === "--token-name") tokenName = args[++i];
|
|
4071
|
+
else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
|
|
4072
|
+
}
|
|
4073
|
+
return {
|
|
4074
|
+
...layer ? { layer } : {},
|
|
4075
|
+
...tokenName ? { tokenName } : {}
|
|
4076
|
+
};
|
|
4077
|
+
}
|
|
4078
|
+
// src/probes/token/permissions.ts
|
|
4079
|
+
/**
|
|
4080
|
+
* Every permission the GitHub plugin's tokens are declared against, by the name the declaration uses, with one read
|
|
4081
|
+
* that needs it. A read proves the token can see the area, not that it can write to it: GitHub exposes no list of a
|
|
4082
|
+
* fine-grained token's permissions, so the write half of `read/write` is taken from the permission table in
|
|
4083
|
+
* `docs/src/content/docs/tokens.mdx`. On a public repository the `contents`, `actions`, `issues`, `pull-requests` and `environments`
|
|
4084
|
+
* reads succeed for any token, so only the other permissions can prove a permission absent. Names with more than one
|
|
4085
|
+
* word are hyphenated, not underscored: `holocron probe docs tokens` strips `_` (Markdown emphasis) from a table cell
|
|
4086
|
+
* before it compares the id with the declaration.
|
|
4087
|
+
*/
|
|
4088
|
+
const PERMISSIONS = {
|
|
4089
|
+
contents: {
|
|
4090
|
+
label: "Contents",
|
|
4091
|
+
path: "/repos/{r}/contents",
|
|
4092
|
+
publicRead: true
|
|
4093
|
+
},
|
|
4094
|
+
actions: {
|
|
4095
|
+
label: "Actions",
|
|
4096
|
+
path: "/repos/{r}/actions/runs?per_page=1",
|
|
4097
|
+
publicRead: true
|
|
4098
|
+
},
|
|
4099
|
+
issues: {
|
|
4100
|
+
label: "Issues",
|
|
4101
|
+
path: "/repos/{r}/issues?per_page=1",
|
|
4102
|
+
publicRead: true
|
|
4103
|
+
},
|
|
4104
|
+
"pull-requests": {
|
|
4105
|
+
label: "Pull requests",
|
|
4106
|
+
path: "/repos/{r}/pulls?per_page=1",
|
|
4107
|
+
publicRead: true
|
|
4108
|
+
},
|
|
4109
|
+
administration: {
|
|
4110
|
+
label: "Administration",
|
|
4111
|
+
path: "/repos/{r}/actions/permissions"
|
|
4112
|
+
},
|
|
4113
|
+
secrets: {
|
|
4114
|
+
label: "Secrets",
|
|
4115
|
+
path: "/repos/{r}/actions/secrets?per_page=1"
|
|
4116
|
+
},
|
|
4117
|
+
environments: {
|
|
4118
|
+
label: "Environments",
|
|
4119
|
+
path: "/repos/{r}/environments?per_page=1",
|
|
4120
|
+
publicRead: true
|
|
4121
|
+
},
|
|
4122
|
+
"actions-variables": {
|
|
4123
|
+
label: "Variables",
|
|
4124
|
+
path: "/repos/{r}/actions/variables?per_page=1"
|
|
4125
|
+
},
|
|
4126
|
+
"custom-properties": {
|
|
4127
|
+
label: "Custom properties",
|
|
4128
|
+
path: "/repos/{r}/properties/values"
|
|
4129
|
+
},
|
|
4130
|
+
pages: {
|
|
4131
|
+
label: "Pages",
|
|
4132
|
+
path: "/repos/{r}/pages"
|
|
4133
|
+
},
|
|
4134
|
+
webhooks: {
|
|
4135
|
+
label: "Webhooks",
|
|
4136
|
+
path: "/repos/{r}/hooks?per_page=1"
|
|
4137
|
+
},
|
|
4138
|
+
"org-webhooks": {
|
|
4139
|
+
label: "Organization: Webhooks",
|
|
4140
|
+
path: "/orgs/{o}/hooks?per_page=1"
|
|
4141
|
+
},
|
|
4142
|
+
"org-members": {
|
|
4143
|
+
label: "Organization: Members",
|
|
4144
|
+
path: "/orgs/{o}/members?per_page=1"
|
|
4145
|
+
},
|
|
4146
|
+
"org-variables": {
|
|
4147
|
+
label: "Organization: Variables",
|
|
4148
|
+
path: "/orgs/{o}/actions/variables?per_page=1"
|
|
4149
|
+
},
|
|
4150
|
+
"org-secrets": {
|
|
4151
|
+
label: "Organization: Secrets",
|
|
4152
|
+
path: "/orgs/{o}/actions/secrets?per_page=1"
|
|
4153
|
+
},
|
|
4154
|
+
"issue-fields": {
|
|
4155
|
+
label: "Organization: Issue fields",
|
|
4156
|
+
path: "/orgs/{o}/issue-fields"
|
|
4157
|
+
},
|
|
4158
|
+
"issue-types": {
|
|
4159
|
+
label: "Organization: Issue types",
|
|
4160
|
+
path: "/orgs/{o}/issue-types"
|
|
4161
|
+
},
|
|
4162
|
+
"user-sync-contents": {
|
|
4163
|
+
label: "Contents (.github-private)",
|
|
4164
|
+
path: "/repos/{o}/.github-private/contents"
|
|
4165
|
+
}
|
|
4166
|
+
};
|
|
4167
|
+
// src/probes/token/token.ts
|
|
4168
|
+
/** The token checked when none is named: the one the plugin reads with by default. */
|
|
4169
|
+
const DEFAULT_TOKEN = "HOLOCRON_READ_TOKEN";
|
|
4170
|
+
/** Does one GET with the token; the response headers are returned for the caller that wants them. */
|
|
4171
|
+
async function get(ctx, token, path) {
|
|
4172
|
+
return ctx.fetch(`${ctx.baseUrl}${path}`, { headers: {
|
|
4173
|
+
authorization: `Bearer ${token}`,
|
|
4174
|
+
accept: "application/vnd.github+json",
|
|
4175
|
+
"x-github-api-version": "2022-11-28",
|
|
4176
|
+
"user-agent": "holocron-probe"
|
|
4177
|
+
} });
|
|
4178
|
+
}
|
|
4179
|
+
/**
|
|
4180
|
+
* One read for one permission. GitHub answers a token without the permission with a 403, or a 404 for something it will
|
|
4181
|
+
* not admit exists, so both are `none`; a 2xx is `has`. Any other status, or a request that did not go through, is an
|
|
4182
|
+
* `error`, which is a failure whatever the layer expects.
|
|
4183
|
+
*/
|
|
4184
|
+
async function reach(ctx, token, permission) {
|
|
4185
|
+
const [owner = ""] = ctx.repo.split("/");
|
|
4186
|
+
const path = PERMISSIONS[permission].path.replaceAll("{r}", ctx.repo).replaceAll("{o}", owner);
|
|
4187
|
+
try {
|
|
4188
|
+
const res = await get(ctx, token, path);
|
|
4189
|
+
if (res.ok) return {
|
|
4190
|
+
kind: "has",
|
|
4191
|
+
detail: `read ${path.split("?")[0]}`
|
|
4192
|
+
};
|
|
4193
|
+
if (res.status === 403 || res.status === 404) return {
|
|
4194
|
+
kind: "none",
|
|
4195
|
+
detail: `no access (${res.status})`
|
|
4196
|
+
};
|
|
4197
|
+
return {
|
|
4198
|
+
kind: "error",
|
|
4199
|
+
detail: `${res.status} ${res.statusText}`.trim()
|
|
4200
|
+
};
|
|
4201
|
+
} catch (err) {
|
|
4202
|
+
return {
|
|
4203
|
+
kind: "error",
|
|
4204
|
+
detail: errorMessage(err)
|
|
4205
|
+
};
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
4208
|
+
/**
|
|
4209
|
+
* One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
|
|
4210
|
+
* judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
|
|
4211
|
+
* permission that is rightly absent is a bare `ok`.
|
|
4212
|
+
*/
|
|
4213
|
+
function rowFor({ label, permission, outcome }, rule) {
|
|
4214
|
+
if (outcome.kind === "error") return {
|
|
4215
|
+
status: "fail",
|
|
4216
|
+
label,
|
|
4217
|
+
detail: outcome.detail
|
|
4218
|
+
};
|
|
4219
|
+
const has = outcome.kind === "has";
|
|
4220
|
+
if (rule === "required") return {
|
|
4221
|
+
status: has ? "ok" : "fail",
|
|
4222
|
+
label,
|
|
4223
|
+
detail: outcome.detail
|
|
4224
|
+
};
|
|
4225
|
+
if (rule === "absent" && has && PERMISSIONS[permission].publicRead) return {
|
|
4226
|
+
status: "info",
|
|
4227
|
+
label,
|
|
4228
|
+
detail: `${outcome.detail}, which any token can on a public repository: not proof either way`
|
|
4229
|
+
};
|
|
4230
|
+
if (rule === "absent") return has ? {
|
|
4231
|
+
status: "fail",
|
|
4232
|
+
label,
|
|
4233
|
+
detail: outcome.detail
|
|
4234
|
+
} : {
|
|
4235
|
+
status: "ok",
|
|
4236
|
+
label
|
|
4237
|
+
};
|
|
4238
|
+
return {
|
|
4239
|
+
status: has ? "ok" : "info",
|
|
4240
|
+
label,
|
|
4241
|
+
detail: outcome.detail
|
|
4242
|
+
};
|
|
4243
|
+
}
|
|
655
4244
|
/**
|
|
656
|
-
* `
|
|
657
|
-
*
|
|
658
|
-
*
|
|
4245
|
+
* The `token` probe: `holocron probe github token` tries each permission Holocron uses with one of the plugin's nine
|
|
4246
|
+
* tokens and reports which ones the token reaches. It only reads (one GET per permission), so it changes nothing, and a
|
|
4247
|
+
* read proves the token can see an area, not that it can write there.
|
|
659
4248
|
*
|
|
660
|
-
*
|
|
661
|
-
*
|
|
662
|
-
*
|
|
663
|
-
*
|
|
4249
|
+
* GitHub lists scopes only for a classic token (the `X-OAuth-Scopes` header on any response), so a classic token's scopes
|
|
4250
|
+
* are shown. A fine-grained token has no list, so the permissions are found by trying them; the first row says which kind
|
|
4251
|
+
* was read. With `--environment <layer>` the CLI runs the probe once for each token the Environment holds and hands it
|
|
4252
|
+
* `--token-name <envName>` (and the token itself as `cliToken`); by hand, `--token-name` picks which token the plugin
|
|
4253
|
+
* resolves (default `HOLOCRON_READ_TOKEN`).
|
|
4254
|
+
*
|
|
4255
|
+
* With no layer the token is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
|
|
4256
|
+
* `local`), the results are judged against what that token is meant to carry in that layer (the plugin's `tokens`
|
|
4257
|
+
* declaration, read with `tokenExpectations()`) and shown in two groups, what it should have and what it should not,
|
|
4258
|
+
* where a missing or extra permission fails.
|
|
664
4259
|
*/
|
|
4260
|
+
function tokenProbe(ctx) {
|
|
4261
|
+
return {
|
|
4262
|
+
summary: "Try each GitHub permission Holocron uses (contents, actions, issues, administration, secrets, ...) with one of the plugin's tokens and report which it reaches; for a ci or dev Environment, check it against what that layer should carry. Read-only.",
|
|
4263
|
+
writes: false,
|
|
4264
|
+
acceptsToken: true,
|
|
4265
|
+
async run(probe) {
|
|
4266
|
+
const { layer, tokenName } = parseTokenArgs(probe.args ?? []);
|
|
4267
|
+
const envName = tokenName ?? DEFAULT_TOKEN;
|
|
4268
|
+
const token = ctx.resolve(envName);
|
|
4269
|
+
if (token === void 0) {
|
|
4270
|
+
probe.say({
|
|
4271
|
+
status: "fail",
|
|
4272
|
+
label: envName,
|
|
4273
|
+
detail: `not a GitHub token; use one of: ${ctx.tokenNames.join(", ")}`
|
|
4274
|
+
});
|
|
4275
|
+
return;
|
|
4276
|
+
}
|
|
4277
|
+
probe.secret(token);
|
|
4278
|
+
let identity;
|
|
4279
|
+
try {
|
|
4280
|
+
identity = await get(ctx, token, "/user");
|
|
4281
|
+
} catch (err) {
|
|
4282
|
+
probe.say({
|
|
4283
|
+
status: "fail",
|
|
4284
|
+
label: "token",
|
|
4285
|
+
detail: errorMessage(err)
|
|
4286
|
+
});
|
|
4287
|
+
return;
|
|
4288
|
+
}
|
|
4289
|
+
if (identity.status === 401) {
|
|
4290
|
+
probe.say({
|
|
4291
|
+
status: "fail",
|
|
4292
|
+
label: "token",
|
|
4293
|
+
detail: "rejected by GitHub (401): expired, revoked or not a token"
|
|
4294
|
+
});
|
|
4295
|
+
return;
|
|
4296
|
+
}
|
|
4297
|
+
const scopes = identity.headers.get("x-oauth-scopes");
|
|
4298
|
+
probe.say({
|
|
4299
|
+
status: "ok",
|
|
4300
|
+
label: "token",
|
|
4301
|
+
detail: scopes === null ? "fine-grained (GitHub lists no permissions for one, so each is tried with a read)" : `classic (scopes: ${scopes === "" ? "none" : scopes}); each permission is also tried with a read`
|
|
4302
|
+
});
|
|
4303
|
+
const declared = layer ? tokenExpectations(tokens, {
|
|
4304
|
+
layer,
|
|
4305
|
+
envName
|
|
4306
|
+
})[0] : void 0;
|
|
4307
|
+
if (layer && !declared) probe.say({
|
|
4308
|
+
status: "info",
|
|
4309
|
+
label: layer,
|
|
4310
|
+
detail: "no expectations are declared for this token there, so it is only described"
|
|
4311
|
+
});
|
|
4312
|
+
const rules = declared?.rules ?? {};
|
|
4313
|
+
const names = declared ? Object.keys(rules) : Object.keys(PERMISSIONS);
|
|
4314
|
+
const tried = [];
|
|
4315
|
+
for (const permission of names) tried.push({
|
|
4316
|
+
label: PERMISSIONS[permission].label,
|
|
4317
|
+
permission,
|
|
4318
|
+
outcome: await reach(ctx, token, permission)
|
|
4319
|
+
});
|
|
4320
|
+
if (!declared) {
|
|
4321
|
+
for (const t of tried) probe.say(rowFor(t, void 0));
|
|
4322
|
+
return;
|
|
4323
|
+
}
|
|
4324
|
+
for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
|
|
4325
|
+
const inGroup = tried.filter((t) => rules[t.permission] === rule);
|
|
4326
|
+
if (inGroup.length === 0) continue;
|
|
4327
|
+
probe.say({
|
|
4328
|
+
status: "heading",
|
|
4329
|
+
label: heading
|
|
4330
|
+
});
|
|
4331
|
+
for (const t of inGroup) probe.say(rowFor(t, rule));
|
|
4332
|
+
}
|
|
4333
|
+
}
|
|
4334
|
+
};
|
|
4335
|
+
}
|
|
4336
|
+
// src/token-resolvers.ts
|
|
4337
|
+
/** Each token's resolver by its environment variable (`HOLOCRON_ADMIN_TOKEN`), which is what `--token-name` carries. */
|
|
4338
|
+
const TOKEN_RESOLVERS = {
|
|
4339
|
+
HOLOCRON_READ_TOKEN: resolveReadToken,
|
|
4340
|
+
HOLOCRON_ISSUES_TOKEN: resolveIssuesToken,
|
|
4341
|
+
HOLOCRON_SYNC_TOKEN: resolveSyncToken,
|
|
4342
|
+
HOLOCRON_RELEASE_TOKEN: resolveReleaseToken,
|
|
4343
|
+
HOLOCRON_ADMIN_TOKEN: resolveAdminToken,
|
|
4344
|
+
HOLOCRON_SECRETS_TOKEN: resolveSecretsToken,
|
|
4345
|
+
HOLOCRON_DEPLOY_TOKEN: resolveDeployToken,
|
|
4346
|
+
HOLOCRON_USER_SYNC_TOKEN: resolveUserSyncToken,
|
|
4347
|
+
HOLOCRON_ORG_TOKEN: resolveOrgToken
|
|
4348
|
+
};
|
|
4349
|
+
// src/verify-token.ts
|
|
4350
|
+
/** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
|
|
665
4351
|
async function verifyToken(token, opts = {}) {
|
|
666
4352
|
const client = createGitHubClient({
|
|
667
4353
|
token,
|
|
@@ -669,43 +4355,56 @@ async function verifyToken(token, opts = {}) {
|
|
|
669
4355
|
fetch: opts.fetch
|
|
670
4356
|
});
|
|
671
4357
|
try {
|
|
672
|
-
const me = await client.user.
|
|
4358
|
+
const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
|
|
673
4359
|
return {
|
|
674
4360
|
ok: true,
|
|
675
|
-
subject: `user @ ${me.login ?? me.email ?? "unknown"}
|
|
4361
|
+
subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
|
|
4362
|
+
...expiresAt ? { expiresAt } : {}
|
|
676
4363
|
};
|
|
677
4364
|
} catch (err) {
|
|
678
4365
|
return {
|
|
679
4366
|
ok: false,
|
|
680
|
-
message:
|
|
4367
|
+
message: errorMessage(err)
|
|
681
4368
|
};
|
|
682
4369
|
}
|
|
683
4370
|
}
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
function source(ctx, orgClient) {
|
|
4371
|
+
// src/index.ts
|
|
4372
|
+
/** Builds the `source` capability; the optional clients cover org-level and user-sync access. */
|
|
4373
|
+
function source(ctx, orgClient, userSyncClient) {
|
|
687
4374
|
return new GitHubSource(ctx.client, {
|
|
688
4375
|
repo: ctx.repo,
|
|
689
4376
|
repoRoot: ctx.repoRoot,
|
|
690
4377
|
orgClient,
|
|
4378
|
+
userSyncClient,
|
|
691
4379
|
baseUrl: ctx.options.baseUrl,
|
|
692
4380
|
fetch: ctx.options.fetch
|
|
693
4381
|
});
|
|
694
4382
|
}
|
|
695
|
-
|
|
696
|
-
|
|
4383
|
+
/** Builds the `secrets` capability; the optional client handles organization secrets. */
|
|
4384
|
+
function secrets(ctx, orgClient) {
|
|
4385
|
+
return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
|
|
697
4386
|
}
|
|
4387
|
+
/** Builds the `environments` capability. */
|
|
698
4388
|
function environments(ctx) {
|
|
699
4389
|
return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
|
|
700
4390
|
}
|
|
4391
|
+
/** Builds the `ci` capability. */
|
|
701
4392
|
function ci(ctx) {
|
|
702
4393
|
return new GitHubCi(ctx.client, { repo: ctx.repo });
|
|
703
4394
|
}
|
|
704
|
-
|
|
4395
|
+
/** Builds the `issues` capability, passing the lifecycle labels when configured. */
|
|
4396
|
+
function issues(ctx, orgClient) {
|
|
705
4397
|
const opts = { repo: ctx.repo };
|
|
706
4398
|
if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
|
|
4399
|
+
if (ctx.options.issueTypes !== void 0) opts.issueTypes = ctx.options.issueTypes;
|
|
4400
|
+
if (orgClient) opts.orgClient = orgClient;
|
|
707
4401
|
return new GitHubIssues(ctx.client, opts);
|
|
708
4402
|
}
|
|
4403
|
+
/** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
|
|
4404
|
+
function projects(ctx) {
|
|
4405
|
+
return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo });
|
|
4406
|
+
}
|
|
4407
|
+
/** Creates the plugin, resolving a token per capability when it is first used. */
|
|
709
4408
|
function createPlugin(options) {
|
|
710
4409
|
function makeCtx(resolver) {
|
|
711
4410
|
const token = resolver(options);
|
|
@@ -720,6 +4419,40 @@ function createPlugin(options) {
|
|
|
720
4419
|
repoRoot: options.repoRoot ?? process.cwd()
|
|
721
4420
|
};
|
|
722
4421
|
}
|
|
4422
|
+
/** A token, or undefined when that feature token is simply not configured. */
|
|
4423
|
+
function tryResolve(resolver) {
|
|
4424
|
+
try {
|
|
4425
|
+
return resolver(options);
|
|
4426
|
+
} catch (err) {
|
|
4427
|
+
if (err instanceof AuthError) return void 0;
|
|
4428
|
+
throw err;
|
|
4429
|
+
}
|
|
4430
|
+
}
|
|
4431
|
+
/**
|
|
4432
|
+
* Organization secrets need an org-resource-owner token (`github.secrets`);
|
|
4433
|
+
* repo and environment secrets need `github.admin`. Each scope prefers its own
|
|
4434
|
+
* token and falls back to the other, so a setup with only one of them keeps
|
|
4435
|
+
* working, and an explicit `--token` serves both. With neither configured this
|
|
4436
|
+
* fails exactly as the admin-token capabilities do.
|
|
4437
|
+
*/
|
|
4438
|
+
function makeSecrets() {
|
|
4439
|
+
const secretsToken = tryResolve(resolveSecretsToken);
|
|
4440
|
+
const adminToken = tryResolve(resolveAdminToken);
|
|
4441
|
+
if (!secretsToken && !adminToken) resolveAdminToken(options);
|
|
4442
|
+
const clientFor = (token) => createGitHubClient$1({
|
|
4443
|
+
token,
|
|
4444
|
+
baseUrl: options.baseUrl,
|
|
4445
|
+
fetch: options.fetch
|
|
4446
|
+
});
|
|
4447
|
+
const repoClient = clientFor(adminToken ?? secretsToken);
|
|
4448
|
+
const orgClient = clientFor(secretsToken ?? adminToken);
|
|
4449
|
+
return secrets({
|
|
4450
|
+
options,
|
|
4451
|
+
client: repoClient,
|
|
4452
|
+
repo: options.repo,
|
|
4453
|
+
repoRoot: options.repoRoot ?? process.cwd()
|
|
4454
|
+
}, orgClient);
|
|
4455
|
+
}
|
|
723
4456
|
function makeOrgClient() {
|
|
724
4457
|
try {
|
|
725
4458
|
const token = resolveOrgToken(options);
|
|
@@ -732,21 +4465,54 @@ function createPlugin(options) {
|
|
|
732
4465
|
return;
|
|
733
4466
|
}
|
|
734
4467
|
}
|
|
4468
|
+
/** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
|
|
4469
|
+
function makeUserSyncClient() {
|
|
4470
|
+
const token = tryResolve(resolveUserSyncToken);
|
|
4471
|
+
return token ? createGitHubClient$1({
|
|
4472
|
+
token,
|
|
4473
|
+
baseUrl: options.baseUrl,
|
|
4474
|
+
fetch: options.fetch
|
|
4475
|
+
}) : void 0;
|
|
4476
|
+
}
|
|
735
4477
|
return {
|
|
736
4478
|
name: "@theholocron/holocron-plugin-github",
|
|
4479
|
+
probes: {
|
|
4480
|
+
token: tokenProbe({
|
|
4481
|
+
repo: options.repo,
|
|
4482
|
+
baseUrl: (options.baseUrl ?? "https://api.github.com").replace(/\/$/, ""),
|
|
4483
|
+
fetch: options.fetch ?? fetch,
|
|
4484
|
+
resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
|
|
4485
|
+
tokenNames: Object.keys(TOKEN_RESOLVERS)
|
|
4486
|
+
}),
|
|
4487
|
+
"issue-types": issueTypesProbe({
|
|
4488
|
+
makeApi: (repo) => createBackfillApi(makeCtx(resolveIssuesToken).client, makeCtx(resolveOrgToken).client, repo),
|
|
4489
|
+
repo: options.repo,
|
|
4490
|
+
config: options.areaLabels ?? {}
|
|
4491
|
+
}),
|
|
4492
|
+
connection: connectionProbe({
|
|
4493
|
+
provider: "GitHub",
|
|
4494
|
+
url: options.baseUrl ?? "https://api.github.com",
|
|
4495
|
+
fetch: options.fetch,
|
|
4496
|
+
token: () => resolveReadToken(options),
|
|
4497
|
+
verify: (token) => verifyToken(token, {
|
|
4498
|
+
baseUrl: options.baseUrl,
|
|
4499
|
+
fetch: options.fetch
|
|
4500
|
+
})
|
|
4501
|
+
})
|
|
4502
|
+
},
|
|
737
4503
|
capabilities: {
|
|
738
|
-
source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
|
|
4504
|
+
source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
|
|
739
4505
|
ci: () => ci(makeCtx(resolveReadToken)),
|
|
740
|
-
secrets: () =>
|
|
4506
|
+
secrets: () => makeSecrets(),
|
|
741
4507
|
environments: () => environments(makeCtx(resolveAdminToken)),
|
|
742
|
-
issues: () => issues(makeCtx(resolveIssuesToken))
|
|
4508
|
+
issues: () => issues(makeCtx(resolveIssuesToken), makeOrgClient),
|
|
4509
|
+
projects: () => projects(makeCtx(resolveOrgToken))
|
|
743
4510
|
}
|
|
744
4511
|
};
|
|
745
4512
|
}
|
|
746
4513
|
/**
|
|
747
|
-
* One-line hint printed by `holocron
|
|
4514
|
+
* One-line hint printed by `holocron new token github` when no token
|
|
748
4515
|
* is supplied or the supplied token is rejected.
|
|
749
4516
|
*/
|
|
750
|
-
const AUTH_HINT = "generate fine-grained Personal Access Tokens at https://github.com/settings/tokens (one per feature — see docs/tokens.md for required scopes per operation), then run: holocron
|
|
751
|
-
|
|
752
|
-
export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSyncToken, secrets, source, syncLabels, syncTeams, verifyToken };
|
|
4517
|
+
const AUTH_HINT = "generate fine-grained Personal Access Tokens at https://github.com/settings/tokens (one per feature — see docs/tokens.md for required scopes per operation), then run: holocron new token github.<feature> <PAT>";
|
|
4518
|
+
export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubProjects, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, projects, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSecretsToken, resolveSyncToken, resolveUserSyncToken, secrets, source, syncLabels, syncTeams, tokens, verifyToken };
|