@theholocron/holocron-plugin-github 5.0.0-alpha.501 → 5.0.0-alpha.502

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/dist/index.d.mts CHANGED
@@ -7,7 +7,7 @@
7
7
  * receives plugin-level options from `holocron.config.json` and
8
8
  * returns the bound implementation.
9
9
  */
10
- import { AddedItem, Auth, AuthError, BoardItem, BoardItemInput, BoardState, BoardSummary, BoardTemplate, Ci, CiRun, CiRunFilter, EnsureReport, Environment, Environments, ExportInfo, ImportOptions, ImportResult, Issue, IssueRecord, IssueSearchFilter, IssueSelector, Issues, LabelDef, LifecycleResult, LifecycleSlot, MoveReport, PagesConfig, PluginToken, Projects, PullRequest, RepoRef, RepoSettings, ResolveTokenInput, Ruleset, SecretAccess, SecretScope, Secrets, Source, SourceBranch, SourceFile, SourceRepoInfo, SourceRulesetDetail, SourceSecurity, SourceTeamMember, SyncResult, TeamEntry, TeamEntry as TeamEntry$1, TeamPermission, TeamPermission as TeamPermission$1, TrackerDoctorReport, TrackerUser, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, createFeatureResolver } from "@theholocron/cli";
10
+ import { AddedItem, Auth, AuthError, BoardItem, BoardItemInput, BoardState, BoardSummary, BoardTemplate, Ci, CiRun, CiRunFilter, EnsureReport, Environment, Environments, ExportInfo, ImportOptions, ImportResult, Issue, IssueCreateInput, IssuePatch, IssueRecord, IssueSearchFilter, IssueSelector, IssueUpdateResult, Issues, LabelDef, LifecycleResult, LifecycleSlot, MoveReport, PagesConfig, PluginToken, Projects, PullRequest, PullRequestChecks, PullRequestInput, PullRequestPatch, PullRequestResult, RepoRef, RepoSettings, ResolveTokenInput, Ruleset, SecretAccess, SecretScope, Secrets, Source, SourceBranch, SourceFile, SourceRepoInfo, SourceRulesetDetail, SourceSecurity, SourceTeamMember, SyncResult, TeamEntry, TeamEntry as TeamEntry$1, TeamPermission, TeamPermission as TeamPermission$1, TrackerDoctorReport, TrackerUser, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, createFeatureResolver } from "@theholocron/cli";
11
11
  import { GitHubClient, GitHubClientOptions, GraphQLClient, createGitHubClient } from "@theholocron/github-client";
12
12
  /** Resolves the token for read-only GitHub access (`HOLOCRON_READ_TOKEN`, keyring key `github.read`). */
13
13
  export declare const resolveReadToken: import("@theholocron/cli").FeatureResolver;
@@ -109,17 +109,17 @@ export declare class GitHubIssues implements Issues {
109
109
  private searchText;
110
110
  /** Fetches one issue by its key. */
111
111
  get(key: string): Promise<Issue>;
112
- /** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
113
- create(input: {
114
- summary: string;
115
- body?: string;
116
- labels?: string[];
117
- milestone?: string;
118
- assignees?: string[];
119
- }): Promise<{
112
+ /**
113
+ * Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. Type, Priority,
114
+ * Effort, the dates, the parent and the blockers are set after the issue exists; what GitHub refuses of them comes
115
+ * back in `dropped`, never as a failure, because the issue is made by then and its key must not be lost.
116
+ */
117
+ create(input: IssueCreateInput): Promise<{
120
118
  key: string;
121
119
  dropped?: string[];
122
120
  }>;
121
+ /** Changes an issue; see {@link updateGitHubIssue}. */
122
+ update(key: string, patch: IssuePatch): Promise<IssueUpdateResult>;
123
123
  transition(key: string, slot: LifecycleSlot): Promise<LifecycleResult>;
124
124
  /** Adds a comment to the issue with the given key. */
125
125
  comment(key: string, body: string): Promise<void>;
@@ -131,6 +131,9 @@ export declare class GitHubIssues implements Issues {
131
131
  import(records: IssueRecord[], options?: ImportOptions): Promise<ImportResult[]>;
132
132
  /** Like `import`, and it also updates what an earlier import or sync made, for `holocron sync issues`. */
133
133
  sync(records: IssueRecord[], options?: ImportOptions): Promise<SyncResult[]>;
134
+ private fieldSetter;
135
+ /** What the field writers need; the setter is shared so the organization's field list is read once. */
136
+ private fieldContext;
134
137
  private resolveMilestone;
135
138
  private removeStatusLabels;
136
139
  private mapIssue;
@@ -375,6 +378,11 @@ export declare class GitHubSource implements Source {
375
378
  listBranches(repo?: string): Promise<SourceBranch[]>;
376
379
  deleteBranch(name: string, repo?: string): Promise<void>;
377
380
  listPullRequestCommits(number: number, repo?: string): Promise<string[]>;
381
+ listPullRequestFiles(number: number, repo?: string): Promise<string[]>;
382
+ createPullRequest(input: PullRequestInput, repo?: string): Promise<PullRequestResult>;
383
+ updatePullRequest(number: number, patch: PullRequestPatch, repo?: string): Promise<PullRequestResult>;
384
+ markReady(number: number, repo?: string): Promise<boolean>;
385
+ getPullRequestChecks(number: number, repo?: string): Promise<PullRequestChecks>;
378
386
  configurePages(config: PagesConfig, token: string): Promise<void>;
379
387
  }
380
388
  /** A team entry with the permission spelled out. */
package/dist/index.mjs CHANGED
@@ -151,15 +151,21 @@ var GitHubEnvironments = class {
151
151
  }));
