@theholocron/holocron-plugin-github 5.0.0-alpha.47 → 5.0.0-alpha.470
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 +281 -70
- package/dist/index.mjs +2089 -68
- package/package.json +29 -25
package/dist/index.mjs
CHANGED
|
@@ -1,48 +1,74 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
+
import { AuthError, MissingTokenError, ProviderApiError, connectionProbe, createFeatureResolver, pickByCreation, readKeysLimited, reportProgress, tokenExpectations } from "@theholocron/cli";
|
|
2
3
|
import { createGitHubClient, createGitHubClient as createGitHubClient$1 } from "@theholocron/github-client";
|
|
3
|
-
import { AuthError, createFeatureResolver } from "@theholocron/cli";
|
|
4
4
|
import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
|
-
|
|
6
|
+
import { findRootSync } from "@theholocron/fs-utils";
|
|
7
|
+
import { ProviderApiError as ProviderApiError$1 } from "@theholocron/http-client";
|
|
8
|
+
import { errorMessage } from "@theholocron/misc-utils";
|
|
9
|
+
// src/auth.ts
|
|
10
|
+
/** Resolves the token for read-only GitHub access (`HOLOCRON_READ_TOKEN`, keyring key `github.read`). */
|
|
7
11
|
const resolveReadToken = createFeatureResolver({
|
|
8
12
|
envName: "HOLOCRON_READ_TOKEN",
|
|
9
13
|
keyringKey: "github.read"
|
|
10
14
|
});
|
|
15
|
+
/** Resolves the token for issue operations (`HOLOCRON_ISSUES_TOKEN`, keyring key `github.issues`). */
|
|
11
16
|
const resolveIssuesToken = createFeatureResolver({
|
|
12
17
|
envName: "HOLOCRON_ISSUES_TOKEN",
|
|
13
18
|
keyringKey: "github.issues"
|
|
14
19
|
});
|
|
20
|
+
/** Resolves the token for syncing repo files and settings (`HOLOCRON_SYNC_TOKEN`, keyring key `github.sync`). */
|
|
15
21
|
const resolveSyncToken = createFeatureResolver({
|
|
16
22
|
envName: "HOLOCRON_SYNC_TOKEN",
|
|
17
23
|
keyringKey: "github.sync"
|
|
18
24
|
});
|
|
25
|
+
/** Resolves the token for release operations (`HOLOCRON_RELEASE_TOKEN`, keyring key `github.release`). */
|
|
19
26
|
const resolveReleaseToken = createFeatureResolver({
|
|
20
27
|
envName: "HOLOCRON_RELEASE_TOKEN",
|
|
21
28
|
keyringKey: "github.release"
|
|
22
29
|
});
|
|
30
|
+
/** Resolves the repo-scoped admin token (`HOLOCRON_ADMIN_TOKEN`, keyring key `github.admin`). */
|
|
23
31
|
const resolveAdminToken = createFeatureResolver({
|
|
24
32
|
envName: "HOLOCRON_ADMIN_TOKEN",
|
|
25
33
|
keyringKey: "github.admin"
|
|
26
34
|
});
|
|
35
|
+
/** Resolves the org-level secrets token (`HOLOCRON_SECRETS_TOKEN`, keyring key `github.secrets`). */
|
|
36
|
+
const resolveSecretsToken = createFeatureResolver({
|
|
37
|
+
envName: "HOLOCRON_SECRETS_TOKEN",
|
|
38
|
+
keyringKey: "github.secrets"
|
|
39
|
+
});
|
|
40
|
+
/** Resolves the token for deployment operations (`HOLOCRON_DEPLOY_TOKEN`, keyring key `github.deploy`). */
|
|
27
41
|
const resolveDeployToken = createFeatureResolver({
|
|
28
42
|
envName: "HOLOCRON_DEPLOY_TOKEN",
|
|
29
43
|
keyringKey: "github.deploy"
|
|
30
44
|
});
|
|
45
|
+
/**
|
|
46
|
+
* Resolves the token for the user-sync files in the org's private config repo (`HOLOCRON_USER_SYNC_TOKEN`, keyring
|
|
47
|
+
* key `github.user-sync`).
|
|
48
|
+
*/
|
|
49
|
+
const resolveUserSyncToken = createFeatureResolver({
|
|
50
|
+
envName: "HOLOCRON_USER_SYNC_TOKEN",
|
|
51
|
+
keyringKey: "github.user-sync"
|
|
52
|
+
});
|
|
53
|
+
/** Resolves the org-level token (`HOLOCRON_ORG_TOKEN`, keyring key `github.org`). */
|
|
31
54
|
const resolveOrgToken = createFeatureResolver({
|
|
32
55
|
envName: "HOLOCRON_ORG_TOKEN",
|
|
33
56
|
keyringKey: "github.org"
|
|
34
57
|
});
|
|
35
|
-
|
|
36
|
-
|
|
58
|
+
// src/capabilities/ci.ts
|
|
59
|
+
/** The GitHub implementation of the `ci` capability, backed by GitHub Actions workflow runs. */
|
|
37
60
|
var GitHubCi = class {
|
|
38
61
|
client;
|
|
39
62
|
opts;
|
|
63
|
+
/** Capability key, always `"ci"`. */
|
|
40
64
|
key = "ci";
|
|
65
|
+
/** Provider name, always `"github"`. */
|
|
41
66
|
providerName = "github";
|
|
42
67
|
constructor(client, opts) {
|
|
43
68
|
this.client = client;
|
|
44
69
|
this.opts = opts;
|
|
45
70
|
}
|
|
71
|
+
/** Lists workflow runs for the repo, optionally filtered by branch, status and limit. */
|
|
46
72
|
async listRuns(filter) {
|
|
47
73
|
return (await this.client.workflows.listRuns(this.opts.repo, {
|
|
48
74
|
branch: filter?.branch,
|
|
@@ -50,6 +76,7 @@ var GitHubCi = class {
|
|
|
50
76
|
status: filter?.status
|
|
51
77
|
})).map((r) => this.mapRun(r));
|
|
52
78
|
}
|
|
79
|
+
/** Fetches one workflow run by id. */
|
|
53
80
|
async getRun(id) {
|
|
54
81
|
const raw = await this.client.workflows.getRun(this.opts.repo, id);
|
|
55
82
|
return this.mapRun(raw);
|
|
@@ -77,17 +104,20 @@ var GitHubCi = class {
|
|
|
77
104
|
}
|
|
78
105
|
}
|
|
79
106
|
};
|
|
80
|
-
|
|
81
|
-
|
|
107
|
+
// src/capabilities/environments.ts
|
|
108
|
+
/** The GitHub implementation of the `environments` capability, managing a repo's deployment environments. */
|
|
82
109
|
var GitHubEnvironments = class {
|
|
83
110
|
client;
|
|
84
111
|
opts;
|
|
112
|
+
/** Capability key, always `"environments"`. */
|
|
85
113
|
key = "environments";
|
|
114
|
+
/** Provider name, always `"github"`. */
|
|
86
115
|
providerName = "github";
|
|
87
116
|
constructor(client, opts) {
|
|
88
117
|
this.client = client;
|
|
89
118
|
this.opts = opts;
|
|
90
119
|
}
|
|
120
|
+
/** Lists the repo's environments with their wait timer, self-review rule and required reviewers. */
|
|
91
121
|
async listEnvironments() {
|
|
92
122
|
return (await this.client.environments.listEnvironments(this.opts.repo)).map((e) => ({
|
|
93
123
|
name: e.name,
|
|
@@ -96,6 +126,7 @@ var GitHubEnvironments = class {
|
|
|
96
126
|
reviewers: this.flattenReviewers(e.protection_rules)
|
|
97
127
|
}));
|
|
98
128
|
}
|
|
129
|
+
/** Creates or updates an environment, sending only the settings the given environment defines. */
|
|
99
130
|
async upsertEnvironment(env) {
|
|
100
131
|
const body = {};
|
|
101
132
|
if (env.waitTimer !== void 0) body.wait_timer = env.waitTimer;
|
|
@@ -106,6 +137,7 @@ var GitHubEnvironments = class {
|
|
|
106
137
|
}));
|
|
107
138
|
await this.client.environments.upsertEnvironment(this.opts.repo, env.name, body);
|
|
108
139
|
}
|
|
140
|
+
/** Deletes the named environment. */
|
|
109
141
|
async deleteEnvironment(name) {
|
|
110
142
|
await this.client.environments.deleteEnvironment(this.opts.repo, name);
|
|
111
143
|
}
|
|
@@ -119,11 +151,427 @@ var GitHubEnvironments = class {
|
|
|
119
151
|
}));
|
|
120
152
|
}
|
|
121
153
|
};
|
|
122
|
-
|
|
123
|
-
|
|
154
|
+
// src/capabilities/issue-priority.ts
|
|
155
|
+
const OPTION_NAMES = {
|
|
156
|
+
urgent: "Urgent",
|
|
157
|
+
high: "High",
|
|
158
|
+
medium: "Medium",
|
|
159
|
+
low: "Low"
|
|
160
|
+
};
|
|
161
|
+
/** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
|
|
162
|
+
function refusal(err) {
|
|
163
|
+
if (!(err instanceof ProviderApiError)) return void 0;
|
|
164
|
+
if (err.status === void 0 || ![
|
|
165
|
+
401,
|
|
166
|
+
403,
|
|
167
|
+
404,
|
|
168
|
+
422
|
|
169
|
+
].includes(err.status)) return void 0;
|
|
170
|
+
if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
|
|
171
|
+
return `GitHub refused: ${err.status}`;
|
|
172
|
+
}
|
|
173
|
+
function createPrioritySetter(client, repo) {
|
|
174
|
+
const org = repo.split("/")[0];
|
|
175
|
+
let lookup;
|
|
176
|
+
const findField = () => lookup ??= client.issueFields.list(org).then((fields) => {
|
|
177
|
+
const field = fields.find((f) => f.name === "Priority" && f.data_type === "single_select");
|
|
178
|
+
return field ? { field } : { note: `priority field (${org} has no Priority issue field)` };
|
|
179
|
+
}, (err) => {
|
|
180
|
+
const why = refusal(err);
|
|
181
|
+
if (why === void 0) throw err;
|
|
182
|
+
return { note: `priority field (${why})` };
|
|
183
|
+
});
|
|
184
|
+
return { async set(number, level, flags = {}) {
|
|
185
|
+
if (!level || level === "none") return { changed: false };
|
|
186
|
+
const found = await findField();
|
|
187
|
+
if ("note" in found) return {
|
|
188
|
+
changed: false,
|
|
189
|
+
note: found.note
|
|
190
|
+
};
|
|
191
|
+
const { field } = found;
|
|
192
|
+
const optionName = OPTION_NAMES[level];
|
|
193
|
+
const option = field.options?.find((o) => o.name.toLowerCase() === optionName.toLowerCase());
|
|
194
|
+
if (!option) return {
|
|
195
|
+
changed: false,
|
|
196
|
+
note: `priority field (no "${optionName}" option)`
|
|
197
|
+
};
|
|
198
|
+
try {
|
|
199
|
+
const current = flags.isNew ? void 0 : (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
|
|
200
|
+
if ((current ? current.single_select_option?.name ?? String(current.value) : void 0)?.toLowerCase() === option.name.toLowerCase()) return { changed: false };
|
|
201
|
+
if (flags.dryRun) return { changed: true };
|
|
202
|
+
if (current) await client.issueFields.deleteValue(repo, number, field.id);
|
|
203
|
+
await client.issueFields.addValues(repo, number, [{
|
|
204
|
+
field_id: field.id,
|
|
205
|
+
value: option.name
|
|
206
|
+
}]);
|
|
207
|
+
return { changed: true };
|
|
208
|
+
} catch (err) {
|
|
209
|
+
const why = refusal(err);
|
|
210
|
+
if (why === void 0) throw err;
|
|
211
|
+
return {
|
|
212
|
+
changed: false,
|
|
213
|
+
note: `priority field (${why})`
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
} };
|
|
217
|
+
}
|
|
218
|
+
// src/capabilities/issues-migration.ts
|
|
219
|
+
/**
|
|
220
|
+
* Export and import of GitHub issues for `holocron migrate`.
|
|
221
|
+
*
|
|
222
|
+
* GitHub holds less than a planning tool, so what does not fit is named in each result's `dropped` list rather than
|
|
223
|
+
* lost quietly:
|
|
224
|
+
* - priority is a label (`priority: high`), because on GitHub it lives in a project field, not on the issue;
|
|
225
|
+
* - an import cannot backdate an issue or a comment, and cannot post as someone else, so the original date and
|
|
226
|
+
* author go in the text;
|
|
227
|
+
* - an import does not set parent or blocked-by links (they need GraphQL node ids of issues made in the same run);
|
|
228
|
+
* - an assignee is not mapped (a Linear user is not a GitHub login).
|
|
229
|
+
* - the organization's `Priority` issue field is set from the priority (`issue-priority.ts`), beside the label.
|
|
230
|
+
* A migrated issue ends with `<!-- holocron:migrated-from <url> -->`, which is how a second run finds it.
|
|
231
|
+
*/
|
|
232
|
+
const MARKER = /<!-- holocron:migrated-from (\S+) -->/;
|
|
233
|
+
const PRIORITY_LABEL = /^priority\s*[:/-]\s*(urgent|high|medium|low)$/i;
|
|
234
|
+
const LINK_QUERY = `query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) {
|
|
235
|
+
issue(number: $number) { parent { number } blockedBy(first: 50) { nodes { number } } } } }`;
|
|
236
|
+
/** Splits `priority: high` labels from the rest. */
|
|
237
|
+
function splitLabels(names) {
|
|
238
|
+
let priority;
|
|
239
|
+
const labels = [];
|
|
240
|
+
for (const name of names) {
|
|
241
|
+
const match = PRIORITY_LABEL.exec(name);
|
|
242
|
+
if (match) priority = match[1].toLowerCase();
|
|
243
|
+
else labels.push(name);
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
labels,
|
|
247
|
+
...priority ? { priority } : {}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function categoryOf(issue) {
|
|
251
|
+
if (issue.state === "closed") return "done";
|
|
252
|
+
const names = issue.labels.map((l) => l.name.toLowerCase());
|
|
253
|
+
if (names.some((n) => n === "status:in-review" || n === "status: in review")) return "in-review";
|
|
254
|
+
if (names.some((n) => n === "status:in-progress" || n === "status: in progress")) return "in-progress";
|
|
255
|
+
return "open";
|
|
256
|
+
}
|
|
257
|
+
/** How many issues an export fetches at once. GitHub's secondary rate limit punishes bursts of requests, not volume. */
|
|
258
|
+
const EXPORT_CONCURRENCY = 4;
|
|
259
|
+
/** Runs `fn` over `items`, at most `limit` at a time, and returns the results in the order of `items`. */
|
|
260
|
+
async function mapLimit(items, limit, fn) {
|
|
261
|
+
const results = new Array(items.length);
|
|
262
|
+
let next = 0;
|
|
263
|
+
const worker = async () => {
|
|
264
|
+
while (next < items.length) {
|
|
265
|
+
const at = next++;
|
|
266
|
+
results[at] = await fn(items[at]);
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
270
|
+
return results;
|
|
271
|
+
}
|
|
272
|
+
/** GitHub's own answer to a burst of requests (403 or 429 naming the secondary limit) becomes a message that says what to do. */
|
|
273
|
+
function explainSecondaryLimit(err) {
|
|
274
|
+
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.");
|
|
275
|
+
return err;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Reads the issues `selector` names, with their comments, priority label, parent and blockers.
|
|
279
|
+
*
|
|
280
|
+
* With `limit`, only that many survivors of the other filters are read, from the `order` end of the creation order. A
|
|
281
|
+
* list of keys is sorted by issue number (which rises with creation in one repository) before anything is fetched, then
|
|
282
|
+
* fetched a few at a time until enough are kept; a listing already carries `created_at`, so it is cut before the
|
|
283
|
+
* per-issue comment and link requests. `info.matched` receives how many the selection matched before the cut.
|
|
284
|
+
*/
|
|
285
|
+
async function exportIssues(client, repo, selector, info = {}) {
|
|
286
|
+
return readIssues(client, repo, selector, info).catch((err) => {
|
|
287
|
+
throw explainSecondaryLimit(err);
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
async function readIssues(client, repo, selector, info) {
|
|
291
|
+
const [owner = "", name = ""] = repo.split("/", 2);
|
|
292
|
+
const since = selector.since ? Date.parse(selector.since) : void 0;
|
|
293
|
+
const survives = (i) => !i.pull_request && !(selector.openOnly && i.state === "closed") && (since === void 0 || Date.parse(i.updated_at) >= since);
|
|
294
|
+
const { limit, order = "oldest" } = selector;
|
|
295
|
+
let issues;
|
|
296
|
+
if (selector.keys) {
|
|
297
|
+
const fetch = (k) => client.issues.getIssue(repo, parseNumber(k));
|
|
298
|
+
info.matched = selector.keys.length;
|
|
299
|
+
issues = limit === void 0 ? (await mapLimit(selector.keys, EXPORT_CONCURRENCY, fetch)).filter(survives) : await readKeysLimited({
|
|
300
|
+
keys: selector.keys,
|
|
301
|
+
order,
|
|
302
|
+
limit,
|
|
303
|
+
concurrency: EXPORT_CONCURRENCY,
|
|
304
|
+
fetch,
|
|
305
|
+
keep: survives
|
|
306
|
+
});
|
|
307
|
+
} else {
|
|
308
|
+
let raw;
|
|
309
|
+
if (selector.milestone) {
|
|
310
|
+
const milestone = await findMilestone(client, repo, selector.milestone);
|
|
311
|
+
if (!milestone) throw new Error(`Milestone "${selector.milestone}" not found in ${repo}.`);
|
|
312
|
+
raw = await listAll(client, repo, { milestone: String(milestone.number) });
|
|
313
|
+
} else if (selector.all) raw = await listAll(client, repo, {});
|
|
314
|
+
else throw new Error("export needs keys, a milestone or all");
|
|
315
|
+
issues = raw.filter(survives);
|
|
316
|
+
info.matched = issues.length;
|
|
317
|
+
if (limit !== void 0) issues = pickByCreation(issues, (i) => i.created_at ?? i.updated_at, order, limit);
|
|
318
|
+
}
|
|
319
|
+
const records = [];
|
|
320
|
+
for (const issue of issues) {
|
|
321
|
+
reportProgress(info.onProgress, records.length, issues.length);
|
|
322
|
+
const comments = await client.issues.listComments(repo, issue.number);
|
|
323
|
+
const links = (await client.graphql.query(LINK_QUERY, {
|
|
324
|
+
owner,
|
|
325
|
+
name,
|
|
326
|
+
number: issue.number
|
|
327
|
+
}).catch(() => void 0))?.repository.issue;
|
|
328
|
+
const { labels, priority } = splitLabels(issue.labels.map((l) => l.name));
|
|
329
|
+
const body = issue.body?.replace(MARKER, "").trimEnd();
|
|
330
|
+
const migratedFrom = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
|
|
331
|
+
records.push({
|
|
332
|
+
key: `#${issue.number}`,
|
|
333
|
+
url: issue.html_url,
|
|
334
|
+
title: issue.title,
|
|
335
|
+
...body ? { body } : {},
|
|
336
|
+
statusCategory: categoryOf(issue),
|
|
337
|
+
closed: issue.state === "closed",
|
|
338
|
+
...priority ? { priority } : {},
|
|
339
|
+
labels: labels.filter((l) => !l.toLowerCase().startsWith("status:")),
|
|
340
|
+
...issue.assignee ? { assignee: {
|
|
341
|
+
id: issue.assignee.login,
|
|
342
|
+
displayName: issue.assignee.name ?? issue.assignee.login,
|
|
343
|
+
...issue.assignee.email ? { emailAddress: issue.assignee.email } : {}
|
|
344
|
+
} } : {},
|
|
345
|
+
...issue.milestone ? { milestone: issue.milestone.title } : {},
|
|
346
|
+
...links?.parent ? { parent: `#${links.parent.number}` } : {},
|
|
347
|
+
blockedBy: (links?.blockedBy.nodes ?? []).map((n) => `#${n.number}`),
|
|
348
|
+
comments: comments.map((c) => ({
|
|
349
|
+
...c.user ? { author: c.user.login } : {},
|
|
350
|
+
body: c.body,
|
|
351
|
+
createdAt: c.created_at
|
|
352
|
+
})),
|
|
353
|
+
createdAt: issue.created_at ?? issue.updated_at,
|
|
354
|
+
updatedAt: issue.updated_at,
|
|
355
|
+
...migratedFrom ? { migratedFrom } : {}
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
reportProgress(info.onProgress, records.length, issues.length);
|
|
359
|
+
return records;
|
|
360
|
+
}
|
|
361
|
+
/** Makes the records as issues, skipping any whose source address an earlier run already recorded. */
|
|
362
|
+
async function importIssues(client, repo, records, options = {}) {
|
|
363
|
+
const existing = /* @__PURE__ */ new Map();
|
|
364
|
+
for (const issue of await listAll(client, repo, {})) {
|
|
365
|
+
const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
|
|
366
|
+
if (url) existing.set(url, issue.number);
|
|
367
|
+
}
|
|
368
|
+
const priority = createPrioritySetter(client, repo);
|
|
369
|
+
const results = [];
|
|
370
|
+
const tick = () => reportProgress(options.onProgress, results.length, records.length);
|
|
371
|
+
for (const record of records) {
|
|
372
|
+
const found = existing.get(record.url);
|
|
373
|
+
if (found !== void 0) {
|
|
374
|
+
results.push({
|
|
375
|
+
source: record.key,
|
|
376
|
+
key: `#${found}`,
|
|
377
|
+
created: false,
|
|
378
|
+
dropped: []
|
|
379
|
+
});
|
|
380
|
+
tick();
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
const dropped = droppedFor(record);
|
|
384
|
+
if (options.dryRun) {
|
|
385
|
+
results.push({
|
|
386
|
+
source: record.key,
|
|
387
|
+
created: true,
|
|
388
|
+
dropped
|
|
389
|
+
});
|
|
390
|
+
tick();
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
const number = await createFromRecord(client, repo, record, options);
|
|
394
|
+
const field = await priority.set(number, record.priority, { isNew: true });
|
|
395
|
+
if (field.note) dropped.push(field.note);
|
|
396
|
+
results.push({
|
|
397
|
+
source: record.key,
|
|
398
|
+
key: `#${number}`,
|
|
399
|
+
created: true,
|
|
400
|
+
dropped
|
|
401
|
+
});
|
|
402
|
+
tick();
|
|
403
|
+
}
|
|
404
|
+
return results;
|
|
405
|
+
}
|
|
406
|
+
/** What GitHub cannot hold of this record, for the report. */
|
|
407
|
+
function droppedFor(record) {
|
|
408
|
+
const dropped = ["createdAt (GitHub sets it; the original date is in the text)"];
|
|
409
|
+
if (record.assignee && !record.assignee.login) dropped.push("assignee (not mapped)");
|
|
410
|
+
if (record.parent) dropped.push("parent (not set on GitHub)");
|
|
411
|
+
if (record.blockedBy.length > 0) dropped.push("blockedBy (not set on GitHub)");
|
|
412
|
+
return dropped;
|
|
413
|
+
}
|
|
414
|
+
/** The labels a record becomes on GitHub: its own, plus `priority: <level>` (GitHub's priority is a label). */
|
|
415
|
+
function labelsFor(record) {
|
|
416
|
+
return [...record.labels, ...record.priority && record.priority !== "none" ? [`priority: ${record.priority}`] : []];
|
|
417
|
+
}
|
|
418
|
+
/** The text a comment gets when it is copied: GitHub cannot post as another author or backdate. */
|
|
419
|
+
function renderComment(comment) {
|
|
420
|
+
return `${comment.author ? `**${comment.author}**` : "Someone"} commented on ${comment.createdAt}:\n\n${comment.body}`;
|
|
421
|
+
}
|
|
422
|
+
/** Makes one issue from a record, with its comments, and closes it when the record is closed; returns its number. */
|
|
423
|
+
async function createFromRecord(client, repo, record, options) {
|
|
424
|
+
const milestoneName = options.milestone ?? record.milestone;
|
|
425
|
+
const milestone = milestoneName ? await ensureMilestone(client, repo, milestoneName) : void 0;
|
|
426
|
+
const labels = labelsFor(record);
|
|
427
|
+
const created = await client.issues.createIssue(repo, {
|
|
428
|
+
title: record.title,
|
|
429
|
+
body: withProvenance(record),
|
|
430
|
+
...labels.length > 0 ? { labels } : {},
|
|
431
|
+
...milestone !== void 0 ? { milestone } : {},
|
|
432
|
+
...record.assignee?.login ? { assignees: [record.assignee.login] } : {}
|
|
433
|
+
});
|
|
434
|
+
for (const comment of record.comments) await client.issues.createComment(repo, created.number, renderComment(comment));
|
|
435
|
+
if (record.closed) await client.issues.updateIssue(repo, created.number, {
|
|
436
|
+
state: "closed",
|
|
437
|
+
state_reason: "completed"
|
|
438
|
+
});
|
|
439
|
+
return created.number;
|
|
440
|
+
}
|
|
441
|
+
/** The text of a migrated issue: the record's body, then where it came from and the marker a second run looks for. */
|
|
442
|
+
function withProvenance(record) {
|
|
443
|
+
return `${record.body ? `${record.body}\n\n` : ""}---\n_Migrated from [${record.key}](${record.url}); created ${record.createdAt}._\n<!-- holocron:migrated-from ${record.url} -->`;
|
|
444
|
+
}
|
|
445
|
+
function parseNumber(key) {
|
|
446
|
+
const n = key.trim().replace(/^.*#/, "");
|
|
447
|
+
if (!/^\d+$/.test(n)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
|
|
448
|
+
return parseInt(n, 10);
|
|
449
|
+
}
|
|
450
|
+
async function listAll(client, repo, extra) {
|
|
451
|
+
const all = [];
|
|
452
|
+
for (let page = 1;; page++) {
|
|
453
|
+
const batch = await client.issues.listIssues(repo, {
|
|
454
|
+
state: "all",
|
|
455
|
+
per_page: 100,
|
|
456
|
+
page,
|
|
457
|
+
...extra
|
|
458
|
+
});
|
|
459
|
+
all.push(...batch);
|
|
460
|
+
if (batch.length < 100) return all;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
async function findMilestone(client, repo, ref) {
|
|
464
|
+
return (await client.issues.listMilestones(repo, { state: "all" })).find((m) => String(m.number) === ref || m.title.toLowerCase() === ref.toLowerCase());
|
|
465
|
+
}
|
|
466
|
+
async function ensureMilestone(client, repo, title) {
|
|
467
|
+
return (await findMilestone(client, repo, title))?.number ?? (await client.issues.createMilestone(repo, title)).number;
|
|
468
|
+
}
|
|
469
|
+
// src/capabilities/issues-sync.ts
|
|
470
|
+
const COMMENT_HEADER = /^(?:\*\*.*?\*\*|Someone) commented on (\S+?):\n/;
|
|
471
|
+
/** Whether GitHub is asking to be left alone: a 429, or a 403 that says it is a rate limit. */
|
|
472
|
+
function isRateLimited(err) {
|
|
473
|
+
return err instanceof ProviderApiError && (err.status === 429 || err.status === 403 && /rate limit/i.test(`${err.message} ${String(err.details)}`));
|
|
474
|
+
}
|
|
475
|
+
const normalize = (text) => text.replace(/\r\n/g, "\n").trim();
|
|
476
|
+
const sorted = (names) => names.map((n) => n.toLowerCase()).sort().join("\n");
|
|
477
|
+
/** Makes the records missing from the repo and updates the ones an earlier run made. See the file comment. */
|
|
478
|
+
async function syncIssues(client, repo, records, options = {}) {
|
|
479
|
+
const existing = /* @__PURE__ */ new Map();
|
|
480
|
+
for (const issue of await listAll(client, repo, {})) {
|
|
481
|
+
const url = issue.body ? MARKER.exec(issue.body)?.[1] : void 0;
|
|
482
|
+
if (url) existing.set(url, issue);
|
|
483
|
+
}
|
|
484
|
+
const priority = createPrioritySetter(client, repo);
|
|
485
|
+
const results = [];
|
|
486
|
+
for (const record of records) try {
|
|
487
|
+
const found = existing.get(record.url);
|
|
488
|
+
results.push(found ? await update(client, repo, found, record, options, priority) : await create(client, repo, record, options, priority));
|
|
489
|
+
reportProgress(options.onProgress, results.length, records.length);
|
|
490
|
+
} catch (err) {
|
|
491
|
+
if (isRateLimited(err)) return results;
|
|
492
|
+
throw err;
|
|
493
|
+
}
|
|
494
|
+
return results;
|
|
495
|
+
}
|
|
496
|
+
async function create(client, repo, record, options, priority) {
|
|
497
|
+
const dropped = droppedFor(record);
|
|
498
|
+
if (options.dryRun) return {
|
|
499
|
+
source: record.key,
|
|
500
|
+
created: true,
|
|
501
|
+
updated: false,
|
|
502
|
+
changes: [],
|
|
503
|
+
dropped
|
|
504
|
+
};
|
|
505
|
+
const number = await createFromRecord(client, repo, record, options);
|
|
506
|
+
const field = await priority.set(number, record.priority, { isNew: true });
|
|
507
|
+
if (field.note) dropped.push(field.note);
|
|
508
|
+
return {
|
|
509
|
+
source: record.key,
|
|
510
|
+
key: `#${number}`,
|
|
511
|
+
created: true,
|
|
512
|
+
updated: false,
|
|
513
|
+
changes: [],
|
|
514
|
+
dropped
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
async function update(client, repo, issue, record, options, priority) {
|
|
518
|
+
const patch = {};
|
|
519
|
+
const changes = [];
|
|
520
|
+
if (issue.title !== record.title) {
|
|
521
|
+
patch.title = record.title;
|
|
522
|
+
changes.push("title");
|
|
523
|
+
}
|
|
524
|
+
const body = withProvenance(record);
|
|
525
|
+
if (normalize(issue.body) !== normalize(body)) {
|
|
526
|
+
patch.body = body;
|
|
527
|
+
changes.push("description");
|
|
528
|
+
}
|
|
529
|
+
if (issue.state === "closed" !== record.closed) {
|
|
530
|
+
patch.state = record.closed ? "closed" : "open";
|
|
531
|
+
if (record.closed) patch.state_reason = "completed";
|
|
532
|
+
changes.push("state");
|
|
533
|
+
}
|
|
534
|
+
const current = issue.labels.map((l) => l.name);
|
|
535
|
+
const finalLabels = [...labelsFor(record), ...current.filter((n) => n.toLowerCase().startsWith("status:"))];
|
|
536
|
+
if (sorted(finalLabels) !== sorted(current)) {
|
|
537
|
+
patch.labels = finalLabels;
|
|
538
|
+
changes.push("labels");
|
|
539
|
+
}
|
|
540
|
+
const login = record.assignee?.login;
|
|
541
|
+
if (login && issue.assignee?.login.toLowerCase() !== login.toLowerCase()) {
|
|
542
|
+
patch.assignees = [login];
|
|
543
|
+
changes.push("assignee");
|
|
544
|
+
}
|
|
545
|
+
const field = await priority.set(issue.number, record.priority, { dryRun: options.dryRun });
|
|
546
|
+
if (field.changed) changes.push("priority field");
|
|
547
|
+
const comments = await client.issues.listComments(repo, issue.number);
|
|
548
|
+
const seen = new Set(comments.map((c) => COMMENT_HEADER.exec(c.body)?.[1]));
|
|
549
|
+
const missing = record.comments.filter((c) => !seen.has(c.createdAt));
|
|
550
|
+
if (missing.length > 0) changes.push("comments");
|
|
551
|
+
if (!options.dryRun) {
|
|
552
|
+
if (Object.keys(patch).length > 0) await client.issues.updateIssue(repo, issue.number, patch);
|
|
553
|
+
for (const comment of missing) await client.issues.createComment(repo, issue.number, renderComment(comment));
|
|
554
|
+
}
|
|
555
|
+
return {
|
|
556
|
+
source: record.key,
|
|
557
|
+
key: `#${issue.number}`,
|
|
558
|
+
created: false,
|
|
559
|
+
updated: changes.length > 0,
|
|
560
|
+
changes,
|
|
561
|
+
dropped: [...droppedFor(record), ...field.note ? [field.note] : []]
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
// src/capabilities/issues.ts
|
|
565
|
+
/** Issues read per request when `search` has a `text`; GitHub's largest page. */
|
|
566
|
+
const TEXT_PAGE_SIZE = 100;
|
|
567
|
+
/** Pages `search` reads for a `text` before it stops (the 2000 most recently updated issues). */
|
|
568
|
+
const TEXT_MAX_PAGES = 20;
|
|
569
|
+
/** The GitHub implementation of the `issues` capability, backed by GitHub Issues and status labels. */
|
|
124
570
|
var GitHubIssues = class {
|
|
125
571
|
client;
|
|
572
|
+
/** Capability key, always `"issues"`. */
|
|
126
573
|
key = "issues";
|
|
574
|
+
/** Provider name, always `"github"`. */
|
|
127
575
|
providerName = "github";
|
|
128
576
|
owner;
|
|
129
577
|
repoName;
|
|
@@ -145,7 +593,18 @@ var GitHubIssues = class {
|
|
|
145
593
|
...raw.email ? { emailAddress: raw.email } : {}
|
|
146
594
|
};
|
|
147
595
|
}
|
|
596
|
+
/**
|
|
597
|
+
* Searches the repo's issues, newest update first, leaving out pull requests.
|
|
598
|
+
*
|
|
599
|
+
* With `filter.text`, the issues are paged (newest update first, 100 a page, at most 20 pages) and compared
|
|
600
|
+
* client-side, without regard to case, until `limit` matches are found or the issues run out. GitHub's issue
|
|
601
|
+
* search (`GET /search/issues`) is deliberately not used: it indexes the words of a body, so punctuation and an
|
|
602
|
+
* HTML comment such as `<!-- holocron:idea notes/a.md -->` cannot be relied on to match, it is limited to 30
|
|
603
|
+
* requests a minute and it is eventually consistent (an issue made a moment ago may be missing). Paging has none
|
|
604
|
+
* of those limits, at the cost of reading up to 20 pages of a very large repository.
|
|
605
|
+
*/
|
|
148
606
|
async search(filter) {
|
|
607
|
+
if (filter.text) return this.searchText(filter, filter.text);
|
|
149
608
|
const params = {
|
|
150
609
|
state: filter.openOnly ? "open" : "all",
|
|
151
610
|
sort: "updated",
|
|
@@ -164,11 +623,39 @@ var GitHubIssues = class {
|
|
|
164
623
|
assignee: params.assignee
|
|
165
624
|
})).filter((i) => !i.pull_request).map((i) => this.mapIssue(i));
|
|
166
625
|
}
|
|
626
|
+
async searchText(filter, text) {
|
|
627
|
+
const needle = text.toLowerCase();
|
|
628
|
+
const limit = filter.limit ?? 50;
|
|
629
|
+
const assignee = filter.assignee === "currentUser" ? (await this.getMyself()).id : filter.assignee || void 0;
|
|
630
|
+
const found = [];
|
|
631
|
+
for (let page = 1; page <= TEXT_MAX_PAGES; page++) {
|
|
632
|
+
const raw = await this.client.issues.listIssues(this.repo, {
|
|
633
|
+
state: filter.openOnly ? "open" : "all",
|
|
634
|
+
sort: "updated",
|
|
635
|
+
direction: "desc",
|
|
636
|
+
per_page: TEXT_PAGE_SIZE,
|
|
637
|
+
page,
|
|
638
|
+
filter: "all",
|
|
639
|
+
...assignee ? { assignee } : {}
|
|
640
|
+
});
|
|
641
|
+
for (const issue of raw) {
|
|
642
|
+
if (issue.pull_request) continue;
|
|
643
|
+
if (`${issue.title}\n${issue.body ?? ""}`.toLowerCase().includes(needle)) {
|
|
644
|
+
found.push(this.mapIssue(issue));
|
|
645
|
+
if (found.length >= limit) return found;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (raw.length < TEXT_PAGE_SIZE) break;
|
|
649
|
+
}
|
|
650
|
+
return found;
|
|
651
|
+
}
|
|
652
|
+
/** Fetches one issue by its key. */
|
|
167
653
|
async get(key) {
|
|
168
654
|
const number = parseIssueNumber(key, this.owner, this.repoName);
|
|
169
655
|
const raw = await this.client.issues.getIssue(this.repo, number);
|
|
170
656
|
return this.mapIssue(raw);
|
|
171
657
|
}
|
|
658
|
+
/** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
|
|
172
659
|
async create(input) {
|
|
173
660
|
const body = { title: input.summary };
|
|
174
661
|
if (input.body) body.body = input.body;
|
|
@@ -216,10 +703,12 @@ var GitHubIssues = class {
|
|
|
216
703
|
via: `label set to ${targetLabel}`
|
|
217
704
|
};
|
|
218
705
|
}
|
|
706
|
+
/** Adds a comment to the issue with the given key. */
|
|
219
707
|
async comment(key, body) {
|
|
220
708
|
const number = parseIssueNumber(key, this.owner, this.repoName);
|
|
221
709
|
await this.client.issues.createComment(this.repo, number, body);
|
|
222
710
|
}
|
|
711
|
+
/** Checks the authenticated user, the repo and the label-backed lifecycle slots, and reports what resolves. */
|
|
223
712
|
async doctor() {
|
|
224
713
|
const me = await this.getMyself();
|
|
225
714
|
const repo = await this.client.repos.getRepo(this.repo);
|
|
@@ -288,6 +777,18 @@ var GitHubIssues = class {
|
|
|
288
777
|
lifecycle
|
|
289
778
|
};
|
|
290
779
|
}
|
|
780
|
+
/** Reads issues with their comments, priority label, parent and blockers, for `holocron migrate`. */
|
|
781
|
+
export(selector, info) {
|
|
782
|
+
return exportIssues(this.client, this.repo, selector, info);
|
|
783
|
+
}
|
|
784
|
+
/** Makes the records as issues; one already made by an earlier run is skipped. */
|
|
785
|
+
import(records, options) {
|
|
786
|
+
return importIssues(this.client, this.repo, records, options);
|
|
787
|
+
}
|
|
788
|
+
/** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
|
|
789
|
+
sync(records, options) {
|
|
790
|
+
return syncIssues(this.client, this.repo, records, options);
|
|
791
|
+
}
|
|
291
792
|
async resolveMilestone(ref) {
|
|
292
793
|
if (/^\d+$/.test(ref)) return parseInt(ref, 10);
|
|
293
794
|
const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
|
|
@@ -337,8 +838,584 @@ function parseIssueNumber(key, owner, repoName) {
|
|
|
337
838
|
if (!/^\d+$/.test(num)) throw new Error(`Invalid GitHub issue key "${key}" — expected #N or N.`);
|
|
338
839
|
return parseInt(num, 10);
|
|
339
840
|
}
|
|
340
|
-
|
|
341
|
-
|
|
841
|
+
// src/capabilities/projects.ts
|
|
842
|
+
/** The name of the single select field that holds an item's status. */
|
|
843
|
+
const STATUS_FIELD = "Status";
|
|
844
|
+
/** The name of the field `move` carries over besides the status. */
|
|
845
|
+
const PRIORITY_FIELD = "Priority";
|
|
846
|
+
const P_LEVELS = {
|
|
847
|
+
p0: "urgent",
|
|
848
|
+
p1: "high",
|
|
849
|
+
p2: "medium",
|
|
850
|
+
p3: "low"
|
|
851
|
+
};
|
|
852
|
+
/** The neutral priority a `Priority` option stands for, by its name; undefined for a name that is not one of them. */
|
|
853
|
+
function priorityOf(value) {
|
|
854
|
+
const name = value?.trim().toLowerCase();
|
|
855
|
+
if (name === "urgent" || name === "high" || name === "medium" || name === "low") return name;
|
|
856
|
+
return name ? P_LEVELS[name] : void 0;
|
|
857
|
+
}
|
|
858
|
+
const PROJECT_FIELDS = "id number title closed url";
|
|
859
|
+
const BOARD_QUERY = `query($id: ID!) { node(id: $id) { ... on ProjectV2 {
|
|
860
|
+
${PROJECT_FIELDS}
|
|
861
|
+
fields(first: 100) { nodes {
|
|
862
|
+
... on ProjectV2FieldCommon { id name dataType }
|
|
863
|
+
... on ProjectV2SingleSelectField { options { id name color description } }
|
|
864
|
+
} }
|
|
865
|
+
views(first: 50) { nodes { id name layout filter groupByFields(first: 5) { nodes { ... on ProjectV2FieldCommon { name } } } } }
|
|
866
|
+
workflows(first: 50) { nodes { id name enabled } }
|
|
867
|
+
} } }`;
|
|
868
|
+
const ITEMS_QUERY = `query($id: ID!, $after: String) { node(id: $id) { ... on ProjectV2 {
|
|
869
|
+
items(first: 100, after: $after) {
|
|
870
|
+
pageInfo { hasNextPage endCursor }
|
|
871
|
+
nodes {
|
|
872
|
+
id
|
|
873
|
+
fieldValues(first: 30) { nodes { ... on ProjectV2ItemFieldSingleSelectValue { name field { ... on ProjectV2FieldCommon { name } } } } }
|
|
874
|
+
content {
|
|
875
|
+
__typename
|
|
876
|
+
... on Issue { id number title state repository { nameWithOwner } blockedBy(first: 50) { nodes { number state repository { nameWithOwner } } } }
|
|
877
|
+
... on PullRequest { id number title state repository { nameWithOwner } }
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
} } }`;
|
|
882
|
+
const LIST_QUERY = `query($owner: String!, $after: String) { organization(login: $owner) { id projectsV2(first: 100, after: $after) {
|
|
883
|
+
pageInfo { hasNextPage endCursor }
|
|
884
|
+
nodes { ${PROJECT_FIELDS} }
|
|
885
|
+
} } }`;
|
|
886
|
+
const OWNER_QUERY = "query($owner: String!) { organization(login: $owner) { id } }";
|
|
887
|
+
const SET_VALUE = `mutation($project: ID!, $item: ID!, $field: ID!, $option: String!) {
|
|
888
|
+
updateProjectV2ItemFieldValue(input: { projectId: $project, itemId: $item, fieldId: $field, value: { singleSelectOptionId: $option } }) { projectV2Item { id } }
|
|
889
|
+
}`;
|
|
890
|
+
const UPDATE_OPTIONS = `mutation($field: ID!, $options: [ProjectV2SingleSelectFieldOptionInput!]!) {
|
|
891
|
+
updateProjectV2Field(input: { fieldId: $field, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
|
|
892
|
+
}`;
|
|
893
|
+
const DATA_TYPES = {
|
|
894
|
+
single_select: "SINGLE_SELECT",
|
|
895
|
+
text: "TEXT",
|
|
896
|
+
number: "NUMBER",
|
|
897
|
+
date: "DATE",
|
|
898
|
+
iteration: "ITERATION"
|
|
899
|
+
};
|
|
900
|
+
function fieldTypeOf(dataType) {
|
|
901
|
+
return Object.keys(DATA_TYPES).find((t) => DATA_TYPES[t] === dataType);
|
|
902
|
+
}
|
|
903
|
+
function toSummary(n) {
|
|
904
|
+
return {
|
|
905
|
+
id: n.id,
|
|
906
|
+
number: n.number,
|
|
907
|
+
name: n.title,
|
|
908
|
+
url: n.url,
|
|
909
|
+
closed: n.closed
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
function toOptionInput(o) {
|
|
913
|
+
return {
|
|
914
|
+
...o.id ? { id: o.id } : {},
|
|
915
|
+
name: o.name,
|
|
916
|
+
color: (o.color ?? "GRAY").toUpperCase(),
|
|
917
|
+
description: o.description ?? ""
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
/** The GitHub implementation of the `projects` capability, backed by Projects v2. */
|
|
921
|
+
var GitHubProjects = class {
|
|
922
|
+
graphql;
|
|
923
|
+
/** Capability key, always `"projects"`. */
|
|
924
|
+
key = "projects";
|
|
925
|
+
/** Provider name, always `"github"`. */
|
|
926
|
+
providerName = "github";
|
|
927
|
+
repo;
|
|
928
|
+
constructor(graphql, opts) {
|
|
929
|
+
this.graphql = graphql;
|
|
930
|
+
this.repo = opts.repo;
|
|
931
|
+
}
|
|
932
|
+
/** Every board of the organization, open and closed. */
|
|
933
|
+
async list(owner) {
|
|
934
|
+
const boards = [];
|
|
935
|
+
let after = null;
|
|
936
|
+
for (;;) {
|
|
937
|
+
const page = (await this.graphql.query(LIST_QUERY, {
|
|
938
|
+
owner,
|
|
939
|
+
after
|
|
940
|
+
})).organization.projectsV2;
|
|
941
|
+
boards.push(...page.nodes.map(toSummary));
|
|
942
|
+
if (!page.pageInfo.hasNextPage) return boards;
|
|
943
|
+
after = page.pageInfo.endCursor;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
/** The open board with exactly this name. */
|
|
947
|
+
async find(owner, name) {
|
|
948
|
+
return (await this.list(owner)).find((b) => !b.closed && b.name === name);
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* Makes a board. With `template.source` naming an open board it is copied (fields, options, views and automation
|
|
952
|
+
* rules, no items); otherwise the board is created and brought in line with the template.
|
|
953
|
+
*/
|
|
954
|
+
async create(owner, name, template) {
|
|
955
|
+
const ownerId = await this.ownerId(owner);
|
|
956
|
+
const source = template.source ? await this.find(owner, template.source) : void 0;
|
|
957
|
+
if (source) return toSummary((await this.graphql.query(`mutation($project: ID!, $owner: ID!, $title: String!) {
|
|
958
|
+
copyProjectV2(input: { projectId: $project, ownerId: $owner, title: $title, includeDraftIssues: false }) { projectV2 { ${PROJECT_FIELDS} } }
|
|
959
|
+
}`, {
|
|
960
|
+
project: source.id,
|
|
961
|
+
owner: ownerId,
|
|
962
|
+
title: name
|
|
963
|
+
})).copyProjectV2.projectV2);
|
|
964
|
+
const board = toSummary((await this.graphql.query(`mutation($owner: ID!, $title: String!) {
|
|
965
|
+
createProjectV2(input: { ownerId: $owner, title: $title }) { projectV2 { ${PROJECT_FIELDS} } }
|
|
966
|
+
}`, {
|
|
967
|
+
owner: ownerId,
|
|
968
|
+
title: name
|
|
969
|
+
})).createProjectV2.projectV2);
|
|
970
|
+
await this.ensure(owner, board, template);
|
|
971
|
+
return board;
|
|
972
|
+
}
|
|
973
|
+
/** Closes the board; `updateProjectV2` with `closed: true` is the only way, and reversible. */
|
|
974
|
+
async close(_owner, board) {
|
|
975
|
+
await this.graphql.query(`mutation($project: ID!) { updateProjectV2(input: { projectId: $project, closed: true }) { projectV2 { id } } }`, { project: board.id });
|
|
976
|
+
}
|
|
977
|
+
/** The live board: statuses, other fields, views and automation rules. */
|
|
978
|
+
async read(_owner, board) {
|
|
979
|
+
const raw = await this.readRaw(board.id);
|
|
980
|
+
const status = raw.fields.find((f) => f.name === STATUS_FIELD);
|
|
981
|
+
const fields = [];
|
|
982
|
+
for (const f of raw.fields) {
|
|
983
|
+
const type = fieldTypeOf(f.dataType);
|
|
984
|
+
if (!type || f.name === STATUS_FIELD) continue;
|
|
985
|
+
fields.push({
|
|
986
|
+
name: f.name,
|
|
987
|
+
type,
|
|
988
|
+
...f.options ? { options: f.options.map((o) => o.name) } : {}
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
const views = [];
|
|
992
|
+
for (const v of raw.views) {
|
|
993
|
+
const layout = v.layout === "BOARD_LAYOUT" ? "board" : v.layout === "TABLE_LAYOUT" ? "table" : void 0;
|
|
994
|
+
if (!layout) continue;
|
|
995
|
+
views.push({
|
|
996
|
+
name: v.name,
|
|
997
|
+
layout,
|
|
998
|
+
...v.filter ? { filter: v.filter } : {},
|
|
999
|
+
...v.groupBy[0] ? { groupBy: v.groupBy[0] } : {}
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
return {
|
|
1003
|
+
board: raw.summary,
|
|
1004
|
+
statuses: (status?.options ?? []).map((o) => o.name),
|
|
1005
|
+
fields,
|
|
1006
|
+
views,
|
|
1007
|
+
rules: raw.rules.map(({ name, enabled }) => ({
|
|
1008
|
+
name,
|
|
1009
|
+
enabled
|
|
1010
|
+
}))
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Brings the board in line with the template. Never deletes a field, option or view, and never sends an option
|
|
1015
|
+
* list without ids. Stops (throws) when the status field cannot be read.
|
|
1016
|
+
*/
|
|
1017
|
+
async ensure(_owner, board, template) {
|
|
1018
|
+
const raw = await this.readRaw(board.id);
|
|
1019
|
+
const status = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
|
|
1020
|
+
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`);
|
|
1021
|
+
const changes = [];
|
|
1022
|
+
const todos = [];
|
|
1023
|
+
const statusChanges = await this.ensureOptions(board, status, template.statuses.map((s) => ({
|
|
1024
|
+
name: s.name,
|
|
1025
|
+
color: s.color,
|
|
1026
|
+
description: s.description
|
|
1027
|
+
})));
|
|
1028
|
+
changes.push(...statusChanges.map((c) => `status ${c}`));
|
|
1029
|
+
for (const want of template.fields) {
|
|
1030
|
+
const have = raw.fields.find((f) => f.name === want.name);
|
|
1031
|
+
if (!have) {
|
|
1032
|
+
await this.createField(board.id, want);
|
|
1033
|
+
changes.push(`field ${want.name} created`);
|
|
1034
|
+
continue;
|
|
1035
|
+
}
|
|
1036
|
+
if (fieldTypeOf(have.dataType) !== want.type) {
|
|
1037
|
+
todos.push(`field "${want.name}" is ${have.dataType} but the template says ${want.type}; change it by hand`);
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
if (want.type === "single_select" && have.options && want.options) {
|
|
1041
|
+
const diff = await this.ensureOptions(board, have, want.options.map((name) => ({ name })));
|
|
1042
|
+
changes.push(...diff.map((c) => `field ${want.name} option ${c}`));
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
for (const want of template.views) {
|
|
1046
|
+
const have = raw.views.find((v) => v.name === want.name);
|
|
1047
|
+
const layout = want.layout === "board" ? "BOARD_LAYOUT" : "TABLE_LAYOUT";
|
|
1048
|
+
let viewId = have?.id;
|
|
1049
|
+
if (!viewId) {
|
|
1050
|
+
viewId = await this.createView(board.id, want.name, layout);
|
|
1051
|
+
changes.push(`view ${want.name} created`);
|
|
1052
|
+
} else if (have && have.layout !== layout) {
|
|
1053
|
+
await this.updateView(viewId, { layout });
|
|
1054
|
+
changes.push(`view ${want.name} layout set to ${want.layout}`);
|
|
1055
|
+
}
|
|
1056
|
+
if (want.filter !== void 0 && want.filter !== (have?.filter ?? "")) {
|
|
1057
|
+
await this.updateView(viewId, { filter: want.filter });
|
|
1058
|
+
changes.push(`view ${want.name} filter set`);
|
|
1059
|
+
}
|
|
1060
|
+
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`);
|
|
1061
|
+
}
|
|
1062
|
+
for (const rule of template.rules ?? []) {
|
|
1063
|
+
const have = raw.rules.find((r) => r.name === rule);
|
|
1064
|
+
if (!have) todos.push(`create the automation rule "${rule}"; the API cannot create one`);
|
|
1065
|
+
else if (!have.enabled) todos.push(`turn on the automation rule "${rule}"; the API cannot switch one`);
|
|
1066
|
+
}
|
|
1067
|
+
return {
|
|
1068
|
+
created: false,
|
|
1069
|
+
changes,
|
|
1070
|
+
todos
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Makes a single select field hold the wanted options in order, every existing one sent with its id. Options the
|
|
1075
|
+
* template does not mention stay, after the wanted ones. Returns what changed (`Blocked added`, `order set`).
|
|
1076
|
+
*/
|
|
1077
|
+
async ensureOptions(board, field, wanted) {
|
|
1078
|
+
/* v8 ignore next -- every caller passes a field it found with options; the fallback only satisfies the type */
|
|
1079
|
+
const existing = field.options ?? [];
|
|
1080
|
+
const next = [];
|
|
1081
|
+
const changes = [];
|
|
1082
|
+
for (const w of wanted) {
|
|
1083
|
+
const have = existing.find((o) => o.name === w.name);
|
|
1084
|
+
if (have) {
|
|
1085
|
+
next.push({
|
|
1086
|
+
id: have.id,
|
|
1087
|
+
name: have.name,
|
|
1088
|
+
color: (w.color ?? have.color).toUpperCase(),
|
|
1089
|
+
description: w.description ?? have.description
|
|
1090
|
+
});
|
|
1091
|
+
if (next[next.length - 1].color !== have.color || next[next.length - 1].description !== have.description) changes.push(`${have.name} updated`);
|
|
1092
|
+
} else {
|
|
1093
|
+
next.push({
|
|
1094
|
+
name: w.name,
|
|
1095
|
+
color: (w.color ?? "GRAY").toUpperCase(),
|
|
1096
|
+
description: w.description ?? ""
|
|
1097
|
+
});
|
|
1098
|
+
changes.push(`${w.name} added`);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
for (const have of existing) if (!next.some((n) => n.id === have.id)) next.push({ ...have });
|
|
1102
|
+
const sameOrder = next.length === existing.length && next.every((n, i) => n.id === existing[i]?.id);
|
|
1103
|
+
if (changes.length === 0 && sameOrder) return [];
|
|
1104
|
+
if (sameOrder === false && !changes.some((c) => c.endsWith("added"))) changes.push("order set");
|
|
1105
|
+
const before = await this.fetchItems(board.id);
|
|
1106
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
1107
|
+
for (const item of before) {
|
|
1108
|
+
const value = item.values[field.name];
|
|
1109
|
+
if (value) snapshot.set(item.id, value);
|
|
1110
|
+
}
|
|
1111
|
+
await this.graphql.query(UPDATE_OPTIONS, {
|
|
1112
|
+
field: field.id,
|
|
1113
|
+
options: next.map(toOptionInput)
|
|
1114
|
+
});
|
|
1115
|
+
const afterField = (await this.readRaw(board.id)).fields.find((f) => f.id === field.id);
|
|
1116
|
+
const afterItems = await this.fetchItems(board.id);
|
|
1117
|
+
const afterValues = new Map(afterItems.map((i) => [i.id, i.values[field.name]]));
|
|
1118
|
+
const lost = [...snapshot].filter(([itemId]) => !afterValues.get(itemId));
|
|
1119
|
+
if (lost.length > 0) {
|
|
1120
|
+
let restored = 0;
|
|
1121
|
+
for (const [itemId, name] of lost) {
|
|
1122
|
+
const option = afterField?.options?.find((o) => o.name === name);
|
|
1123
|
+
if (!option) continue;
|
|
1124
|
+
await this.graphql.query(SET_VALUE, {
|
|
1125
|
+
project: board.id,
|
|
1126
|
+
item: itemId,
|
|
1127
|
+
field: field.id,
|
|
1128
|
+
option: option.id
|
|
1129
|
+
});
|
|
1130
|
+
restored++;
|
|
1131
|
+
}
|
|
1132
|
+
throw new Error(`updating "${field.name}" on board "${board.name}" blanked ${lost.length} item value(s); wrote ${restored} back by option name`);
|
|
1133
|
+
}
|
|
1134
|
+
return changes;
|
|
1135
|
+
}
|
|
1136
|
+
async createField(projectId, want) {
|
|
1137
|
+
await this.graphql.query(`mutation($project: ID!, $name: String!, $type: ProjectV2CustomFieldType!, $options: [ProjectV2SingleSelectFieldOptionInput!]) {
|
|
1138
|
+
createProjectV2Field(input: { projectId: $project, name: $name, dataType: $type, singleSelectOptions: $options }) { projectV2Field { ... on ProjectV2SingleSelectField { id } } }
|
|
1139
|
+
}`, {
|
|
1140
|
+
project: projectId,
|
|
1141
|
+
name: want.name,
|
|
1142
|
+
type: DATA_TYPES[want.type],
|
|
1143
|
+
options: want.type === "single_select" ? (want.options ?? []).map((name) => toOptionInput({ name })) : void 0
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
async createView(projectId, name, layout) {
|
|
1147
|
+
return (await this.graphql.query(`mutation($project: ID!, $name: String!, $layout: ProjectV2ViewLayout!) {
|
|
1148
|
+
createProjectV2View(input: { projectId: $project, name: $name, layout: $layout }) { projectV2View { id } }
|
|
1149
|
+
}`, {
|
|
1150
|
+
project: projectId,
|
|
1151
|
+
name,
|
|
1152
|
+
layout
|
|
1153
|
+
})).createProjectV2View.projectV2View.id;
|
|
1154
|
+
}
|
|
1155
|
+
async updateView(viewId, change) {
|
|
1156
|
+
await this.graphql.query(`mutation($view: ID!, $layout: ProjectV2ViewLayout, $filter: String) {
|
|
1157
|
+
updateProjectV2View(input: { viewId: $view, layout: $layout, filter: $filter }) { projectV2View { id } }
|
|
1158
|
+
}`, {
|
|
1159
|
+
view: viewId,
|
|
1160
|
+
layout: change.layout,
|
|
1161
|
+
filter: change.filter
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
/** The board's issues and pull requests with their status, whether they are open and their open blockers. */
|
|
1165
|
+
async items(_owner, board, template) {
|
|
1166
|
+
const categories = new Map(template.statuses.map((s) => [s.name, s.category]));
|
|
1167
|
+
return (await this.fetchItems(board.id)).map((i) => {
|
|
1168
|
+
const status = i.values[STATUS_FIELD];
|
|
1169
|
+
const category = status ? categories.get(status) : void 0;
|
|
1170
|
+
const priority = priorityOf(i.values[PRIORITY_FIELD]);
|
|
1171
|
+
return {
|
|
1172
|
+
key: this.keyOf(i.repo, i.number),
|
|
1173
|
+
title: i.title,
|
|
1174
|
+
open: i.open,
|
|
1175
|
+
...status ? { status } : {},
|
|
1176
|
+
...category ? { category } : {},
|
|
1177
|
+
blockedBy: i.blockers.map((b) => this.keyOf(b.repo, b.number)),
|
|
1178
|
+
...priority ? { priority } : {}
|
|
1179
|
+
};
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
/** Puts an item in a status; `transitioned` is false when it already is there. */
|
|
1183
|
+
async setStatus(_owner, board, key, status) {
|
|
1184
|
+
const ref = this.parseKey(key);
|
|
1185
|
+
const field = (await this.readRaw(board.id)).fields.find((f) => f.name === STATUS_FIELD && f.options);
|
|
1186
|
+
const option = field?.options?.find((o) => o.name === status);
|
|
1187
|
+
if (!field || !option) throw new Error(`board "${board.name}" has no status "${status}"`);
|
|
1188
|
+
const item = (await this.fetchItems(board.id)).find((i) => i.repo === ref.repo && i.number === ref.number);
|
|
1189
|
+
if (!item) throw new Error(`${key} is not on board "${board.name}"`);
|
|
1190
|
+
if (item.values[STATUS_FIELD] === status) return {
|
|
1191
|
+
transitioned: false,
|
|
1192
|
+
status
|
|
1193
|
+
};
|
|
1194
|
+
await this.graphql.query(SET_VALUE, {
|
|
1195
|
+
project: board.id,
|
|
1196
|
+
item: item.id,
|
|
1197
|
+
field: field.id,
|
|
1198
|
+
option: option.id
|
|
1199
|
+
});
|
|
1200
|
+
return {
|
|
1201
|
+
transitioned: true,
|
|
1202
|
+
status,
|
|
1203
|
+
via: "project field set"
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Puts the open items of `from` on `to` with their status and priority, only where the target has no value;
|
|
1208
|
+
* closed and merged ones stay, and are set to the template's done status when theirs is not a done one.
|
|
1209
|
+
*/
|
|
1210
|
+
async move(_owner, from, to, template) {
|
|
1211
|
+
const report = {
|
|
1212
|
+
moved: [],
|
|
1213
|
+
kept: [],
|
|
1214
|
+
left: []
|
|
1215
|
+
};
|
|
1216
|
+
const [source, target, fromRaw, toRaw] = await Promise.all([
|
|
1217
|
+
this.fetchItems(from.id),
|
|
1218
|
+
this.fetchItems(to.id),
|
|
1219
|
+
this.readRaw(from.id),
|
|
1220
|
+
this.readRaw(to.id)
|
|
1221
|
+
]);
|
|
1222
|
+
const done = template.statuses.find((s) => s.category === "done")?.name;
|
|
1223
|
+
const doneNames = new Set(template.statuses.filter((s) => s.category === "done").map((s) => s.name));
|
|
1224
|
+
const carried = [STATUS_FIELD, PRIORITY_FIELD];
|
|
1225
|
+
for (const item of source) {
|
|
1226
|
+
const key = this.keyOf(item.repo, item.number);
|
|
1227
|
+
if (!item.open) {
|
|
1228
|
+
const current = item.values[STATUS_FIELD];
|
|
1229
|
+
if (done && (!current || !doneNames.has(current))) await this.setOption(from.id, fromRaw, item.id, STATUS_FIELD, done);
|
|
1230
|
+
report.left.push(key);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
let targetItem = target.find((t) => t.contentId === item.contentId);
|
|
1234
|
+
if (targetItem) report.kept.push(key);
|
|
1235
|
+
else {
|
|
1236
|
+
const data = await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
|
|
1237
|
+
project: to.id,
|
|
1238
|
+
content: item.contentId
|
|
1239
|
+
});
|
|
1240
|
+
targetItem = {
|
|
1241
|
+
...item,
|
|
1242
|
+
id: data.addProjectV2ItemById.item.id,
|
|
1243
|
+
values: {}
|
|
1244
|
+
};
|
|
1245
|
+
report.moved.push(key);
|
|
1246
|
+
}
|
|
1247
|
+
for (const name of carried) {
|
|
1248
|
+
const value = item.values[name];
|
|
1249
|
+
if (value && !targetItem.values[name]) await this.setOption(to.id, toRaw, targetItem.id, name, value);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
return report;
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Puts issues on the board (`addProjectV2ItemById`, the content id the issue's node id) and sets Status and Priority
|
|
1256
|
+
* through the single select update, only where the item has no value yet. A status or priority with no option on
|
|
1257
|
+
* the board is reported in `dropped`; no option is ever created, so no value is cleared.
|
|
1258
|
+
*/
|
|
1259
|
+
async addItems(_owner, board, items, template) {
|
|
1260
|
+
const raw = await this.readRaw(board.id);
|
|
1261
|
+
const onBoard = await this.fetchItems(board.id);
|
|
1262
|
+
const statusField = raw.fields.find((f) => f.name === STATUS_FIELD && f.options);
|
|
1263
|
+
const priorityField = raw.fields.find((f) => f.name === PRIORITY_FIELD && f.options);
|
|
1264
|
+
const results = [];
|
|
1265
|
+
for (const input of items) {
|
|
1266
|
+
const ref = this.parseKey(input.key);
|
|
1267
|
+
let current = onBoard.find((i) => i.repo === ref.repo && i.number === ref.number);
|
|
1268
|
+
const added = !current;
|
|
1269
|
+
if (!current) current = {
|
|
1270
|
+
id: (await this.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
|
|
1271
|
+
project: board.id,
|
|
1272
|
+
content: await this.nodeId(ref)
|
|
1273
|
+
})).addProjectV2ItemById.item.id,
|
|
1274
|
+
contentId: "",
|
|
1275
|
+
repo: ref.repo,
|
|
1276
|
+
number: ref.number,
|
|
1277
|
+
title: "",
|
|
1278
|
+
open: true,
|
|
1279
|
+
values: {},
|
|
1280
|
+
blockers: []
|
|
1281
|
+
};
|
|
1282
|
+
const dropped = [];
|
|
1283
|
+
if (input.status !== void 0 || input.category !== void 0) {
|
|
1284
|
+
const name = this.statusFor(input, template, statusField?.options);
|
|
1285
|
+
if (!name) dropped.push(`status ${input.status ?? input.category} (no matching option on the board)`);
|
|
1286
|
+
else if (!current.values[STATUS_FIELD]) await this.setOption(board.id, raw, current.id, STATUS_FIELD, name);
|
|
1287
|
+
}
|
|
1288
|
+
if (input.priority !== void 0 && input.priority !== "none") {
|
|
1289
|
+
const option = priorityField?.options?.find((o) => priorityOf(o.name) === input.priority);
|
|
1290
|
+
if (!option) dropped.push(`priority ${input.priority} (no matching option on the board)`);
|
|
1291
|
+
else if (!current.values[PRIORITY_FIELD]) await this.setOption(board.id, raw, current.id, PRIORITY_FIELD, option.name);
|
|
1292
|
+
}
|
|
1293
|
+
results.push({
|
|
1294
|
+
key: input.key,
|
|
1295
|
+
added,
|
|
1296
|
+
dropped
|
|
1297
|
+
});
|
|
1298
|
+
}
|
|
1299
|
+
return results;
|
|
1300
|
+
}
|
|
1301
|
+
/** The board's own status for an input: the option named like its status, else the template's status of its category. */
|
|
1302
|
+
statusFor(input, template, options) {
|
|
1303
|
+
const has = (name) => options?.find((o) => o.name.toLowerCase() === name.toLowerCase())?.name;
|
|
1304
|
+
const named = input.status === void 0 ? void 0 : has(input.status);
|
|
1305
|
+
if (named) return named;
|
|
1306
|
+
const byCategory = template.statuses.find((s) => s.category === input.category);
|
|
1307
|
+
return byCategory ? has(byCategory.name) : void 0;
|
|
1308
|
+
}
|
|
1309
|
+
/** The node id of an issue, which `addProjectV2ItemById` takes as the content id. */
|
|
1310
|
+
async nodeId(ref) {
|
|
1311
|
+
const [owner, name] = ref.repo.split("/");
|
|
1312
|
+
const id = (await this.graphql.query(`query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { id } } }`, {
|
|
1313
|
+
owner,
|
|
1314
|
+
name,
|
|
1315
|
+
number: ref.number
|
|
1316
|
+
})).repository?.issue?.id;
|
|
1317
|
+
if (!id) throw new Error(`issue ${ref.repo}#${ref.number} not found`);
|
|
1318
|
+
return id;
|
|
1319
|
+
}
|
|
1320
|
+
/** A `holocron doctor` smoke check: how many boards the token sees in the configured repository's organization. */
|
|
1321
|
+
async whoami() {
|
|
1322
|
+
try {
|
|
1323
|
+
return {
|
|
1324
|
+
ok: true,
|
|
1325
|
+
boards: (await this.list(this.repo.split("/")[0] ?? "")).length
|
|
1326
|
+
};
|
|
1327
|
+
} catch {
|
|
1328
|
+
return {
|
|
1329
|
+
ok: false,
|
|
1330
|
+
boards: 0
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
/** Sets a single select value by option name; a field or option the board lacks is skipped. */
|
|
1335
|
+
async setOption(projectId, raw, itemId, fieldName, optionName) {
|
|
1336
|
+
const field = raw.fields.find((f) => f.name === fieldName && f.options);
|
|
1337
|
+
const option = field?.options?.find((o) => o.name === optionName);
|
|
1338
|
+
if (!field || !option) return;
|
|
1339
|
+
await this.graphql.query(SET_VALUE, {
|
|
1340
|
+
project: projectId,
|
|
1341
|
+
item: itemId,
|
|
1342
|
+
field: field.id,
|
|
1343
|
+
option: option.id
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
async ownerId(owner) {
|
|
1347
|
+
return (await this.graphql.query(OWNER_QUERY, { owner })).organization.id;
|
|
1348
|
+
}
|
|
1349
|
+
async readRaw(id) {
|
|
1350
|
+
const n = (await this.graphql.query(BOARD_QUERY, { id })).node;
|
|
1351
|
+
if (!n) throw new Error(`board ${id} not found`);
|
|
1352
|
+
return {
|
|
1353
|
+
summary: toSummary(n),
|
|
1354
|
+
fields: n.fields.nodes.filter((f) => f.id).map((f) => ({
|
|
1355
|
+
id: f.id,
|
|
1356
|
+
name: f.name,
|
|
1357
|
+
dataType: f.dataType,
|
|
1358
|
+
...f.options ? { options: f.options } : {}
|
|
1359
|
+
})),
|
|
1360
|
+
views: n.views.nodes.map((v) => ({
|
|
1361
|
+
id: v.id,
|
|
1362
|
+
name: v.name,
|
|
1363
|
+
layout: v.layout,
|
|
1364
|
+
filter: v.filter,
|
|
1365
|
+
groupBy: (v.groupByFields?.nodes ?? []).map((g) => g.name)
|
|
1366
|
+
})),
|
|
1367
|
+
rules: n.workflows.nodes.map((w) => ({
|
|
1368
|
+
id: w.id,
|
|
1369
|
+
name: w.name,
|
|
1370
|
+
enabled: w.enabled
|
|
1371
|
+
}))
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
async fetchItems(id) {
|
|
1375
|
+
const items = [];
|
|
1376
|
+
let after = null;
|
|
1377
|
+
for (;;) {
|
|
1378
|
+
const page = (await this.graphql.query(ITEMS_QUERY, {
|
|
1379
|
+
id,
|
|
1380
|
+
after
|
|
1381
|
+
})).node.items;
|
|
1382
|
+
for (const n of page.nodes) {
|
|
1383
|
+
const c = n.content;
|
|
1384
|
+
if (!c || !c.repository) continue;
|
|
1385
|
+
const values = {};
|
|
1386
|
+
for (const v of n.fieldValues.nodes) if (v.name && v.field?.name) values[v.field.name] = v.name;
|
|
1387
|
+
items.push({
|
|
1388
|
+
id: n.id,
|
|
1389
|
+
contentId: c.id,
|
|
1390
|
+
repo: c.repository.nameWithOwner,
|
|
1391
|
+
number: c.number,
|
|
1392
|
+
title: c.title,
|
|
1393
|
+
open: c.state === "OPEN",
|
|
1394
|
+
values,
|
|
1395
|
+
blockers: (c.blockedBy?.nodes ?? []).filter((b) => b.state === "OPEN").map((b) => ({
|
|
1396
|
+
repo: b.repository.nameWithOwner,
|
|
1397
|
+
number: b.number
|
|
1398
|
+
}))
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
if (!page.pageInfo.hasNextPage) return items;
|
|
1402
|
+
after = page.pageInfo.endCursor;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
keyOf(repo, number) {
|
|
1406
|
+
return repo === this.repo ? `#${number}` : `${repo}#${number}`;
|
|
1407
|
+
}
|
|
1408
|
+
parseKey(key) {
|
|
1409
|
+
const m = /^(?:([^#\s]+))?#?(\d+)$/.exec(key.trim());
|
|
1410
|
+
const hasRepo = key.includes("#") && m?.[1];
|
|
1411
|
+
if (!m) throw new Error(`not an issue key: ${key}`);
|
|
1412
|
+
return {
|
|
1413
|
+
repo: hasRepo ? m[1] : this.repo,
|
|
1414
|
+
number: Number(m[2])
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
// src/sodium.ts
|
|
342
1419
|
/**
|
|
343
1420
|
* libsodium sealed-box encryption for GitHub Actions secrets.
|
|
344
1421
|
*
|
|
@@ -369,32 +1446,86 @@ async function encryptSecret(publicKeyBase64, value) {
|
|
|
369
1446
|
const ciphertext = sodium.crypto_box_seal(plaintext, publicKey);
|
|
370
1447
|
return sodium.to_base64(ciphertext, sodium.base64_variants.ORIGINAL);
|
|
371
1448
|
}
|
|
372
|
-
|
|
373
|
-
|
|
1449
|
+
// src/capabilities/secrets.ts
|
|
1450
|
+
/** The GitHub implementation of the `secrets` capability, covering repository, environment and organization secrets. */
|
|
374
1451
|
var GitHubSecrets = class {
|
|
375
1452
|
client;
|
|
376
1453
|
opts;
|
|
1454
|
+
orgClient;
|
|
1455
|
+
/** Capability key, always `"secrets"`. */
|
|
377
1456
|
key = "secrets";
|
|
1457
|
+
/** Provider name, always `"github"`. */
|
|
378
1458
|
providerName = "github";
|
|
379
|
-
|
|
1459
|
+
/**
|
|
1460
|
+
* `client` handles repo and environment scopes; `orgClient`, when given, handles
|
|
1461
|
+
* the organization scope. They differ when a dedicated org-only token exists:
|
|
1462
|
+
* it can write org secrets but not repo ones, and `github.admin` is the reverse.
|
|
1463
|
+
*/
|
|
1464
|
+
constructor(client, opts, orgClient) {
|
|
380
1465
|
this.client = client;
|
|
381
1466
|
this.opts = opts;
|
|
1467
|
+
this.orgClient = orgClient;
|
|
1468
|
+
}
|
|
1469
|
+
/** Repository name to numeric id, so one run asks GitHub once per repository however many secrets name it. */
|
|
1470
|
+
repoIds = /* @__PURE__ */ new Map();
|
|
1471
|
+
clientFor(scope) {
|
|
1472
|
+
return scope.kind === "organization" ? this.orgClient ?? this.client : this.client;
|
|
382
1473
|
}
|
|
383
1474
|
async listSecrets(scope) {
|
|
384
|
-
return this.
|
|
1475
|
+
return this.clientFor(scope).secrets.listSecrets(this.opts.repo, toGHScope(scope));
|
|
385
1476
|
}
|
|
386
1477
|
async setSecret(scope, name, value) {
|
|
387
1478
|
const ghScope = toGHScope(scope);
|
|
388
|
-
const
|
|
1479
|
+
const client = this.clientFor(scope);
|
|
1480
|
+
const readers = scope.kind === "organization" ? await this.readers(scope) : {};
|
|
1481
|
+
const pk = await client.secrets.getPublicKey(this.opts.repo, ghScope);
|
|
389
1482
|
const body = {
|
|
390
1483
|
encrypted_value: await encryptSecret(pk.key, value),
|
|
391
1484
|
key_id: pk.key_id
|
|
392
1485
|
};
|
|
393
|
-
|
|
394
|
-
await
|
|
1486
|
+
Object.assign(body, readers);
|
|
1487
|
+
await client.secrets.putSecret(this.opts.repo, ghScope, name, body);
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Who can read each organization secret, by name (never a value): `selected` ones come with the names of their
|
|
1491
|
+
* repositories. Any other scope has no visibility and gives `{}`.
|
|
1492
|
+
*/
|
|
1493
|
+
async listSecretAccess(scope) {
|
|
1494
|
+
if (scope.kind !== "organization") return {};
|
|
1495
|
+
const client = this.clientFor(scope);
|
|
1496
|
+
const found = {};
|
|
1497
|
+
for (const info of await client.secrets.listOrgSecretInfo(scope.name)) found[info.name] = info.visibility === "selected" ? {
|
|
1498
|
+
visibility: "selected",
|
|
1499
|
+
repos: await client.secrets.listSelectedRepositories(scope.name, info.name)
|
|
1500
|
+
} : { visibility: info.visibility };
|
|
1501
|
+
return found;
|
|
1502
|
+
}
|
|
1503
|
+
/** The `visibility` (and repository ids) of an organization write. No `visibility` keeps the older default, `all`. */
|
|
1504
|
+
async readers(scope) {
|
|
1505
|
+
const visibility = scope.visibility ?? "all";
|
|
1506
|
+
if (visibility !== "selected") return { visibility };
|
|
1507
|
+
if (!scope.repos?.length) throw new Error(`organization secret with visibility "selected" needs a non-empty repos list`);
|
|
1508
|
+
const ids = [];
|
|
1509
|
+
for (const name of scope.repos) ids.push(await this.repoId(scope.name, name));
|
|
1510
|
+
return {
|
|
1511
|
+
visibility,
|
|
1512
|
+
selected_repository_ids: ids
|
|
1513
|
+
};
|
|
395
1514
|
}
|
|
1515
|
+
repoId(org, name) {
|
|
1516
|
+
const full = `${org}/${name}`;
|
|
1517
|
+
let id = this.repoIds.get(full);
|
|
1518
|
+
if (!id) {
|
|
1519
|
+
id = this.client.repos.getRepo(full).then((repo) => repo.id, (err) => {
|
|
1520
|
+
throw new Error(`could not resolve repository ${full}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1521
|
+
});
|
|
1522
|
+
this.repoIds.set(full, id);
|
|
1523
|
+
}
|
|
1524
|
+
return id;
|
|
1525
|
+
}
|
|
1526
|
+
/** Deletes the named secret in the given scope. */
|
|
396
1527
|
async deleteSecret(scope, name) {
|
|
397
|
-
await this.
|
|
1528
|
+
await this.clientFor(scope).secrets.deleteSecret(this.opts.repo, toGHScope(scope), name);
|
|
398
1529
|
}
|
|
399
1530
|
};
|
|
400
1531
|
function toGHScope(scope) {
|
|
@@ -404,8 +1535,46 @@ function toGHScope(scope) {
|
|
|
404
1535
|
};
|
|
405
1536
|
return scope;
|
|
406
1537
|
}
|
|
407
|
-
|
|
408
|
-
|
|
1538
|
+
// src/capabilities/files.ts
|
|
1539
|
+
/** Reads one file; `null` when it does not exist. `version` is the blob sha `writeFile` needs to replace exactly this one. */
|
|
1540
|
+
/** A fine-grained token only reaches the repositories and permissions it was given; say which one is missing. */
|
|
1541
|
+
function noAccess(repo, action, cause) {
|
|
1542
|
+
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 });
|
|
1543
|
+
}
|
|
1544
|
+
async function readRepoFile(client, repo, path) {
|
|
1545
|
+
try {
|
|
1546
|
+
const file = await client.git.getContents(repo, path);
|
|
1547
|
+
if (file.encoding !== "base64") throw new Error(`${repo}/${path}: unexpected encoding \`${file.encoding}\``);
|
|
1548
|
+
return {
|
|
1549
|
+
content: Buffer.from(file.content, "base64").toString("utf-8"),
|
|
1550
|
+
version: file.sha
|
|
1551
|
+
};
|
|
1552
|
+
} catch (err) {
|
|
1553
|
+
if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "read", err);
|
|
1554
|
+
if (!(err instanceof ProviderApiError && err.status === 404)) throw err;
|
|
1555
|
+
}
|
|
1556
|
+
try {
|
|
1557
|
+
await client.repos.getRepo(repo);
|
|
1558
|
+
} catch (err) {
|
|
1559
|
+
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 });
|
|
1560
|
+
throw err;
|
|
1561
|
+
}
|
|
1562
|
+
return null;
|
|
1563
|
+
}
|
|
1564
|
+
/** Creates or replaces one file in a commit; GitHub refuses (409) a `version` that has since changed. */
|
|
1565
|
+
async function writeRepoFile(client, repo, path, content, opts) {
|
|
1566
|
+
try {
|
|
1567
|
+
await client.git.putContents(repo, path, {
|
|
1568
|
+
message: opts.message,
|
|
1569
|
+
content,
|
|
1570
|
+
...opts.version ? { sha: opts.version } : {}
|
|
1571
|
+
});
|
|
1572
|
+
} catch (err) {
|
|
1573
|
+
if (err instanceof ProviderApiError && err.status === 403) throw noAccess(repo, "write", err);
|
|
1574
|
+
throw err;
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
// src/capabilities/labels.ts
|
|
409
1578
|
/**
|
|
410
1579
|
* Idempotently synchronise a repo's labels to the canonical set.
|
|
411
1580
|
*
|
|
@@ -443,14 +1612,208 @@ async function syncLabels(client, repo, canonical, stale) {
|
|
|
443
1612
|
}
|
|
444
1613
|
return `${created} created, ${updated} updated, ${deleted} deleted`;
|
|
445
1614
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
1615
|
+
// src/capabilities/property-fix-hints.ts
|
|
1616
|
+
/** GitHub's wording when a custom property value is not one the organization's definition allows. */
|
|
1617
|
+
const NOT_ALLOWED = /Value '([^']+)' is not allowed for property '([^']+)'/g;
|
|
1618
|
+
/**
|
|
1619
|
+
* What to do about each value GitHub says an organization custom property does not allow, one sentence per property,
|
|
1620
|
+
* read from GitHub's own message so it works even when the organization's definitions cannot be read. The values
|
|
1621
|
+
* belong to the organization's definition, not to the repository, so the fix is to add them there: a repository cannot
|
|
1622
|
+
* make its own value allowed. Empty when GitHub's message names no such value.
|
|
1623
|
+
*/
|
|
1624
|
+
function propertyFixHints(githubMessage) {
|
|
1625
|
+
const byProperty = /* @__PURE__ */ new Map();
|
|
1626
|
+
for (const [, value, property] of githubMessage.matchAll(NOT_ALLOWED)) {
|
|
1627
|
+
const values = byProperty.get(property) ?? [];
|
|
1628
|
+
if (!values.includes(value)) values.push(value);
|
|
1629
|
+
byProperty.set(property, values);
|
|
1630
|
+
}
|
|
1631
|
+
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`);
|
|
1632
|
+
}
|
|
1633
|
+
// src/capabilities/rejected-properties.ts
|
|
1634
|
+
/** The values `setup` sends for `true_false` properties; anything else is rejected. */
|
|
1635
|
+
const BOOLEANS = /* @__PURE__ */ new Set(["true", "false"]);
|
|
1636
|
+
/**
|
|
1637
|
+
* What is wrong with `values` when compared with the organization's property definitions, one sentence per
|
|
1638
|
+
* problem, in the order the properties are given: a property the organization does not define, a value a
|
|
1639
|
+
* `single_select` or `multi_select` property does not allow, or a `true_false` property that is not `true` or
|
|
1640
|
+
* `false`. A `string` or `url` property has nothing to check here. Empty when every value fits its definition.
|
|
1641
|
+
*/
|
|
1642
|
+
function rejectedProperties(values, schema) {
|
|
1643
|
+
const byName = new Map(schema.map((property) => [property.property_name, property]));
|
|
1644
|
+
const problems = [];
|
|
1645
|
+
for (const [name, value] of Object.entries(values)) {
|
|
1646
|
+
const definition = byName.get(name);
|
|
1647
|
+
if (!definition) {
|
|
1648
|
+
problems.push(`${name} is not a custom property of the organization`);
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
const sent = Array.isArray(value) ? value : [value];
|
|
1652
|
+
if (definition.value_type === "true_false") {
|
|
1653
|
+
for (const item of sent.filter((item) => !BOOLEANS.has(item))) problems.push(`${name} is "${item}", but it takes only true or false`);
|
|
1654
|
+
continue;
|
|
1655
|
+
}
|
|
1656
|
+
const allowed = definition.allowed_values ?? [];
|
|
1657
|
+
if (definition.value_type !== "single_select" && definition.value_type !== "multi_select") continue;
|
|
1658
|
+
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(", ")})`);
|
|
1659
|
+
}
|
|
1660
|
+
return problems;
|
|
1661
|
+
}
|
|
1662
|
+
// src/capabilities/properties.ts
|
|
1663
|
+
/** GitHub's own message from a 422 body (`{"message": ..., "errors": [...]}`), or the start of the body when it is not JSON. */
|
|
1664
|
+
function githubMessage(details) {
|
|
1665
|
+
const raw = String(details ?? "").trim();
|
|
1666
|
+
try {
|
|
1667
|
+
const body = JSON.parse(raw);
|
|
1668
|
+
const errors = Array.isArray(body.errors) ? body.errors.map((e) => JSON.stringify(e)).join(", ") : "";
|
|
1669
|
+
const message = typeof body.message === "string" ? body.message : raw;
|
|
1670
|
+
return errors ? `${message}: ${errors}` : message;
|
|
1671
|
+
} catch {
|
|
1672
|
+
return raw.slice(0, 300);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
/** The organization's property definitions, or `undefined` when they cannot be read (permission, an older client). */
|
|
1676
|
+
async function orgSchema(client, repo) {
|
|
1677
|
+
try {
|
|
1678
|
+
return await client.properties.orgSchema(repo.split("/")[0]);
|
|
1679
|
+
} catch {
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
/**
|
|
1684
|
+
* The values `values` holds that the organization's property definitions do not allow, one sentence each, or
|
|
1685
|
+
* `undefined` when the definitions cannot be read (the token lacks the organization's custom properties permission, or
|
|
1686
|
+
* the organization defines none). `client` should be the organization-scoped one when there is one, since reading the
|
|
1687
|
+
* definitions is an organization permission a repository token often lacks. Read-only.
|
|
1688
|
+
*/
|
|
1689
|
+
async function checkPropertyValues(client, repo, values) {
|
|
1690
|
+
const schema = await orgSchema(client, repo);
|
|
1691
|
+
return schema ? rejectedProperties(values, schema) : void 0;
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Sets the repo's custom properties. When GitHub answers 422 the error says which value it refused and what to do
|
|
1695
|
+
* about it: the values are compared with the organization's property definitions (read-only, with `schemaClient`, the
|
|
1696
|
+
* organization-scoped client when there is one), GitHub's own message is added, and each value GitHub says a property
|
|
1697
|
+
* does not allow gets the fix, which does not need the definitions to be readable. One refused value fails the whole
|
|
1698
|
+
* request, so none of the properties is set.
|
|
1699
|
+
*/
|
|
1700
|
+
async function syncProperties(client, repo, values, schemaClient = client) {
|
|
1701
|
+
try {
|
|
1702
|
+
await client.properties.setProperties(repo, values);
|
|
1703
|
+
} catch (err) {
|
|
1704
|
+
if (!(err instanceof ProviderApiError$1) || err.status !== 422) throw err;
|
|
1705
|
+
const problems = await checkPropertyValues(schemaClient, repo, values) ?? [];
|
|
1706
|
+
const said = githubMessage(err.details);
|
|
1707
|
+
const fixes = propertyFixHints(said);
|
|
1708
|
+
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 });
|
|
1709
|
+
}
|
|
450
1710
|
return `${Object.keys(values).length} properties set`;
|
|
451
1711
|
}
|
|
452
|
-
|
|
453
|
-
|
|
1712
|
+
/** The values the organization's property `name` allows; `undefined` when it cannot be read, is not defined or takes any value. */
|
|
1713
|
+
async function getOrgPropertyValues(client, repo, name) {
|
|
1714
|
+
return ((await orgSchema(client, repo))?.find((p) => p.property_name === name))?.allowed_values ?? void 0;
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* Adds the missing `values` to the organization's property `name` and returns them. GitHub replaces the whole
|
|
1718
|
+
* definition on a write, so the current one is read and sent back with the allowed values extended, in their order,
|
|
1719
|
+
* and nothing removed. A write is made only when something is missing.
|
|
1720
|
+
*/
|
|
1721
|
+
async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = true) {
|
|
1722
|
+
const org = repo.split("/")[0];
|
|
1723
|
+
const current = (await client.properties.orgSchema(org)).find((p) => p.property_name === name);
|
|
1724
|
+
if (!current) throw new Error(`the organization ${org} has no custom property "${name}"; create it first`);
|
|
1725
|
+
if (!current.allowed_values) throw new Error(`the custom property "${name}" takes any value; it has nothing to extend`);
|
|
1726
|
+
const have = new Set(current.allowed_values);
|
|
1727
|
+
const added = [...new Set(values)].filter((v) => !have.has(v));
|
|
1728
|
+
if (added.length === 0) return [];
|
|
1729
|
+
try {
|
|
1730
|
+
await client.properties.setOrgProperty(org, {
|
|
1731
|
+
...current,
|
|
1732
|
+
allowed_values: [...current.allowed_values, ...added]
|
|
1733
|
+
});
|
|
1734
|
+
} catch (err) {
|
|
1735
|
+
if (!(err instanceof ProviderApiError$1) || err.status !== 403 && err.status !== 401) throw err;
|
|
1736
|
+
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)";
|
|
1737
|
+
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 });
|
|
1738
|
+
}
|
|
1739
|
+
return added;
|
|
1740
|
+
}
|
|
1741
|
+
// src/capabilities/read-repo.ts
|
|
1742
|
+
/** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
|
|
1743
|
+
const SETTING_KEYS = [
|
|
1744
|
+
"allow_squash_merge",
|
|
1745
|
+
"allow_merge_commit",
|
|
1746
|
+
"allow_rebase_merge",
|
|
1747
|
+
"allow_auto_merge",
|
|
1748
|
+
"allow_update_branch",
|
|
1749
|
+
"delete_branch_on_merge",
|
|
1750
|
+
"has_issues",
|
|
1751
|
+
"has_discussions",
|
|
1752
|
+
"has_projects",
|
|
1753
|
+
"has_wiki"
|
|
1754
|
+
];
|
|
1755
|
+
/** The repository's description, homepage, default branch, topics and settings, from one read. */
|
|
1756
|
+
async function readRepoInfo(client, repo) {
|
|
1757
|
+
const data = await client.repos.getRepo(repo);
|
|
1758
|
+
const settings = { default_branch: data.default_branch };
|
|
1759
|
+
for (const key of SETTING_KEYS) {
|
|
1760
|
+
const value = data[key];
|
|
1761
|
+
if (value !== void 0) settings[key] = value;
|
|
1762
|
+
}
|
|
1763
|
+
return {
|
|
1764
|
+
description: data.description ?? null,
|
|
1765
|
+
homepage: data.homepage ?? null,
|
|
1766
|
+
defaultBranch: data.default_branch,
|
|
1767
|
+
topics: data.topics ?? [],
|
|
1768
|
+
settings
|
|
1769
|
+
};
|
|
1770
|
+
}
|
|
1771
|
+
/** A ruleset reduced to what `setup` writes: its enforcement, rule types and required status checks. */
|
|
1772
|
+
function toRulesetDetail(data) {
|
|
1773
|
+
const rules = data.rules ?? [];
|
|
1774
|
+
const checks = rules.find((r) => r.type === "required_status_checks")?.parameters?.required_status_checks;
|
|
1775
|
+
return {
|
|
1776
|
+
name: data.name,
|
|
1777
|
+
enforcement: data.enforcement,
|
|
1778
|
+
ruleTypes: rules.map((r) => r.type),
|
|
1779
|
+
requiredChecks: Array.isArray(checks) ? checks.map((c) => String(c.context)) : []
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1782
|
+
/** The value, or `undefined` when GitHub refuses the read (permission, plan, feature absent). Other errors still throw. */
|
|
1783
|
+
async function readable(read) {
|
|
1784
|
+
try {
|
|
1785
|
+
return await read();
|
|
1786
|
+
} catch (err) {
|
|
1787
|
+
if (err instanceof ProviderApiError$1) return void 0;
|
|
1788
|
+
throw err;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
/** Which security features are on. One GitHub refuses to report is left out, not reported as off. */
|
|
1792
|
+
async function readSecurity(client, repo) {
|
|
1793
|
+
const [data, alerts, fixes, reporting, codeScanning] = await Promise.all([
|
|
1794
|
+
readable(() => client.repos.getRepo(repo)),
|
|
1795
|
+
readable(() => client.security.vulnerabilityAlertsEnabled(repo)),
|
|
1796
|
+
readable(() => client.security.automatedSecurityFixesEnabled(repo)),
|
|
1797
|
+
readable(() => client.security.privateVulnerabilityReportingEnabled(repo)),
|
|
1798
|
+
readable(() => client.security.codeScanningDefaultSetupState(repo))
|
|
1799
|
+
]);
|
|
1800
|
+
const analysis = data?.security_and_analysis;
|
|
1801
|
+
const on = (feature) => {
|
|
1802
|
+
const status = analysis?.[feature]?.status;
|
|
1803
|
+
return status === void 0 ? void 0 : status === "enabled";
|
|
1804
|
+
};
|
|
1805
|
+
const found = {
|
|
1806
|
+
vulnerabilityAlerts: alerts,
|
|
1807
|
+
automatedSecurityFixes: fixes,
|
|
1808
|
+
secretScanning: on("secret_scanning"),
|
|
1809
|
+
secretScanningPushProtection: on("secret_scanning_push_protection"),
|
|
1810
|
+
privateVulnerabilityReporting: reporting,
|
|
1811
|
+
codeScanningDefaultSetup: codeScanning === void 0 ? void 0 : codeScanning === "configured"
|
|
1812
|
+
};
|
|
1813
|
+
return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== void 0));
|
|
1814
|
+
}
|
|
1815
|
+
// src/capabilities/teams.ts
|
|
1816
|
+
/** Turns a team entry into slug and permission form; a bare slug gets `push`. */
|
|
454
1817
|
function normalizeTeamEntry(entry) {
|
|
455
1818
|
if (typeof entry === "string") return {
|
|
456
1819
|
slug: entry,
|
|
@@ -458,6 +1821,7 @@ function normalizeTeamEntry(entry) {
|
|
|
458
1821
|
};
|
|
459
1822
|
return entry;
|
|
460
1823
|
}
|
|
1824
|
+
/** Grants each team access to the repo and reports the outcome; throws when every team fails. */
|
|
461
1825
|
async function syncTeams(client, repo, teams) {
|
|
462
1826
|
const [org = "", name = ""] = repo.split("/", 2);
|
|
463
1827
|
const normalized = teams.map(normalizeTeamEntry);
|
|
@@ -470,17 +1834,132 @@ async function syncTeams(client, repo, teams) {
|
|
|
470
1834
|
}
|
|
471
1835
|
return `${succeeded} team${succeeded === 1 ? "" : "s"} synced`;
|
|
472
1836
|
}
|
|
473
|
-
|
|
474
|
-
//#region src/capabilities/topics.ts
|
|
1837
|
+
// src/capabilities/topics.ts
|
|
475
1838
|
async function syncTopics(client, repo, topics) {
|
|
476
1839
|
await client.topics.setTopics(repo, topics);
|
|
477
1840
|
return `${topics.length} topics set`;
|
|
478
1841
|
}
|
|
479
|
-
|
|
480
|
-
|
|
1842
|
+
// src/capabilities/variables.ts
|
|
1843
|
+
/** GitHub's rule for a variable name: letters, digits and underscores, not starting with a digit or `GITHUB_`. */
|
|
1844
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
1845
|
+
/** Longest name GitHub accepts. */
|
|
1846
|
+
const MAX_NAME = 256;
|
|
1847
|
+
function assertNames(names) {
|
|
1848
|
+
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_`);
|
|
1849
|
+
}
|
|
1850
|
+
/** GitHub treats variable names as case-insensitive, so every comparison goes through this. */
|
|
1851
|
+
const key = (name) => name.toUpperCase();
|
|
1852
|
+
/**
|
|
1853
|
+
* Bring one scope's variables in line with the declaration: create what is missing, update what differs, leave what
|
|
1854
|
+
* already matches. Variables that exist but are not declared are left alone, or deleted with `prune`, except an
|
|
1855
|
+
* organization variable limited to selected repositories, which this client cannot manage and so is never deleted.
|
|
1856
|
+
* Returns a one-line summary, naming the ones left so drift is visible. In a dry run it only describes the changes.
|
|
1857
|
+
*/
|
|
1858
|
+
async function reconcile(client, repo, scope, wanted, opts) {
|
|
1859
|
+
assertNames(wanted.map((w) => w.name));
|
|
1860
|
+
const existing = new Map((await client.variables.listVariables(repo, scope)).map((v) => [key(v.name), v]));
|
|
1861
|
+
const counts = {
|
|
1862
|
+
created: 0,
|
|
1863
|
+
updated: 0,
|
|
1864
|
+
unchanged: 0,
|
|
1865
|
+
deleted: 0
|
|
1866
|
+
};
|
|
1867
|
+
for (const want of wanted) {
|
|
1868
|
+
const have = existing.get(key(want.name));
|
|
1869
|
+
const body = {
|
|
1870
|
+
name: want.name,
|
|
1871
|
+
value: want.value
|
|
1872
|
+
};
|
|
1873
|
+
if (want.visibility) body["visibility"] = want.visibility;
|
|
1874
|
+
if (!have) {
|
|
1875
|
+
if (opts.dryRun) {
|
|
1876
|
+
counts.created++;
|
|
1877
|
+
continue;
|
|
1878
|
+
}
|
|
1879
|
+
try {
|
|
1880
|
+
await client.variables.createVariable(repo, scope, body);
|
|
1881
|
+
counts.created++;
|
|
1882
|
+
continue;
|
|
1883
|
+
} catch (err) {
|
|
1884
|
+
if (!(err instanceof ProviderApiError && (err.status === 409 || err.status === 422))) throw err;
|
|
1885
|
+
}
|
|
1886
|
+
} else if (have.value === want.value && (!want.visibility || have.visibility === want.visibility)) {
|
|
1887
|
+
counts.unchanged++;
|
|
1888
|
+
continue;
|
|
1889
|
+
}
|
|
1890
|
+
if (!opts.dryRun) await client.variables.updateVariable(repo, scope, have?.name ?? want.name, body);
|
|
1891
|
+
counts.updated++;
|
|
1892
|
+
}
|
|
1893
|
+
const declared = new Set(wanted.map((w) => key(w.name)));
|
|
1894
|
+
const undeclared = [...existing.entries()].filter(([k]) => !declared.has(k)).map(([, v]) => v);
|
|
1895
|
+
const unmanaged = undeclared.filter((v) => v.visibility === "selected");
|
|
1896
|
+
if (opts.prune) for (const v of undeclared.filter((u) => u.visibility !== "selected")) {
|
|
1897
|
+
if (!opts.dryRun) await client.variables.deleteVariable(repo, scope, v.name);
|
|
1898
|
+
counts.deleted++;
|
|
1899
|
+
}
|
|
1900
|
+
const parts = opts.dryRun ? [
|
|
1901
|
+
`would create ${counts.created}`,
|
|
1902
|
+
`would update ${counts.updated}`,
|
|
1903
|
+
`${counts.unchanged} unchanged`
|
|
1904
|
+
] : [
|
|
1905
|
+
`${counts.created} created`,
|
|
1906
|
+
`${counts.updated} updated`,
|
|
1907
|
+
`${counts.unchanged} unchanged`
|
|
1908
|
+
];
|
|
1909
|
+
if (counts.deleted > 0) parts.push(`${counts.deleted} ${opts.dryRun ? "would be deleted" : "deleted"}`);
|
|
1910
|
+
const left = opts.prune ? unmanaged : undeclared;
|
|
1911
|
+
if (left.length > 0) {
|
|
1912
|
+
const why = opts.prune ? "limited to selected repositories, not managed" : "not declared, left alone";
|
|
1913
|
+
parts.push(`${left.length} ${why}: ${left.map((v) => v.name).join(", ")}`);
|
|
1914
|
+
}
|
|
1915
|
+
return parts.join(", ");
|
|
1916
|
+
}
|
|
1917
|
+
/** Reconcile a repository's Actions variables. */
|
|
1918
|
+
function syncVariables(client, repo, variables, opts = {}) {
|
|
1919
|
+
return reconcile(client, repo, { kind: "repo" }, Object.entries(variables).map(([name, value]) => ({
|
|
1920
|
+
name,
|
|
1921
|
+
value
|
|
1922
|
+
})), {
|
|
1923
|
+
prune: opts.prune === true,
|
|
1924
|
+
dryRun: opts.dryRun === true
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
/** Reconcile an organization's Actions variables. `repo` is only the coordinate the client is bound to. */
|
|
1928
|
+
function syncOrgVariables(client, repo, org, variables, opts = {}) {
|
|
1929
|
+
const wanted = Object.entries(variables).map(([name, v]) => ({
|
|
1930
|
+
name,
|
|
1931
|
+
value: v.value,
|
|
1932
|
+
visibility: v.visibility
|
|
1933
|
+
}));
|
|
1934
|
+
return reconcile(client, repo, {
|
|
1935
|
+
kind: "organization",
|
|
1936
|
+
org
|
|
1937
|
+
}, wanted, {
|
|
1938
|
+
prune: opts.prune === true,
|
|
1939
|
+
dryRun: opts.dryRun === true
|
|
1940
|
+
});
|
|
1941
|
+
}
|
|
1942
|
+
// src/capabilities/source.ts
|
|
1943
|
+
function toPullRequest(raw) {
|
|
1944
|
+
return {
|
|
1945
|
+
number: raw.number,
|
|
1946
|
+
title: raw.title,
|
|
1947
|
+
state: raw.state,
|
|
1948
|
+
merged: raw.merged_at !== null,
|
|
1949
|
+
branch: raw.head.ref,
|
|
1950
|
+
headSha: raw.head.sha,
|
|
1951
|
+
url: raw.html_url
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
|
|
1956
|
+
* features and local workflow files.
|
|
1957
|
+
*/
|
|
481
1958
|
var GitHubSource = class {
|
|
482
1959
|
client;
|
|
1960
|
+
/** Capability key, always `"source"`. */
|
|
483
1961
|
key = "source";
|
|
1962
|
+
/** Provider name, always `"github"`. */
|
|
484
1963
|
providerName = "github";
|
|
485
1964
|
owner;
|
|
486
1965
|
name;
|
|
@@ -488,6 +1967,7 @@ var GitHubSource = class {
|
|
|
488
1967
|
repoRoot;
|
|
489
1968
|
workflowDir;
|
|
490
1969
|
orgClient;
|
|
1970
|
+
userSyncClient;
|
|
491
1971
|
baseUrl;
|
|
492
1972
|
fetchImpl;
|
|
493
1973
|
constructor(client, opts) {
|
|
@@ -496,15 +1976,20 @@ var GitHubSource = class {
|
|
|
496
1976
|
this.owner = owner;
|
|
497
1977
|
this.name = name;
|
|
498
1978
|
this.repo = opts.repo;
|
|
499
|
-
this.repoRoot = opts.repoRoot
|
|
500
|
-
|
|
1979
|
+
this.repoRoot = findRootSync(opts.repoRoot, ".git", {
|
|
1980
|
+
fallback: "start",
|
|
1981
|
+
realpath: true
|
|
1982
|
+
});
|
|
1983
|
+
this.workflowDir = join(this.repoRoot, ".github", "workflows");
|
|
501
1984
|
this.orgClient = opts.orgClient;
|
|
1985
|
+
this.userSyncClient = opts.userSyncClient;
|
|
502
1986
|
this.baseUrl = opts.baseUrl;
|
|
503
1987
|
this.fetchImpl = opts.fetch;
|
|
504
1988
|
}
|
|
505
1989
|
async whoami() {
|
|
506
1990
|
return { login: (await this.client.user.getCurrentUser()).login };
|
|
507
1991
|
}
|
|
1992
|
+
/** Returns the repo's owner, name and default branch. */
|
|
508
1993
|
async getRepo() {
|
|
509
1994
|
const data = await this.client.repos.getRepo(this.repo);
|
|
510
1995
|
return {
|
|
@@ -513,27 +1998,34 @@ var GitHubSource = class {
|
|
|
513
1998
|
defaultBranch: data.default_branch
|
|
514
1999
|
};
|
|
515
2000
|
}
|
|
2001
|
+
/** Lists the repo's rulesets. */
|
|
516
2002
|
async listRulesets() {
|
|
517
2003
|
return this.client.rulesets.listRulesets(this.repo);
|
|
518
2004
|
}
|
|
2005
|
+
/** Creates a ruleset from the given payload. */
|
|
519
2006
|
async createRuleset(payload) {
|
|
520
2007
|
return this.client.rulesets.createRuleset(this.repo, payload);
|
|
521
2008
|
}
|
|
2009
|
+
/** Updates the ruleset with the given id from the payload. */
|
|
522
2010
|
async updateRuleset(id, payload) {
|
|
523
2011
|
return this.client.rulesets.updateRuleset(this.repo, id, payload);
|
|
524
2012
|
}
|
|
2013
|
+
/** Updates the repo's settings. */
|
|
525
2014
|
async updateRepoSettings(settings) {
|
|
526
2015
|
await this.client.repos.updateRepo(this.repo, settings);
|
|
527
2016
|
}
|
|
528
2017
|
async protectBranch(branch, payload) {
|
|
529
2018
|
await this.client.branches.protectBranch(this.repo, branch, payload);
|
|
530
2019
|
}
|
|
2020
|
+
/** Enables Dependabot vulnerability alerts. */
|
|
531
2021
|
async enableVulnerabilityAlerts() {
|
|
532
2022
|
await this.client.security.enableVulnerabilityAlerts(this.repo);
|
|
533
2023
|
}
|
|
2024
|
+
/** Enables Dependabot automated security fixes. */
|
|
534
2025
|
async enableAutomatedSecurityFixes() {
|
|
535
2026
|
await this.client.security.enableAutomatedSecurityFixes(this.repo);
|
|
536
2027
|
}
|
|
2028
|
+
/** Enables secret scanning. */
|
|
537
2029
|
async enableSecretScanning() {
|
|
538
2030
|
await this.client.security.enableSecretScanning(this.repo);
|
|
539
2031
|
}
|
|
@@ -546,9 +2038,11 @@ var GitHubSource = class {
|
|
|
546
2038
|
async enableDependencyGraph() {
|
|
547
2039
|
await this.client.security.enableDependencyGraph(this.repo);
|
|
548
2040
|
}
|
|
2041
|
+
/** Enables private vulnerability reporting. */
|
|
549
2042
|
async enablePrivateVulnerabilityReporting() {
|
|
550
2043
|
await this.client.security.enablePrivateVulnerabilityReporting(this.repo);
|
|
551
2044
|
}
|
|
2045
|
+
/** Lists the `.yml` and `.yaml` files in `.github/workflows`, sorted by name; empty when the folder is missing. */
|
|
552
2046
|
async listWorkflowFiles() {
|
|
553
2047
|
try {
|
|
554
2048
|
return (await readdir(this.workflowDir)).filter((e) => e.endsWith(".yml") || e.endsWith(".yaml")).sort();
|
|
@@ -557,6 +2051,7 @@ var GitHubSource = class {
|
|
|
557
2051
|
throw err;
|
|
558
2052
|
}
|
|
559
2053
|
}
|
|
2054
|
+
/** Reads a workflow file's text, or `null` when it does not exist. */
|
|
560
2055
|
async readWorkflowFile(name) {
|
|
561
2056
|
try {
|
|
562
2057
|
return await readFile(join(this.workflowDir, name), "utf8");
|
|
@@ -565,10 +2060,12 @@ var GitHubSource = class {
|
|
|
565
2060
|
throw err;
|
|
566
2061
|
}
|
|
567
2062
|
}
|
|
2063
|
+
/** Writes a workflow file, creating `.github/workflows` first when needed. */
|
|
568
2064
|
async writeWorkflowFile(name, contents) {
|
|
569
2065
|
await ensureDir(this.workflowDir);
|
|
570
2066
|
await writeFile(join(this.workflowDir, name), contents, "utf8");
|
|
571
2067
|
}
|
|
2068
|
+
/** Removes a workflow file; a file that is already gone is not an error. */
|
|
572
2069
|
async removeWorkflowFile(name) {
|
|
573
2070
|
try {
|
|
574
2071
|
await rm(join(this.workflowDir, name));
|
|
@@ -586,14 +2083,83 @@ var GitHubSource = class {
|
|
|
586
2083
|
return syncLabels(this.client, this.repo, canonical, stale);
|
|
587
2084
|
}
|
|
588
2085
|
async syncProperties(values) {
|
|
589
|
-
return syncProperties(this.client, this.repo, values);
|
|
2086
|
+
return syncProperties(this.client, this.repo, values, this.orgClient ?? this.client);
|
|
2087
|
+
}
|
|
2088
|
+
async getOrgPropertyValues(name) {
|
|
2089
|
+
return getOrgPropertyValues(this.orgClient ?? this.client, this.repo, name);
|
|
2090
|
+
}
|
|
2091
|
+
async addOrgPropertyValues(name, values) {
|
|
2092
|
+
return addOrgPropertyValues(this.orgClient ?? this.client, this.repo, name, values, this.orgClient !== void 0);
|
|
2093
|
+
}
|
|
2094
|
+
async checkPropertyValues(values) {
|
|
2095
|
+
return checkPropertyValues(this.orgClient ?? this.client, this.repo, values);
|
|
590
2096
|
}
|
|
591
2097
|
async syncTeams(teams) {
|
|
592
2098
|
return syncTeams(this.orgClient ?? this.client, this.repo, teams);
|
|
593
2099
|
}
|
|
2100
|
+
async teamMembers(teamSlug, org = this.owner) {
|
|
2101
|
+
return (await (this.orgClient ?? this.client).teams.members(org, teamSlug)).map((m) => ({
|
|
2102
|
+
id: String(m.id),
|
|
2103
|
+
login: m.login
|
|
2104
|
+
}));
|
|
2105
|
+
}
|
|
2106
|
+
async readFile(path, repo = this.repo) {
|
|
2107
|
+
return readRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, repo, path);
|
|
2108
|
+
}
|
|
2109
|
+
async writeFile(path, content, opts) {
|
|
2110
|
+
return writeRepoFile(this.userSyncClient ?? this.orgClient ?? this.client, opts.repo ?? this.repo, path, content, opts);
|
|
2111
|
+
}
|
|
594
2112
|
async syncTopics(topics) {
|
|
595
2113
|
return syncTopics(this.client, this.repo, topics);
|
|
596
2114
|
}
|
|
2115
|
+
async syncVariables(variables, opts) {
|
|
2116
|
+
return syncVariables(this.client, this.repo, variables, opts);
|
|
2117
|
+
}
|
|
2118
|
+
async syncOrgVariables(org, variables, opts) {
|
|
2119
|
+
if (!this.orgClient) throw new Error("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
|
|
2120
|
+
return syncOrgVariables(this.orgClient, this.repo, org, variables, opts);
|
|
2121
|
+
}
|
|
2122
|
+
async listVariables() {
|
|
2123
|
+
const found = await this.client.variables.listVariables(this.repo, { kind: "repo" });
|
|
2124
|
+
return Object.fromEntries(found.map((v) => [v.name, v.value]));
|
|
2125
|
+
}
|
|
2126
|
+
async listOrgVariables(org) {
|
|
2127
|
+
if (!this.orgClient) throw new MissingTokenError("organization variables need the org token: set HOLOCRON_ORG_TOKEN or run `holocron new token github.org <token>`");
|
|
2128
|
+
const found = await this.orgClient.variables.listVariables(this.repo, {
|
|
2129
|
+
kind: "organization",
|
|
2130
|
+
org
|
|
2131
|
+
});
|
|
2132
|
+
return Object.fromEntries(found.map((v) => [v.name, {
|
|
2133
|
+
value: v.value,
|
|
2134
|
+
visibility: v.visibility ?? "all"
|
|
2135
|
+
}]));
|
|
2136
|
+
}
|
|
2137
|
+
async getRepoInfo() {
|
|
2138
|
+
return readRepoInfo(this.client, this.repo);
|
|
2139
|
+
}
|
|
2140
|
+
async getProperties() {
|
|
2141
|
+
const found = await this.client.properties.getValues(this.repo);
|
|
2142
|
+
return Object.fromEntries(found.flatMap((p) => p.value === null ? [] : [[p.property_name, p.value]]));
|
|
2143
|
+
}
|
|
2144
|
+
async listLabels() {
|
|
2145
|
+
return (await this.client.labels.listLabels(this.repo)).map((l) => ({
|
|
2146
|
+
name: l.name,
|
|
2147
|
+
color: l.color,
|
|
2148
|
+
description: l.description ?? ""
|
|
2149
|
+
}));
|
|
2150
|
+
}
|
|
2151
|
+
async listTeamAccess() {
|
|
2152
|
+
return (await (this.orgClient ?? this.client).teams.listForRepo(this.repo)).map((t) => ({
|
|
2153
|
+
slug: t.slug,
|
|
2154
|
+
permission: t.permission
|
|
2155
|
+
}));
|
|
2156
|
+
}
|
|
2157
|
+
async getRulesetDetail(id) {
|
|
2158
|
+
return toRulesetDetail(await this.client.rulesets.getRuleset(this.repo, id));
|
|
2159
|
+
}
|
|
2160
|
+
async getSecurity() {
|
|
2161
|
+
return readSecurity(this.client, this.repo);
|
|
2162
|
+
}
|
|
597
2163
|
async syncDescription(description) {
|
|
598
2164
|
await this.client.repos.updateRepo(this.repo, { description });
|
|
599
2165
|
return "description updated";
|
|
@@ -603,15 +2169,27 @@ var GitHubSource = class {
|
|
|
603
2169
|
return "homepage updated";
|
|
604
2170
|
}
|
|
605
2171
|
async getPullRequest(number, repo) {
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
2172
|
+
return toPullRequest(await this.client.pulls.getPullRequest(repo ?? this.repo, number));
|
|
2173
|
+
}
|
|
2174
|
+
async listPullRequests(state, repo) {
|
|
2175
|
+
return (await this.client.pulls.listPullRequests(repo ?? this.repo, state)).map(toPullRequest);
|
|
2176
|
+
}
|
|
2177
|
+
async listBranches(repo) {
|
|
2178
|
+
return (await this.client.branches.listBranches(repo ?? this.repo)).map((b) => ({
|
|
2179
|
+
name: b.name,
|
|
2180
|
+
sha: b.commit.sha
|
|
2181
|
+
}));
|
|
2182
|
+
}
|
|
2183
|
+
async deleteBranch(name, repo) {
|
|
2184
|
+
try {
|
|
2185
|
+
await this.client.branches.removeBranch(repo ?? this.repo, name);
|
|
2186
|
+
} catch (err) {
|
|
2187
|
+
if (err instanceof ProviderApiError && err.status === 422 && String(err.details).includes("does not exist")) return;
|
|
2188
|
+
throw err;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
async listPullRequestCommits(number, repo) {
|
|
2192
|
+
return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
|
|
615
2193
|
}
|
|
616
2194
|
async configurePages(config, token) {
|
|
617
2195
|
const pagesClient = createGitHubClient$1({
|
|
@@ -650,18 +2228,386 @@ async function ensureDir(path) {
|
|
|
650
2228
|
throw err;
|
|
651
2229
|
}
|
|
652
2230
|
}
|
|
653
|
-
|
|
654
|
-
|
|
2231
|
+
// src/probes/token/expectations.ts
|
|
2232
|
+
/** The same rules in every layer that runs the workflow: a laptop (`local` inherits `dev`) and CI. */
|
|
2233
|
+
function everywhere(rules) {
|
|
2234
|
+
return { permissions: {
|
|
2235
|
+
local: rules,
|
|
2236
|
+
dev: rules,
|
|
2237
|
+
ci: rules
|
|
2238
|
+
} };
|
|
2239
|
+
}
|
|
2240
|
+
/**
|
|
2241
|
+
* What each GitHub token is meant to carry, by its `envName`, the same as the GitHub tokens table in
|
|
2242
|
+
* `docs/src/content/docs/tokens.mdx`. This is the plugin's `tokens` declaration, read through `tokenExpectations()`;
|
|
2243
|
+
* change it and that table together.
|
|
2244
|
+
*
|
|
2245
|
+
* Every token CI uses (the `sync-repo`, `sync-secrets`, `reconcile-projects` and `check-tokens` workflows read all of
|
|
2246
|
+
* them) is declared with the same permissions in `local`, `dev` and `ci`, so the probe checks that a `ci` token is no
|
|
2247
|
+
* broader than its `dev` one rather than assuming a split the workflows do not allow. The release token is held by CI
|
|
2248
|
+
* only, so it has no `local` or `dev` entry. A narrow token must not reach administration or secrets; the admin token
|
|
2249
|
+
* must not reach organization secrets (that is `HOLOCRON_SECRETS_TOKEN`'s alone).
|
|
2250
|
+
*/
|
|
2251
|
+
const EXPECTED = {
|
|
2252
|
+
HOLOCRON_READ_TOKEN: everywhere({
|
|
2253
|
+
contents: "required",
|
|
2254
|
+
actions: "required",
|
|
2255
|
+
administration: "absent",
|
|
2256
|
+
secrets: "absent",
|
|
2257
|
+
environments: "absent"
|
|
2258
|
+
}),
|
|
2259
|
+
HOLOCRON_ISSUES_TOKEN: everywhere({
|
|
2260
|
+
issues: "required",
|
|
2261
|
+
administration: "absent",
|
|
2262
|
+
secrets: "absent",
|
|
2263
|
+
environments: "absent"
|
|
2264
|
+
}),
|
|
2265
|
+
HOLOCRON_SYNC_TOKEN: everywhere({
|
|
2266
|
+
actions: "required",
|
|
2267
|
+
contents: "required",
|
|
2268
|
+
"pull-requests": "required",
|
|
2269
|
+
administration: "absent",
|
|
2270
|
+
secrets: "absent"
|
|
2271
|
+
}),
|
|
2272
|
+
HOLOCRON_RELEASE_TOKEN: { permissions: { ci: {
|
|
2273
|
+
contents: "required",
|
|
2274
|
+
issues: "required",
|
|
2275
|
+
"pull-requests": "required",
|
|
2276
|
+
administration: "absent",
|
|
2277
|
+
secrets: "absent"
|
|
2278
|
+
} } },
|
|
2279
|
+
HOLOCRON_ADMIN_TOKEN: everywhere({
|
|
2280
|
+
administration: "required",
|
|
2281
|
+
secrets: "required",
|
|
2282
|
+
environments: "required",
|
|
2283
|
+
issues: "required",
|
|
2284
|
+
"custom-properties": "required",
|
|
2285
|
+
"actions-variables": "required",
|
|
2286
|
+
"org-secrets": "absent"
|
|
2287
|
+
}),
|
|
2288
|
+
HOLOCRON_SECRETS_TOKEN: everywhere({
|
|
2289
|
+
"org-secrets": "required",
|
|
2290
|
+
administration: "absent"
|
|
2291
|
+
}),
|
|
2292
|
+
HOLOCRON_DEPLOY_TOKEN: everywhere({
|
|
2293
|
+
pages: "required",
|
|
2294
|
+
administration: "required",
|
|
2295
|
+
secrets: "absent",
|
|
2296
|
+
"org-secrets": "absent"
|
|
2297
|
+
}),
|
|
2298
|
+
HOLOCRON_USER_SYNC_TOKEN: everywhere({
|
|
2299
|
+
"user-sync-contents": "required",
|
|
2300
|
+
administration: "absent",
|
|
2301
|
+
secrets: "absent"
|
|
2302
|
+
}),
|
|
2303
|
+
HOLOCRON_ORG_TOKEN: everywhere({
|
|
2304
|
+
administration: "required",
|
|
2305
|
+
"org-members": "required",
|
|
2306
|
+
"org-variables": "required",
|
|
2307
|
+
"org-secrets": "absent"
|
|
2308
|
+
})
|
|
2309
|
+
};
|
|
2310
|
+
// src/tokens.ts
|
|
2311
|
+
/** Adds what a layer's token must and must not be able to do (`EXPECTED`, by `envName`) to a token. */
|
|
2312
|
+
function declared(token) {
|
|
2313
|
+
return {
|
|
2314
|
+
...token,
|
|
2315
|
+
expect: EXPECTED[token.envName]
|
|
2316
|
+
};
|
|
2317
|
+
}
|
|
2318
|
+
/**
|
|
2319
|
+
* Every token this plugin takes, for `holocron doctor tokens`, with what each layer's token must and must not be able
|
|
2320
|
+
* to do. The release token is `optional`: only CI's release workflow reads it (from the org secret), so a development
|
|
2321
|
+
* environment has no reason to hold it.
|
|
2322
|
+
*/
|
|
2323
|
+
const tokens = [
|
|
2324
|
+
declared(resolveReadToken.token),
|
|
2325
|
+
declared(resolveIssuesToken.token),
|
|
2326
|
+
declared(resolveSyncToken.token),
|
|
2327
|
+
declared({
|
|
2328
|
+
...resolveReleaseToken.token,
|
|
2329
|
+
optional: true
|
|
2330
|
+
}),
|
|
2331
|
+
declared(resolveAdminToken.token),
|
|
2332
|
+
declared(resolveSecretsToken.token),
|
|
2333
|
+
declared(resolveDeployToken.token),
|
|
2334
|
+
declared(resolveUserSyncToken.token),
|
|
2335
|
+
declared(resolveOrgToken.token)
|
|
2336
|
+
];
|
|
2337
|
+
// src/probes/token/parse-token-args.ts
|
|
2338
|
+
/** Reads the words after the probe name: `--layer <word>` and `--token-name <VAR>`, in either spelling. */
|
|
2339
|
+
function parseTokenArgs(args) {
|
|
2340
|
+
let layer;
|
|
2341
|
+
let tokenName;
|
|
2342
|
+
for (let i = 0; i < args.length; i++) {
|
|
2343
|
+
const arg = args[i];
|
|
2344
|
+
if (arg === "--layer") layer = args[++i];
|
|
2345
|
+
else if (arg.startsWith("--layer=")) layer = arg.slice(8);
|
|
2346
|
+
else if (arg === "--token-name") tokenName = args[++i];
|
|
2347
|
+
else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
|
|
2348
|
+
}
|
|
2349
|
+
return {
|
|
2350
|
+
...layer ? { layer } : {},
|
|
2351
|
+
...tokenName ? { tokenName } : {}
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
// src/probes/token/permissions.ts
|
|
2355
|
+
/**
|
|
2356
|
+
* Every permission the GitHub plugin's tokens are declared against, by the name the declaration uses, with one read
|
|
2357
|
+
* 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
|
|
2358
|
+
* fine-grained token's permissions, so the write half of `read/write` is taken from the permission table in
|
|
2359
|
+
* `docs/src/content/docs/tokens.mdx`. On a public repository the `contents`, `actions`, `issues`, `pull-requests` and `environments`
|
|
2360
|
+
* reads succeed for any token, so only the other permissions can prove a permission absent. Names with more than one
|
|
2361
|
+
* word are hyphenated, not underscored: `holocron probe docs tokens` strips `_` (Markdown emphasis) from a table cell
|
|
2362
|
+
* before it compares the id with the declaration.
|
|
2363
|
+
*/
|
|
2364
|
+
const PERMISSIONS = {
|
|
2365
|
+
contents: {
|
|
2366
|
+
label: "Contents",
|
|
2367
|
+
path: "/repos/{r}/contents",
|
|
2368
|
+
publicRead: true
|
|
2369
|
+
},
|
|
2370
|
+
actions: {
|
|
2371
|
+
label: "Actions",
|
|
2372
|
+
path: "/repos/{r}/actions/runs?per_page=1",
|
|
2373
|
+
publicRead: true
|
|
2374
|
+
},
|
|
2375
|
+
issues: {
|
|
2376
|
+
label: "Issues",
|
|
2377
|
+
path: "/repos/{r}/issues?per_page=1",
|
|
2378
|
+
publicRead: true
|
|
2379
|
+
},
|
|
2380
|
+
"pull-requests": {
|
|
2381
|
+
label: "Pull requests",
|
|
2382
|
+
path: "/repos/{r}/pulls?per_page=1",
|
|
2383
|
+
publicRead: true
|
|
2384
|
+
},
|
|
2385
|
+
administration: {
|
|
2386
|
+
label: "Administration",
|
|
2387
|
+
path: "/repos/{r}/actions/permissions"
|
|
2388
|
+
},
|
|
2389
|
+
secrets: {
|
|
2390
|
+
label: "Secrets",
|
|
2391
|
+
path: "/repos/{r}/actions/secrets?per_page=1"
|
|
2392
|
+
},
|
|
2393
|
+
environments: {
|
|
2394
|
+
label: "Environments",
|
|
2395
|
+
path: "/repos/{r}/environments?per_page=1",
|
|
2396
|
+
publicRead: true
|
|
2397
|
+
},
|
|
2398
|
+
"actions-variables": {
|
|
2399
|
+
label: "Variables",
|
|
2400
|
+
path: "/repos/{r}/actions/variables?per_page=1"
|
|
2401
|
+
},
|
|
2402
|
+
"custom-properties": {
|
|
2403
|
+
label: "Custom properties",
|
|
2404
|
+
path: "/repos/{r}/properties/values"
|
|
2405
|
+
},
|
|
2406
|
+
pages: {
|
|
2407
|
+
label: "Pages",
|
|
2408
|
+
path: "/repos/{r}/pages"
|
|
2409
|
+
},
|
|
2410
|
+
"org-members": {
|
|
2411
|
+
label: "Organization: Members",
|
|
2412
|
+
path: "/orgs/{o}/members?per_page=1"
|
|
2413
|
+
},
|
|
2414
|
+
"org-variables": {
|
|
2415
|
+
label: "Organization: Variables",
|
|
2416
|
+
path: "/orgs/{o}/actions/variables?per_page=1"
|
|
2417
|
+
},
|
|
2418
|
+
"org-secrets": {
|
|
2419
|
+
label: "Organization: Secrets",
|
|
2420
|
+
path: "/orgs/{o}/actions/secrets?per_page=1"
|
|
2421
|
+
},
|
|
2422
|
+
"user-sync-contents": {
|
|
2423
|
+
label: "Contents (.github-private)",
|
|
2424
|
+
path: "/repos/{o}/.github-private/contents"
|
|
2425
|
+
}
|
|
2426
|
+
};
|
|
2427
|
+
// src/probes/token/token.ts
|
|
2428
|
+
/** The token checked when none is named: the one the plugin reads with by default. */
|
|
2429
|
+
const DEFAULT_TOKEN = "HOLOCRON_READ_TOKEN";
|
|
2430
|
+
/** Does one GET with the token; the response headers are returned for the caller that wants them. */
|
|
2431
|
+
async function get(ctx, token, path) {
|
|
2432
|
+
return ctx.fetch(`${ctx.baseUrl}${path}`, { headers: {
|
|
2433
|
+
authorization: `Bearer ${token}`,
|
|
2434
|
+
accept: "application/vnd.github+json",
|
|
2435
|
+
"x-github-api-version": "2022-11-28",
|
|
2436
|
+
"user-agent": "holocron-probe"
|
|
2437
|
+
} });
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* One read for one permission. GitHub answers a token without the permission with a 403, or a 404 for something it will
|
|
2441
|
+
* not admit exists, so both are `none`; a 2xx is `has`. Any other status, or a request that did not go through, is an
|
|
2442
|
+
* `error`, which is a failure whatever the layer expects.
|
|
2443
|
+
*/
|
|
2444
|
+
async function reach(ctx, token, permission) {
|
|
2445
|
+
const [owner = ""] = ctx.repo.split("/");
|
|
2446
|
+
const path = PERMISSIONS[permission].path.replaceAll("{r}", ctx.repo).replaceAll("{o}", owner);
|
|
2447
|
+
try {
|
|
2448
|
+
const res = await get(ctx, token, path);
|
|
2449
|
+
if (res.ok) return {
|
|
2450
|
+
kind: "has",
|
|
2451
|
+
detail: `read ${path.split("?")[0]}`
|
|
2452
|
+
};
|
|
2453
|
+
if (res.status === 403 || res.status === 404) return {
|
|
2454
|
+
kind: "none",
|
|
2455
|
+
detail: `no access (${res.status})`
|
|
2456
|
+
};
|
|
2457
|
+
return {
|
|
2458
|
+
kind: "error",
|
|
2459
|
+
detail: `${res.status} ${res.statusText}`.trim()
|
|
2460
|
+
};
|
|
2461
|
+
} catch (err) {
|
|
2462
|
+
return {
|
|
2463
|
+
kind: "error",
|
|
2464
|
+
detail: errorMessage(err)
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
|
|
2470
|
+
* judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
|
|
2471
|
+
* permission that is rightly absent is a bare `ok`.
|
|
2472
|
+
*/
|
|
2473
|
+
function rowFor({ label, permission, outcome }, rule) {
|
|
2474
|
+
if (outcome.kind === "error") return {
|
|
2475
|
+
status: "fail",
|
|
2476
|
+
label,
|
|
2477
|
+
detail: outcome.detail
|
|
2478
|
+
};
|
|
2479
|
+
const has = outcome.kind === "has";
|
|
2480
|
+
if (rule === "required") return {
|
|
2481
|
+
status: has ? "ok" : "fail",
|
|
2482
|
+
label,
|
|
2483
|
+
detail: outcome.detail
|
|
2484
|
+
};
|
|
2485
|
+
if (rule === "absent" && has && PERMISSIONS[permission].publicRead) return {
|
|
2486
|
+
status: "info",
|
|
2487
|
+
label,
|
|
2488
|
+
detail: `${outcome.detail}, which any token can on a public repository: not proof either way`
|
|
2489
|
+
};
|
|
2490
|
+
if (rule === "absent") return has ? {
|
|
2491
|
+
status: "fail",
|
|
2492
|
+
label,
|
|
2493
|
+
detail: outcome.detail
|
|
2494
|
+
} : {
|
|
2495
|
+
status: "ok",
|
|
2496
|
+
label
|
|
2497
|
+
};
|
|
2498
|
+
return {
|
|
2499
|
+
status: has ? "ok" : "info",
|
|
2500
|
+
label,
|
|
2501
|
+
detail: outcome.detail
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
655
2504
|
/**
|
|
656
|
-
* `
|
|
657
|
-
*
|
|
658
|
-
*
|
|
2505
|
+
* The `token` probe: `holocron probe github token` tries each permission Holocron uses with one of the plugin's nine
|
|
2506
|
+
* tokens and reports which ones the token reaches. It only reads (one GET per permission), so it changes nothing, and a
|
|
2507
|
+
* read proves the token can see an area, not that it can write there.
|
|
2508
|
+
*
|
|
2509
|
+
* GitHub lists scopes only for a classic token (the `X-OAuth-Scopes` header on any response), so a classic token's scopes
|
|
2510
|
+
* are shown. A fine-grained token has no list, so the permissions are found by trying them; the first row says which kind
|
|
2511
|
+
* was read. With `--environment <layer>` the CLI runs the probe once for each token the Environment holds and hands it
|
|
2512
|
+
* `--token-name <envName>` (and the token itself as `cliToken`); by hand, `--token-name` picks which token the plugin
|
|
2513
|
+
* resolves (default `HOLOCRON_READ_TOKEN`).
|
|
659
2514
|
*
|
|
660
|
-
*
|
|
661
|
-
*
|
|
662
|
-
*
|
|
663
|
-
*
|
|
2515
|
+
* With no layer the token is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
|
|
2516
|
+
* `local`), the results are judged against what that token is meant to carry in that layer (the plugin's `tokens`
|
|
2517
|
+
* declaration, read with `tokenExpectations()`) and shown in two groups, what it should have and what it should not,
|
|
2518
|
+
* where a missing or extra permission fails.
|
|
664
2519
|
*/
|
|
2520
|
+
function tokenProbe(ctx) {
|
|
2521
|
+
return {
|
|
2522
|
+
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.",
|
|
2523
|
+
writes: false,
|
|
2524
|
+
acceptsToken: true,
|
|
2525
|
+
async run(probe) {
|
|
2526
|
+
const { layer, tokenName } = parseTokenArgs(probe.args ?? []);
|
|
2527
|
+
const envName = tokenName ?? DEFAULT_TOKEN;
|
|
2528
|
+
const token = ctx.resolve(envName);
|
|
2529
|
+
if (token === void 0) {
|
|
2530
|
+
probe.say({
|
|
2531
|
+
status: "fail",
|
|
2532
|
+
label: envName,
|
|
2533
|
+
detail: `not a GitHub token; use one of: ${ctx.tokenNames.join(", ")}`
|
|
2534
|
+
});
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
probe.secret(token);
|
|
2538
|
+
let identity;
|
|
2539
|
+
try {
|
|
2540
|
+
identity = await get(ctx, token, "/user");
|
|
2541
|
+
} catch (err) {
|
|
2542
|
+
probe.say({
|
|
2543
|
+
status: "fail",
|
|
2544
|
+
label: "token",
|
|
2545
|
+
detail: errorMessage(err)
|
|
2546
|
+
});
|
|
2547
|
+
return;
|
|
2548
|
+
}
|
|
2549
|
+
if (identity.status === 401) {
|
|
2550
|
+
probe.say({
|
|
2551
|
+
status: "fail",
|
|
2552
|
+
label: "token",
|
|
2553
|
+
detail: "rejected by GitHub (401): expired, revoked or not a token"
|
|
2554
|
+
});
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
const scopes = identity.headers.get("x-oauth-scopes");
|
|
2558
|
+
probe.say({
|
|
2559
|
+
status: "ok",
|
|
2560
|
+
label: "token",
|
|
2561
|
+
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`
|
|
2562
|
+
});
|
|
2563
|
+
const declared = layer ? tokenExpectations(tokens, {
|
|
2564
|
+
layer,
|
|
2565
|
+
envName
|
|
2566
|
+
})[0] : void 0;
|
|
2567
|
+
if (layer && !declared) probe.say({
|
|
2568
|
+
status: "info",
|
|
2569
|
+
label: layer,
|
|
2570
|
+
detail: "no expectations are declared for this token there, so it is only described"
|
|
2571
|
+
});
|
|
2572
|
+
const rules = declared?.rules ?? {};
|
|
2573
|
+
const names = declared ? Object.keys(rules) : Object.keys(PERMISSIONS);
|
|
2574
|
+
const tried = [];
|
|
2575
|
+
for (const permission of names) tried.push({
|
|
2576
|
+
label: PERMISSIONS[permission].label,
|
|
2577
|
+
permission,
|
|
2578
|
+
outcome: await reach(ctx, token, permission)
|
|
2579
|
+
});
|
|
2580
|
+
if (!declared) {
|
|
2581
|
+
for (const t of tried) probe.say(rowFor(t, void 0));
|
|
2582
|
+
return;
|
|
2583
|
+
}
|
|
2584
|
+
for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
|
|
2585
|
+
const inGroup = tried.filter((t) => rules[t.permission] === rule);
|
|
2586
|
+
if (inGroup.length === 0) continue;
|
|
2587
|
+
probe.say({
|
|
2588
|
+
status: "heading",
|
|
2589
|
+
label: heading
|
|
2590
|
+
});
|
|
2591
|
+
for (const t of inGroup) probe.say(rowFor(t, rule));
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
// src/token-resolvers.ts
|
|
2597
|
+
/** Each token's resolver by its environment variable (`HOLOCRON_ADMIN_TOKEN`), which is what `--token-name` carries. */
|
|
2598
|
+
const TOKEN_RESOLVERS = {
|
|
2599
|
+
HOLOCRON_READ_TOKEN: resolveReadToken,
|
|
2600
|
+
HOLOCRON_ISSUES_TOKEN: resolveIssuesToken,
|
|
2601
|
+
HOLOCRON_SYNC_TOKEN: resolveSyncToken,
|
|
2602
|
+
HOLOCRON_RELEASE_TOKEN: resolveReleaseToken,
|
|
2603
|
+
HOLOCRON_ADMIN_TOKEN: resolveAdminToken,
|
|
2604
|
+
HOLOCRON_SECRETS_TOKEN: resolveSecretsToken,
|
|
2605
|
+
HOLOCRON_DEPLOY_TOKEN: resolveDeployToken,
|
|
2606
|
+
HOLOCRON_USER_SYNC_TOKEN: resolveUserSyncToken,
|
|
2607
|
+
HOLOCRON_ORG_TOKEN: resolveOrgToken
|
|
2608
|
+
};
|
|
2609
|
+
// src/verify-token.ts
|
|
2610
|
+
/** Checks a token against `GET /user` and returns who it belongs to, or why it failed. */
|
|
665
2611
|
async function verifyToken(token, opts = {}) {
|
|
666
2612
|
const client = createGitHubClient({
|
|
667
2613
|
token,
|
|
@@ -669,49 +2615,61 @@ async function verifyToken(token, opts = {}) {
|
|
|
669
2615
|
fetch: opts.fetch
|
|
670
2616
|
});
|
|
671
2617
|
try {
|
|
672
|
-
const me = await client.user.
|
|
2618
|
+
const { user: me, expiresAt } = await client.user.getCurrentUserWithExpiry();
|
|
673
2619
|
return {
|
|
674
2620
|
ok: true,
|
|
675
|
-
subject: `user @ ${me.login ?? me.email ?? "unknown"}
|
|
2621
|
+
subject: `user @ ${me.login ?? me.email ?? "unknown"}`,
|
|
2622
|
+
...expiresAt ? { expiresAt } : {}
|
|
676
2623
|
};
|
|
677
2624
|
} catch (err) {
|
|
678
2625
|
return {
|
|
679
2626
|
ok: false,
|
|
680
|
-
message:
|
|
2627
|
+
message: errorMessage(err)
|
|
681
2628
|
};
|
|
682
2629
|
}
|
|
683
2630
|
}
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
function source(ctx, orgClient) {
|
|
2631
|
+
// src/index.ts
|
|
2632
|
+
/** Builds the `source` capability; the optional clients cover org-level and user-sync access. */
|
|
2633
|
+
function source(ctx, orgClient, userSyncClient) {
|
|
687
2634
|
return new GitHubSource(ctx.client, {
|
|
688
2635
|
repo: ctx.repo,
|
|
689
2636
|
repoRoot: ctx.repoRoot,
|
|
690
2637
|
orgClient,
|
|
2638
|
+
userSyncClient,
|
|
691
2639
|
baseUrl: ctx.options.baseUrl,
|
|
692
2640
|
fetch: ctx.options.fetch
|
|
693
2641
|
});
|
|
694
2642
|
}
|
|
695
|
-
|
|
696
|
-
|
|
2643
|
+
/** Builds the `secrets` capability; the optional client handles organization secrets. */
|
|
2644
|
+
function secrets(ctx, orgClient) {
|
|
2645
|
+
return new GitHubSecrets(ctx.client, { repo: ctx.repo }, orgClient);
|
|
697
2646
|
}
|
|
2647
|
+
/** Builds the `environments` capability. */
|
|
698
2648
|
function environments(ctx) {
|
|
699
2649
|
return new GitHubEnvironments(ctx.client, { repo: ctx.repo });
|
|
700
2650
|
}
|
|
2651
|
+
/** Builds the `ci` capability. */
|
|
701
2652
|
function ci(ctx) {
|
|
702
2653
|
return new GitHubCi(ctx.client, { repo: ctx.repo });
|
|
703
2654
|
}
|
|
2655
|
+
/** Builds the `issues` capability, passing the lifecycle labels when configured. */
|
|
704
2656
|
function issues(ctx) {
|
|
705
2657
|
const opts = { repo: ctx.repo };
|
|
706
2658
|
if (ctx.options.labels !== void 0) opts.labels = ctx.options.labels;
|
|
707
2659
|
return new GitHubIssues(ctx.client, opts);
|
|
708
2660
|
}
|
|
2661
|
+
/** Builds the `projects` capability: GitHub Projects v2 over GraphQL, with items keyed relative to the configured repo. */
|
|
2662
|
+
function projects(ctx) {
|
|
2663
|
+
return new GitHubProjects(ctx.client.graphql, { repo: ctx.repo });
|
|
2664
|
+
}
|
|
2665
|
+
/** Creates the plugin, resolving a token per capability when it is first used. */
|
|
709
2666
|
function createPlugin(options) {
|
|
710
2667
|
function makeCtx(resolver) {
|
|
2668
|
+
const token = resolver(options);
|
|
711
2669
|
return {
|
|
712
2670
|
options,
|
|
713
2671
|
client: createGitHubClient$1({
|
|
714
|
-
token
|
|
2672
|
+
token,
|
|
715
2673
|
baseUrl: options.baseUrl,
|
|
716
2674
|
fetch: options.fetch
|
|
717
2675
|
}),
|
|
@@ -719,10 +2677,45 @@ function createPlugin(options) {
|
|
|
719
2677
|
repoRoot: options.repoRoot ?? process.cwd()
|
|
720
2678
|
};
|
|
721
2679
|
}
|
|
2680
|
+
/** A token, or undefined when that feature token is simply not configured. */
|
|
2681
|
+
function tryResolve(resolver) {
|
|
2682
|
+
try {
|
|
2683
|
+
return resolver(options);
|
|
2684
|
+
} catch (err) {
|
|
2685
|
+
if (err instanceof AuthError) return void 0;
|
|
2686
|
+
throw err;
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
/**
|
|
2690
|
+
* Organization secrets need an org-resource-owner token (`github.secrets`);
|
|
2691
|
+
* repo and environment secrets need `github.admin`. Each scope prefers its own
|
|
2692
|
+
* token and falls back to the other, so a setup with only one of them keeps
|
|
2693
|
+
* working, and an explicit `--token` serves both. With neither configured this
|
|
2694
|
+
* fails exactly as the admin-token capabilities do.
|
|
2695
|
+
*/
|
|
2696
|
+
function makeSecrets() {
|
|
2697
|
+
const secretsToken = tryResolve(resolveSecretsToken);
|
|
2698
|
+
const adminToken = tryResolve(resolveAdminToken);
|
|
2699
|
+
if (!secretsToken && !adminToken) resolveAdminToken(options);
|
|
2700
|
+
const clientFor = (token) => createGitHubClient$1({
|
|
2701
|
+
token,
|
|
2702
|
+
baseUrl: options.baseUrl,
|
|
2703
|
+
fetch: options.fetch
|
|
2704
|
+
});
|
|
2705
|
+
const repoClient = clientFor(adminToken ?? secretsToken);
|
|
2706
|
+
const orgClient = clientFor(secretsToken ?? adminToken);
|
|
2707
|
+
return secrets({
|
|
2708
|
+
options,
|
|
2709
|
+
client: repoClient,
|
|
2710
|
+
repo: options.repo,
|
|
2711
|
+
repoRoot: options.repoRoot ?? process.cwd()
|
|
2712
|
+
}, orgClient);
|
|
2713
|
+
}
|
|
722
2714
|
function makeOrgClient() {
|
|
723
2715
|
try {
|
|
2716
|
+
const token = resolveOrgToken(options);
|
|
724
2717
|
return createGitHubClient$1({
|
|
725
|
-
token
|
|
2718
|
+
token,
|
|
726
2719
|
baseUrl: options.baseUrl,
|
|
727
2720
|
fetch: options.fetch
|
|
728
2721
|
});
|
|
@@ -730,21 +2723,49 @@ function createPlugin(options) {
|
|
|
730
2723
|
return;
|
|
731
2724
|
}
|
|
732
2725
|
}
|
|
2726
|
+
/** The token for the user-sync files; undefined when it is not configured, and the org token is used instead. */
|
|
2727
|
+
function makeUserSyncClient() {
|
|
2728
|
+
const token = tryResolve(resolveUserSyncToken);
|
|
2729
|
+
return token ? createGitHubClient$1({
|
|
2730
|
+
token,
|
|
2731
|
+
baseUrl: options.baseUrl,
|
|
2732
|
+
fetch: options.fetch
|
|
2733
|
+
}) : void 0;
|
|
2734
|
+
}
|
|
733
2735
|
return {
|
|
734
2736
|
name: "@theholocron/holocron-plugin-github",
|
|
2737
|
+
probes: {
|
|
2738
|
+
token: tokenProbe({
|
|
2739
|
+
repo: options.repo,
|
|
2740
|
+
baseUrl: (options.baseUrl ?? "https://api.github.com").replace(/\/$/, ""),
|
|
2741
|
+
fetch: options.fetch ?? fetch,
|
|
2742
|
+
resolve: (envName) => TOKEN_RESOLVERS[envName]?.(options),
|
|
2743
|
+
tokenNames: Object.keys(TOKEN_RESOLVERS)
|
|
2744
|
+
}),
|
|
2745
|
+
connection: connectionProbe({
|
|
2746
|
+
provider: "GitHub",
|
|
2747
|
+
url: options.baseUrl ?? "https://api.github.com",
|
|
2748
|
+
fetch: options.fetch,
|
|
2749
|
+
token: () => resolveReadToken(options),
|
|
2750
|
+
verify: (token) => verifyToken(token, {
|
|
2751
|
+
baseUrl: options.baseUrl,
|
|
2752
|
+
fetch: options.fetch
|
|
2753
|
+
})
|
|
2754
|
+
})
|
|
2755
|
+
},
|
|
735
2756
|
capabilities: {
|
|
736
|
-
source: () => source(makeCtx(resolveAdminToken), makeOrgClient()),
|
|
2757
|
+
source: () => source(makeCtx(resolveAdminToken), makeOrgClient(), makeUserSyncClient()),
|
|
737
2758
|
ci: () => ci(makeCtx(resolveReadToken)),
|
|
738
|
-
secrets: () =>
|
|
2759
|
+
secrets: () => makeSecrets(),
|
|
739
2760
|
environments: () => environments(makeCtx(resolveAdminToken)),
|
|
740
|
-
issues: () => issues(makeCtx(resolveIssuesToken))
|
|
2761
|
+
issues: () => issues(makeCtx(resolveIssuesToken)),
|
|
2762
|
+
projects: () => projects(makeCtx(resolveOrgToken))
|
|
741
2763
|
}
|
|
742
2764
|
};
|
|
743
2765
|
}
|
|
744
2766
|
/**
|
|
745
|
-
* One-line hint printed by `holocron
|
|
2767
|
+
* One-line hint printed by `holocron new token github` when no token
|
|
746
2768
|
* is supplied or the supplied token is rejected.
|
|
747
2769
|
*/
|
|
748
|
-
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
|
|
749
|
-
|
|
750
|
-
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 };
|
|
2770
|
+
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>";
|
|
2771
|
+
export { AUTH_HINT, AuthError, GitHubCi, GitHubEnvironments, GitHubIssues, GitHubProjects, GitHubSecrets, GitHubSource, ci, createFeatureResolver, createGitHubClient, createPlugin, encryptSecret, environments, issues, normalizeTeamEntry, projects, resolveAdminToken, resolveDeployToken, resolveIssuesToken, resolveOrgToken, resolveReadToken, resolveReleaseToken, resolveSecretsToken, resolveSyncToken, resolveUserSyncToken, secrets, source, syncLabels, syncTeams, tokens, verifyToken };
|