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