152
152
  }
153
153
  };
154
- // src/capabilities/issue-priority.ts
155
- const OPTION_NAMES = {
156
- urgent: "Urgent",
157
- high: "High",
158
- medium: "Medium",
159
- low: "Low"
160
- };
154
+ // src/capabilities/issue-field-setter.ts
155
+ /**
156
+ * Sets and clears one organization issue field (Priority, Effort, Start date, Target date) on an issue, for the
157
+ * `issues` capability's `create` and `update` and for `createPrioritySetter()`.
158
+ *
159
+ * The field list is read once per setter. A value is added with `POST`, which leaves the issue's other field values
160
+ * alone (`PUT` replaces all of them, and a multi-select value cannot be sent back with certainty); a value that differs
161
+ * is removed first. A missing field, a missing option or a refusal from GitHub (401, 403, 404, 422) comes back as a
162
+ * `note` for the caller's `dropped` list; a rate limit and every other failure are thrown. Spec
163
+ * `tech-github-issue-priority-field`, #2253, and `tool-work-commands`, #2429.
164
+ *
165
+ * Not verified against the live API: that Effort, Start date and Target date are written the way Priority is.
166
+ */
161
167
  /** Whether GitHub refused for a reason about access or setup, which a run reports and goes on from. */
162
- function refusal(err) {
168
+ function fieldRefusal(err) {
163
169
  if (!(err instanceof ProviderApiError)) return void 0;
164
170
  if (err.status === void 0 || ![
165
171
  401,
@@ -170,50 +176,108 @@ function refusal(err) {
170
176
  if (/rate limit/i.test(`${err.message} ${String(err.details)}`)) return void 0;
171
177
  return `GitHub refused: ${err.status}`;
172
178
  }
173
- function createPrioritySetter(client, repo) {
179
+ const DATA_TYPE = {
180
+ select: "single_select",
181
+ date: "date"
182
+ };
183
+ /** Makes the setter for the issues of `repo` (`owner/name`); the organization's field list is read on first use and kept. */
184
+ function createFieldSetter(client, repo) {
174
185
  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);
186
+ let fields;
187
+ const listFields = () => fields ??= client.issueFields.list(org).then((list) => list, (err) => {
188
+ const why = fieldRefusal(err);
181
189
  if (why === void 0) throw err;
182
- return { note: `priority field (${why})` };
190
+ return why;
183
191
  });
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 {
192
+ const label = (target) => `${target.name.toLowerCase()} field`;
193
+ const find = async (target) => {
194
+ const list = await listFields();
195
+ if (typeof list === "string") return { note: `${label(target)} (${list})` };
196
+ const field = list.find((f) => f.name.toLowerCase() === target.name.toLowerCase() && f.data_type === DATA_TYPE[target.type]);
197
+ return field ? { field } : { note: `${label(target)} (${org} has no ${target.name} issue field)` };
198
+ };
199
+ const currentOf = async (number, field, target, flags) => {
200
+ if (flags.isNew) return void 0;
201
+ const found = (await client.issueFields.values(repo, number)).find((v) => v.issue_field_id === field.id);
202
+ if (!found) return void 0;
203
+ return target.type === "date" ? String(found.value).slice(0, 10) : found.single_select_option?.name ?? String(found.value);
204
+ };
205
+ return {
206
+ async set(number, target, flags = {}) {
207
+ if (!target.value) return { changed: false };
208
+ const found = await find(target);
209
+ if ("note" in found) return {
212
210
  changed: false,
213
- note: `priority field (${why})`
211
+ note: found.note
214
212
  };
213
+ const { field } = found;
214
+ let value = target.value;
215
+ if (target.type === "select") {
216
+ const option = field.options?.find((o) => o.name.toLowerCase() === value.toLowerCase());
217
+ if (!option) return {
218
+ changed: false,
219
+ note: `${label(target)} (no "${value}" option)`
220
+ };
221
+ value = option.name;
222
+ }
223
+ try {
224
+ const current = await currentOf(number, field, target, flags);
225
+ if (current?.toLowerCase() === value.toLowerCase()) return { changed: false };
226
+ if (flags.dryRun) return { changed: true };
227
+ if (current !== void 0) await client.issueFields.deleteValue(repo, number, field.id);
228
+ await client.issueFields.addValues(repo, number, [{
229
+ field_id: field.id,
230
+ value
231
+ }]);
232
+ return { changed: true };
233
+ } catch (err) {
234
+ const why = fieldRefusal(err);
235
+ if (why === void 0) throw err;
236
+ return {
237
+ changed: false,
238
+ note: `${label(target)} (${why})`
239
+ };
240
+ }
241
+ },
242
+ async clear(number, target, flags = {}) {
243
+ if (flags.isNew) return { changed: false };
244
+ const found = await find(target);
245
+ if ("note" in found) return {
246
+ changed: false,
247
+ note: found.note
248
+ };
249
+ try {
250
+ if (await currentOf(number, found.field, target, flags) === void 0) return { changed: false };
251
+ if (flags.dryRun) return { changed: true };
252
+ await client.issueFields.deleteValue(repo, number, found.field.id);
253
+ return { changed: true };
254
+ } catch (err) {
255
+ const why = fieldRefusal(err);
256
+ if (why === void 0) throw err;
257
+ return {
258
+ changed: false,
259
+ note: `${label(target)} (${why})`
260
+ };
261
+ }
215
262
  }
216
- } };
263
+ };
264
+ }
265
+ // src/capabilities/issue-priority.ts
266
+ /** The Priority field's option for each level. */
267
+ const PRIORITY_OPTION_NAMES = {
268
+ urgent: "Urgent",
269
+ high: "High",
270
+ medium: "Medium",
271
+ low: "Low"
272
+ };
273
+ /** Makes the Priority setter for the issues of `repo` (`owner/name`). */
274
+ function createPrioritySetter(client, repo) {
275
+ const fields = createFieldSetter(client, repo);
276
+ return { set: (number, level, flags = {}) => !level || level === "none" ? Promise.resolve({ changed: false }) : fields.set(number, {
277
+ name: "Priority",
278
+ type: "select",
279
+ value: PRIORITY_OPTION_NAMES[level]
280
+ }, flags) };
217
281
  }
218
282
  // src/capabilities/issues-migration.ts
219
283
  /**
@@ -561,6 +625,215 @@ async function update(client, repo, issue, record, options, priority) {
561
625
  dropped: [...droppedFor(record), ...field.note ? [field.note] : []]
562
626
  };
563
627
  }
628
+ // src/capabilities/issues-update.ts
629
+ const KIND_NAMES = {
630
+ bug: "Bug",
631
+ feature: "Feature",
632
+ task: "Task"
633
+ };
634
+ const EFFORT_NAMES = {
635
+ high: "High",
636
+ medium: "Medium",
637
+ low: "Low"
638
+ };
639
+ /** Runs one step; a refusal or a bad key is a `dropped` line, anything else (a rate limit) is thrown. */
640
+ async function guarded(what, out, step) {
641
+ try {
642
+ await step();
643
+ } catch (err) {
644
+ const why = fieldRefusal(err);
645
+ if (why !== void 0) out.dropped.push(`${what} (${why})`);
646
+ else if (!(err instanceof ProviderApiError)) out.dropped.push(`${what} (${err.message})`);
647
+ else throw err;
648
+ }
649
+ }
650
+ const CLEAR_FIELD = {
651
+ priority: {
652
+ name: "Priority",
653
+ type: "select"
654
+ },
655
+ effort: {
656
+ name: "Effort",
657
+ type: "select"
658
+ },
659
+ startDate: {
660
+ name: "Start date",
661
+ type: "date"
662
+ },
663
+ targetDate: {
664
+ name: "Target date",
665
+ type: "date"
666
+ }
667
+ };
668
+ /**
669
+ * Writes the {@link IssueFields} of an issue, and clears and unblocks as `clear` and `unblock` ask. `issue` is the issue
670
+ * as it is now (its numeric id and Type); `isNew` says it was just made, so nothing is read to compare.
671
+ */
672
+ async function applyIssueFields(ctx, issue, input, isNew) {
673
+ const { client, repo } = ctx;
674
+ const fields = ctx.fields ??= createFieldSetter(client, repo);
675
+ const out = {
676
+ changed: [],
677
+ dropped: []
678
+ };
679
+ const flags = { isNew };
680
+ const clear = new Set(input.clear ?? []);
681
+ if (input.kind) {
682
+ const name = KIND_NAMES[input.kind];
683
+ if (issue.type?.name?.toLowerCase() !== name.toLowerCase()) await guarded(`kind ${name}`, out, async () => {
684
+ await client.issues.updateIssue(repo, issue.number, { type: name });
685
+ out.changed.push(`kind: ${name}`);
686
+ });
687
+ } else if (clear.has("kind") && issue.type) await guarded("kind", out, async () => {
688
+ await client.issues.updateIssue(repo, issue.number, { type: null });
689
+ out.changed.push("kind cleared");
690
+ });
691
+ const values = [
692
+ [
693
+ "priority",
694
+ "Priority",
695
+ "select",
696
+ input.priority && input.priority !== "none" ? PRIORITY_OPTION_NAMES[input.priority] : void 0
697
+ ],
698
+ [
699
+ "effort",
700
+ "Effort",
701
+ "select",
702
+ input.effort ? EFFORT_NAMES[input.effort] : void 0
703
+ ],
704
+ [
705
+ "startDate",
706
+ "Start date",
707
+ "date",
708
+ input.startDate
709
+ ],
710
+ [
711
+ "targetDate",
712
+ "Target date",
713
+ "date",
714
+ input.targetDate
715
+ ]
716
+ ];
717
+ for (const [label, name, type, value] of values) {
718
+ if (!value) continue;
719
+ const result = await fields.set(issue.number, {
720
+ name,
721
+ type,
722
+ value
723
+ }, flags);
724
+ if (result.note) out.dropped.push(result.note);
725
+ else if (result.changed) out.changed.push(`${label}: ${value}`);
726
+ }
727
+ for (const key of clear) {
728
+ const target = CLEAR_FIELD[key];
729
+ if (!target) continue;
730
+ const result = await fields.clear(issue.number, target, flags);
731
+ if (result.note) out.dropped.push(result.note);
732
+ else if (result.changed) out.changed.push(`${key} cleared`);
733
+ }
734
+ if (input.parent) {
735
+ const parentKey = input.parent;
736
+ await guarded(`parent ${parentKey}`, out, async () => {
737
+ const parentNumber = ctx.parseKey(parentKey);
738
+ const current = isNew ? null : await client.issues.getParent(repo, issue.number);
739
+ if (current?.number === parentNumber) return;
740
+ await client.issues.addSubIssue(repo, parentNumber, issue.id, current !== null);
741
+ out.changed.push(`parent: ${parentKey}`);
742
+ });
743
+ } else if (clear.has("parent") && !isNew) await guarded("parent", out, async () => {
744
+ const current = await client.issues.getParent(repo, issue.number);
745
+ if (!current) return;
746
+ await client.issues.removeSubIssue(repo, current.number, issue.id);
747
+ out.changed.push("parent cleared");
748
+ });
749
+ const adds = input.blockedBy ?? [];
750
+ const removes = input.unblock ?? [];
751
+ if (adds.length > 0 || removes.length > 0) {
752
+ let blockers;
753
+ const current = async () => blockers ??= isNew ? [] : await client.issues.listBlockedBy(repo, issue.number);
754
+ for (const key of adds) await guarded(`blocked by ${key}`, out, async () => {
755
+ const number = ctx.parseKey(key);
756
+ if ((await current()).some((b) => b.number === number)) return;
757
+ const blocker = await client.issues.getIssue(repo, number);
758
+ await client.issues.addBlockedBy(repo, issue.number, blocker.id);
759
+ out.changed.push(`blocked by: ${key}`);
760
+ });
761
+ for (const key of removes) await guarded(`unblock ${key}`, out, async () => {
762
+ const number = ctx.parseKey(key);
763
+ const blocker = (await current()).find((b) => b.number === number);
764
+ if (!blocker) return;
765
+ await client.issues.removeBlockedBy(repo, issue.number, blocker.id);
766
+ out.changed.push(`unblocked: ${key}`);
767
+ });
768
+ }
769
+ return out;
770
+ }
771
+ const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
772
+ /** Changes an issue to match the patch; whatever is already as asked is not written. */
773
+ async function updateGitHubIssue(ctx, key, patch) {
774
+ const { client, repo } = ctx;
775
+ const number = ctx.parseKey(key);
776
+ const issue = await client.issues.getIssue(repo, number);
777
+ const changed = [];
778
+ const clear = new Set(patch.clear ?? []);
779
+ const body = {};
780
+ if (patch.title !== void 0 && patch.title !== issue.title) {
781
+ body.title = patch.title;
782
+ changed.push("title");
783
+ }
784
+ if (patch.body !== void 0 && patch.body !== (issue.body ?? "")) {
785
+ body.body = patch.body;
786
+ changed.push("body");
787
+ }
788
+ if (patch.state && patch.state !== issue.state) {
789
+ body.state = patch.state;
790
+ if (patch.state === "closed") body.state_reason = patch.stateReason ?? "completed";
791
+ changed.push(`state: ${patch.state}`);
792
+ }
793
+ const have = (issue.assignees ?? (issue.assignee ? [issue.assignee] : [])).map((a) => a.login);
794
+ if (patch.assignees?.length) {
795
+ const isMe = (a) => /^@?me$/i.test(a);
796
+ const me = patch.assignees.some(isMe) ? await ctx.myLogin() : void 0;
797
+ const want = [...new Set(patch.assignees.map((a) => isMe(a) && me ? me : a.replace(/^@/, "")))];
798
+ if (!sameSet(want.map((a) => a.toLowerCase()), have.map((a) => a.toLowerCase()))) {
799
+ body.assignees = want;
800
+ changed.push(`assignees: ${want.join(", ")}`);
801
+ }
802
+ } else if (clear.has("assignees") && have.length > 0) {
803
+ body.assignees = [];
804
+ changed.push("assignees cleared");
805
+ }
806
+ if (patch.milestone) {
807
+ const milestone = await ctx.resolveMilestone(patch.milestone);
808
+ if (issue.milestone?.number !== milestone) {
809
+ body.milestone = milestone;
810
+ changed.push(`milestone: ${patch.milestone}`);
811
+ }
812
+ } else if (clear.has("milestone") && issue.milestone) {
813
+ body.milestone = null;
814
+ changed.push("milestone cleared");
815
+ }
816
+ if (Object.keys(body).length > 0) await client.issues.updateIssue(repo, number, body);
817
+ const labels = new Set(issue.labels.map((l) => l.name.toLowerCase()));
818
+ const add = [...new Set(patch.addLabels ?? [])].filter((l) => !labels.has(l.toLowerCase()));
819
+ if (add.length > 0) {
820
+ await client.issues.addLabels(repo, number, add);
821
+ changed.push(`labels added: ${add.join(", ")}`);
822
+ }
823
+ for (const label of new Set(patch.removeLabels ?? [])) {
824
+ if (!labels.has(label.toLowerCase())) continue;
825
+ const exact = issue.labels.find((l) => l.name.toLowerCase() === label.toLowerCase()).name;
826
+ await client.issues.removeLabel(repo, number, exact);
827
+ changed.push(`label removed: ${exact}`);
828
+ }
829
+ const fields = await applyIssueFields(ctx, issue, patch, false);
830
+ const all = [...changed, ...fields.changed];
831
+ return {
832
+ key: `#${number}`,
833
+ changed: all,
834
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
835
+ };
836
+ }
564
837
  // src/capabilities/issues.ts
565
838
  /** Issues read per request when `search` has a `text`; GitHub's largest page. */
566
839
  const TEXT_PAGE_SIZE = 100;
@@ -655,7 +928,11 @@ var GitHubIssues = class {
655
928
  const raw = await this.client.issues.getIssue(this.repo, number);
656
929
  return this.mapIssue(raw);
657
930
  }
658
- /** Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. */
931
+ /**
932
+ * Creates an issue and returns its key as `#<number>`; the milestone is resolved from its title. Type, Priority,
933
+ * Effort, the dates, the parent and the blockers are set after the issue exists; what GitHub refuses of them comes
934
+ * back in `dropped`, never as a failure, because the issue is made by then and its key must not be lost.
935
+ */
659
936
  async create(input) {
660
937
  const body = { title: input.summary };
661
938
  if (input.assignees?.length) {
@@ -666,7 +943,24 @@ var GitHubIssues = class {
666
943
  if (input.body) body.body = input.body;
667
944
  if (input.labels?.length) body.labels = input.labels;
668
945
  if (input.milestone) body.milestone = await this.resolveMilestone(input.milestone);
669
- return { key: `#${(await this.client.issues.createIssue(this.repo, body)).number}` };
946
+ const raw = await this.client.issues.createIssue(this.repo, body);
947
+ const key = `#${raw.number}`;
948
+ const fields = await applyIssueFields(this.fieldContext(), raw, input, true).catch((err) => ({
949
+ changed: [],
950
+ dropped: [`fields (not set: ${err.message})`]
951
+ }));
952
+ return {
953
+ key,
954
+ ...fields.dropped.length > 0 ? { dropped: fields.dropped } : {}
955
+ };
956
+ }
957
+ /** Changes an issue; see {@link updateGitHubIssue}. */
958
+ update(key, patch) {
959
+ return updateGitHubIssue({
960
+ ...this.fieldContext(),
961
+ myLogin: async () => (await this.getMyself()).id,
962
+ resolveMilestone: (ref) => this.resolveMilestone(ref)
963
+ }, key, patch);
670
964
  }
671
965
  async transition(key, slot) {
672
966
  const number = parseIssueNumber(key, this.owner, this.repoName);
@@ -794,6 +1088,17 @@ var GitHubIssues = class {
794
1088
  sync(records, options) {
795
1089
  return syncIssues(this.client, this.repo, records, options);
796
1090
  }
1091
+ fieldSetter;
1092
+ /** What the field writers need; the setter is shared so the organization's field list is read once. */
1093
+ fieldContext() {
1094
+ this.fieldSetter ??= createFieldSetter(this.client, this.repo);
1095
+ return {
1096
+ client: this.client,
1097
+ repo: this.repo,
1098
+ parseKey: (k) => parseIssueNumber(k, this.owner, this.repoName),
1099
+ fields: this.fieldSetter
1100
+ };
1101
+ }
797
1102
  async resolveMilestone(ref) {
798
1103
  if (/^\d+$/.test(ref)) return parseInt(ref, 10);
799
1104
  const match = (await this.client.issues.listMilestones(this.repo, { state: "all" })).find((m) => m.title.toLowerCase() === ref.toLowerCase());
@@ -855,7 +1160,7 @@ const CLOSING_QUERY = `query($id: ID!) { node(id: $id) { ... on Issue {
855
1160
  } } } } }
856
1161
  } }
857
1162
  } } }`;
858
- const FAILED = /* @__PURE__ */ new Set([
1163
+ const FAILED$1 = /* @__PURE__ */ new Set([
859
1164
  "FAILURE",
860
1165
  "TIMED_OUT",
861
1166
  "STARTUP_FAILURE",
@@ -872,7 +1177,7 @@ function aggregateChecks(runs) {
872
1177
  if (!newest) return "none";
873
1178
  if (newest.status !== "COMPLETED") return "pending";
874
1179
  if (newest.conclusion === "SUCCESS") return "success";
875
- if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
1180
+ if (newest.conclusion && FAILED$1.has(newest.conclusion)) return "failure";
876
1181
  if (newest.conclusion === "CANCELLED") return "pending";
877
1182
  return "none";
878
1183
  }
@@ -1828,6 +2133,178 @@ async function addOrgPropertyValues(client, repo, name, values, viaOrgToken = tr
1828
2133
  }
1829
2134
  return added;
1830
2135
  }
2136
+ // src/capabilities/pull-request-checks.ts
2137
+ /** The check run the aggregate `ci` workflow posts on a pull request's head commit. */
2138
+ const AGGREGATE_CHECK = "ci / Required checks";
2139
+ const FAILED = /* @__PURE__ */ new Set([
2140
+ "failure",
2141
+ "timed_out",
2142
+ "startup_failure",
2143
+ "action_required",
2144
+ "stale"
2145
+ ]);
2146
+ const newestFirst = (a, b) => (b.started_at ?? "").localeCompare(a.started_at ?? "") || b.id - a.id;
2147
+ /** The aggregate's verdict from its runs: only the newest counts; a cancelled or unfinished run is `pending`. */
2148
+ function aggregateState(runs) {
2149
+ const newest = [...runs].sort(newestFirst)[0];
2150
+ if (!newest) return "none";
2151
+ if (newest.status !== "completed") return "pending";
2152
+ if (newest.conclusion === "success") return "success";
2153
+ if (newest.conclusion && FAILED.has(newest.conclusion)) return "failure";
2154
+ if (newest.conclusion === "cancelled") return "pending";
2155
+ return "none";
2156
+ }
2157
+ /**
2158
+ * The aggregate check of a pull request's newest commit and the checks that failed on it, read now (never cached, so a
2159
+ * caller that polls sees each change). The newest run of each name counts, so a job that failed and was re-run to green
2160
+ * is not listed.
2161
+ */
2162
+ async function readPullRequestChecks(client, repo, number) {
2163
+ const sha = (await client.pulls.getPullRequest(repo, number)).head.sha;
2164
+ const runs = await client.checks.listCheckRunsForRef(repo, sha);
2165
+ const newest = /* @__PURE__ */ new Map();
2166
+ for (const run of [...runs].sort(newestFirst)) if (!newest.has(run.name)) newest.set(run.name, run);
2167
+ return {
2168
+ state: aggregateState(runs.filter((r) => r.name === AGGREGATE_CHECK)),
2169
+ sha,
2170
+ failing: [...newest.values()].filter((r) => r.status === "completed" && r.conclusion !== null && FAILED.has(r.conclusion)).map((r) => ({
2171
+ name: r.name,
2172
+ url: r.details_url ?? r.html_url
2173
+ }))
2174
+ };
2175
+ }
2176
+ // src/capabilities/pull-requests.ts
2177
+ /** The GitHub pull request as the neutral {@link PullRequest}. */
2178
+ function toPullRequest(raw) {
2179
+ return {
2180
+ number: raw.number,
2181
+ title: raw.title,
2182
+ state: raw.state,
2183
+ merged: raw.merged_at !== null,
2184
+ branch: raw.head.ref,
2185
+ headSha: raw.head.sha,
2186
+ url: raw.html_url
2187
+ };
2188
+ }
2189
+ /** Whether a body already holds a closing or referencing line for the issue (any keyword, any case). */
2190
+ function names(body, issue) {
2191
+ const escaped = issue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2192
+ return new RegExp(`\\b(closes?|fix(es)?|resolves?|refs?)\\s+${escaped}(?![\\w-])`, "i").test(body);
2193
+ }
2194
+ /**
2195
+ * The body with the link line the issue's closing reference needs. GitHub reads `Closes #12` itself, so the link is
2196
+ * text, not a call; a body that already names the issue is left alone.
2197
+ */
2198
+ function withLink(body, link) {
2199
+ if (!link) return body;
2200
+ const issue = link.issue.trim();
2201
+ const ref = /^\d+$/.test(issue) ? `#${issue}` : issue;
2202
+ const text = body ?? "";
2203
+ if (names(text, ref)) return body;
2204
+ const line = `${link.keyword ?? "Refs"} ${ref}`;
2205
+ return text.trim() === "" ? line : `${text.replace(/\s+$/, "")}\n\n${line}`;
2206
+ }
2207
+ /** Puts the pull request (by node id) on each board of the organization found by title; a board not found or refused is returned by name. */
2208
+ async function addToBoards(client, repo, nodeId, titles) {
2209
+ const dropped = [];
2210
+ const owner = repo.slice(0, repo.indexOf("/"));
2211
+ let boards;
2212
+ try {
2213
+ boards = (await client.graphql.query(`query($owner: String!) { organization(login: $owner) { projectsV2(first: 100) { nodes { id title closed } } } }`, { owner })).organization;
2214
+ } catch {
2215
+ return titles.map((t) => `project ${t}`);
2216
+ }
2217
+ for (const title of titles) {
2218
+ const board = boards?.projectsV2.nodes.find((b) => b.title === title && !b.closed);
2219
+ if (!board) {
2220
+ dropped.push(`project ${title}`);
2221
+ continue;
2222
+ }
2223
+ try {
2224
+ await client.graphql.query(`mutation($project: ID!, $content: ID!) { addProjectV2ItemById(input: { projectId: $project, contentId: $content }) { item { id } } }`, {
2225
+ project: board.id,
2226
+ content: nodeId
2227
+ });
2228
+ } catch {
2229
+ dropped.push(`project ${title}`);
2230
+ }
2231
+ }
2232
+ return dropped;
2233
+ }
2234
+ /**
2235
+ * Puts the fields an issue and its pull request share on the pull request (GitHub serves a pull request through
2236
+ * the issues API for these): labels and assignees are added to what is there, a milestone is found by title and
2237
+ * boards by title. What cannot be applied comes back by name; nothing is created or cleared.
2238
+ */
2239
+ async function applyFields(client, repo, pr, fields) {
2240
+ const dropped = [];
2241
+ const { number } = pr;
2242
+ if (fields.labels?.length) await client.issues.addLabels(repo, number, fields.labels);
2243
+ for (const label of fields.removeLabels ?? []) try {
2244
+ await client.issues.removeLabel(repo, number, label);
2245
+ } catch {}
2246
+ const patch = {};
2247
+ if (fields.assignees?.length) {
2248
+ const have = ((await client.issues.getIssue(repo, number)).assignees ?? []).map((a) => a.login);
2249
+ const want = fields.assignees.map((a) => a.replace(/^@/, ""));
2250
+ const next = [.../* @__PURE__ */ new Set([...have, ...want])];
2251
+ if (next.length !== have.length) patch.assignees = next;
2252
+ }
2253
+ if (fields.milestone) {
2254
+ const found = (await client.issues.listMilestones(repo, { state: "open" })).find((m) => m.title === fields.milestone);
2255
+ if (found) patch.milestone = found.number;
2256
+ else dropped.push(`milestone ${fields.milestone}`);
2257
+ }
2258
+ if (Object.keys(patch).length) await client.issues.updateIssue(repo, number, patch);
2259
+ if (fields.projects?.length) {
2260
+ if (pr.node_id) dropped.push(...await addToBoards(client, repo, pr.node_id, fields.projects));
2261
+ else dropped.push(...fields.projects.map((t) => `project ${t}`));
2262
+ }
2263
+ return dropped;
2264
+ }
2265
+ /** Opens a draft pull request, or returns the open one for the same head, and applies the mirrored fields. */
2266
+ async function createPullRequest(client, repo, input) {
2267
+ const existing = (await client.pulls.listOpenByHead(repo, input.head))[0];
2268
+ const created = !existing;
2269
+ const raw = existing ?? await client.pulls.createPullRequest(repo, {
2270
+ title: input.title,
2271
+ head: input.head,
2272
+ base: input.base,
2273
+ body: withLink(input.body, input.link),
2274
+ draft: input.draft ?? true
2275
+ });
2276
+ const dropped = await applyFields(client, repo, raw, input);
2277
+ return {
2278
+ pullRequest: toPullRequest(raw),
2279
+ created,
2280
+ draft: raw.draft ?? false,
2281
+ dropped
2282
+ };
2283
+ }
2284
+ /** Changes a pull request's own fields, then the mirrored ones. A patch that names none of the own fields makes no PATCH. */
2285
+ async function updatePullRequest(client, repo, number, patch) {
2286
+ const own = {};
2287
+ if (patch.title !== void 0) own.title = patch.title;
2288
+ if (patch.body !== void 0) own.body = patch.body;
2289
+ if (patch.base !== void 0) own.base = patch.base;
2290
+ if (patch.state !== void 0) own.state = patch.state;
2291
+ const raw = Object.keys(own).length ? await client.pulls.updatePullRequest(repo, number, own) : await client.pulls.getPullRequest(repo, number);
2292
+ const dropped = await applyFields(client, repo, raw, patch);
2293
+ return {
2294
+ pullRequest: toPullRequest(raw),
2295
+ created: false,
2296
+ draft: raw.draft ?? false,
2297
+ dropped
2298
+ };
2299
+ }
2300
+ /** Takes a draft out of draft; `false` when it was not a draft or is not open. */
2301
+ async function markReady(client, repo, number) {
2302
+ const raw = await client.pulls.getPullRequest(repo, number);
2303
+ if (!raw.draft || raw.state !== "open") return false;
2304
+ if (!raw.node_id) throw new Error(`pull request ${repo}#${number} has no node id to mark ready`);
2305
+ await client.pulls.markReadyForReview(raw.node_id);
2306
+ return true;
2307
+ }
1831
2308
  // src/capabilities/read-repo.ts
1832
2309
  /** The settings `setup` writes, which `GET /repos/{repo}` reports under the same names. */
1833
2310
  const SETTING_KEYS = [
@@ -2030,17 +2507,6 @@ function syncOrgVariables(client, repo, org, variables, opts = {}) {
2030
2507
  });
2031
2508
  }
2032
2509
  // src/capabilities/source.ts
2033
- function toPullRequest(raw) {
2034
- return {
2035
- number: raw.number,
2036
- title: raw.title,
2037
- state: raw.state,
2038
- merged: raw.merged_at !== null,
2039
- branch: raw.head.ref,
2040
- headSha: raw.head.sha,
2041
- url: raw.html_url
2042
- };
2043
- }
2044
2510
  /**
2045
2511
  * The GitHub implementation of the `source` capability: repo settings, rulesets, branch protection, security
2046
2512
  * features and local workflow files.
@@ -2281,6 +2747,22 @@ var GitHubSource = class {
2281
2747
  async listPullRequestCommits(number, repo) {
2282
2748
  return (await this.client.pulls.listCommits(repo ?? this.repo, number)).map((commit) => commit.sha);
2283
2749
  }
2750
+ async listPullRequestFiles(number, repo) {
2751
+ const files = await this.client.pulls.listFiles(repo ?? this.repo, number);
2752
+ return [...new Set(files.flatMap((f) => f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]))];
2753
+ }
2754
+ async createPullRequest(input, repo) {
2755
+ return createPullRequest(this.client, repo ?? this.repo, input);
2756
+ }
2757
+ async updatePullRequest(number, patch, repo) {
2758
+ return updatePullRequest(this.client, repo ?? this.repo, number, patch);
2759
+ }
2760
+ async markReady(number, repo) {
2761
+ return markReady(this.client, repo ?? this.repo, number);
2762
+ }
2763
+ async getPullRequestChecks(number, repo) {
2764
+ return readPullRequestChecks(this.client, repo ?? this.repo, number);
2765
+ }
2284
2766
  async configurePages(config, token) {
2285
2767
  const pagesClient = createGitHubClient$1({
2286
2768
  token,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-github",
3
- "version": "5.0.0-alpha.501",
3
+ "version": "5.0.0-alpha.502",
4
4
  "description": "Holocron plugin for GitHub. Implements source, ci, secrets, environments, and issues capabilities against the GitHub REST API.",
5
5
  "keywords": [
6
6
  "ci",
@@ -44,21 +44,21 @@
44
44
  "tsx": "4.23.15",
45
45
  "typescript": "^5.9.3",
46
46
  "vitest": "^5.1.0",
47
- "@theholocron/cli": "5.0.0-alpha.501",
48
- "@theholocron/eslint-config": "^8.9.0-alpha.21",
47
+ "@theholocron/cli": "5.0.0-alpha.502",
49
48
  "@theholocron/fs-utils": "^1.17.0-alpha.5",
50
49
  "@theholocron/github-client": "^1.58.0-alpha.45",
50
+ "@theholocron/eslint-config": "^8.9.0-alpha.21",
51
51
  "@theholocron/http-client": "^1.58.0-alpha.45",
52
- "@theholocron/misc-utils": "^1.17.0-alpha.5",
53
52
  "@theholocron/tsconfig": "^8.9.0-alpha.21",
54
53
  "@theholocron/tsdown-config": "^8.9.0-alpha.21",
54
+ "@theholocron/misc-utils": "^1.17.0-alpha.5",
55
55
  "@theholocron/vitest-config": "^8.9.0-alpha.21"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@theholocron/fs-utils": "^1.16.0",
59
59
  "@theholocron/github-client": "^1.58.0",
60
60
  "@theholocron/misc-utils": "^1.16.0",
61
- "@theholocron/cli": "5.0.0-alpha.501"
61
+ "@theholocron/cli": "5.0.0-alpha.502"
62
62
  },
63
63
  "engines": {
64
64
  "node": ">=22"