@leitwerk-dev/forgejo-repo-change 0.3.0 → 0.3.1

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/src/process.ts CHANGED
@@ -2,27 +2,19 @@ import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
2
2
  import {
3
3
  createRepositoryChangePublication,
4
4
  publicationObject as object,
5
- type PublicationContext,
6
5
  type PublicationSource,
7
6
  type PublicationState,
7
+ pullRequestPublicationCallbacks,
8
+ pullRequestPublicationSources,
8
9
  readPublicationState,
10
+ reconcilePullRequestSourceIssue,
11
+ resolvePullRequestGitIdentity,
9
12
  } from "@leitwerk-dev/coding/repository-change-publication";
10
13
  import type { RepositoryChangeState } from "@leitwerk-dev/coding/repository-change-state";
11
- import {
12
- type ForgejoGitIdentity,
13
- type ForgejoPullRequest,
14
- forgejoExternal,
15
- forgejoIssueWatcherSource,
16
- } from "@leitwerk-dev/forgejo";
17
- import type { FlowAutomaticRunContext } from "@leitwerk-dev/process-sdk";
14
+ import { forgejoExternal, forgejoIssueWatcherSource } from "@leitwerk-dev/forgejo";
18
15
  import { woodpeckerExternal } from "@leitwerk-dev/woodpecker";
16
+ import type { createForgejoRepoChangeLauncher } from "./launcher.js";
19
17
  import {
20
- type createForgejoRepoChangeLauncher,
21
- forgejoRepoChangeLaunchConfig,
22
- forgejoRepoChangeParams,
23
- } from "./launcher.js";
24
- import {
25
- type ForgejoIssueOriginParams,
26
18
  type ForgejoRepoChangeParams,
27
19
  forgejoRepoChangeParamsCodec,
28
20
  isIssueOrigin,
@@ -36,44 +28,6 @@ const ids = {
36
28
  operator: "ci_operator_action",
37
29
  };
38
30
  const remote = (state: RepositoryChangeState) => readPublicationState(state, "forgejoRepoChange");
39
- function requirePr(state: RepositoryChangeState) {
40
- const value = remote(state);
41
- if (!value.headSha || !value.prNumber || !value.prUrl)
42
- throw new Error("Pull request delivery state is incomplete");
43
- return { ...value, headSha: value.headSha, prNumber: value.prNumber, prUrl: value.prUrl };
44
- }
45
- const feedbackKey = (value: { kind: string; id: number }) => `${value.kind}:${value.id}`;
46
- const callFor =
47
- (ctx: PublicationContext<ForgejoRepoChangeParams>) =>
48
- <T>(name: string, args: Record<string, unknown>) =>
49
- ctx.callIntegrationTool(name, { projectKey: "repo", ...args }) as Promise<T>;
50
- function requireIssueOrigin(
51
- params: ForgejoRepoChangeParams,
52
- ): ForgejoRepoChangeParams & ForgejoIssueOriginParams {
53
- if (!isIssueOrigin(params)) throw new Error("Forgejo source issue metadata is unavailable");
54
- return params;
55
- }
56
-
57
- function pinnedGitIdentity(
58
- ctx: FlowAutomaticRunContext<ForgejoRepoChangeParams, RepositoryChangeState>,
59
- ): ForgejoGitIdentity | null {
60
- const project = ctx.projects.find((candidate) => candidate.key === "repo");
61
- const candidate = object(project?.metadata)?.["leitwerk.gitIdentity"];
62
- const identity = object(candidate);
63
- if (
64
- identity.provider !== "forgejo" ||
65
- identity.profile !== ctx.params.forgejoProfile ||
66
- typeof identity.login !== "string" ||
67
- !identity.login.trim() ||
68
- typeof identity.name !== "string" ||
69
- !identity.name.trim() ||
70
- typeof identity.email !== "string" ||
71
- !identity.email.trim()
72
- ) {
73
- return null;
74
- }
75
- return identity as unknown as ForgejoGitIdentity;
76
- }
77
31
 
78
32
  const deliveryTools = [
79
33
  "forgejo_get_pull_request",
@@ -93,6 +47,14 @@ export function createForgejoRepoChangeProcess(
93
47
  launcher: ReturnType<typeof createForgejoRepoChangeLauncher>,
94
48
  docker: boolean,
95
49
  ) {
50
+ const sharedSources = pullRequestPublicationSources<ForgejoRepoChangeParams>(
51
+ "forgejo",
52
+ "Forgejo",
53
+ forgejoExternal,
54
+ (params) => params.forgejoProfile,
55
+ (params) => (isIssueOrigin(params) ? params : undefined),
56
+ );
57
+ const { requirePr } = sharedSources;
96
58
  const failedPipeline = woodpeckerExternal.pipeline<
97
59
  ForgejoRepoChangeParams,
98
60
  RepositoryChangeState
@@ -129,34 +91,7 @@ export function createForgejoRepoChangeProcess(
129
91
  conflict: object(event).conflict as NonNullable<PublicationState["conflict"]>,
130
92
  }),
131
93
  },
132
- {
133
- id: "forgejo_feedback",
134
- kind: "feedback",
135
- label: "Forgejo pull request feedback",
136
- source: forgejoExternal.pullRequestFeedback(({ params, state }) => ({
137
- profile: params.forgejoProfile,
138
- owner: params.owner,
139
- repo: params.repo,
140
- prNumber: requirePr(state).prNumber,
141
- conversationCursor: remote(state).conversationCursor,
142
- reviewCursor: remote(state).reviewCursor,
143
- inlineCursor: remote(state).inlineCursor,
144
- quietPeriodMs: 120000,
145
- pollInterval: "30s",
146
- })),
147
- read: ({ state, event }) => {
148
- const value = object(event);
149
- const cursors = object(value.cursors);
150
- const current = remote(state);
151
- return {
152
- kind: "feedback",
153
- conversationCursor: Number(cursors.conversationCursor ?? current.conversationCursor),
154
- reviewCursor: Number(cursors.reviewCursor ?? current.reviewCursor),
155
- inlineCursor: Number(cursors.inlineCursor ?? current.inlineCursor),
156
- feedbackIds: (value.feedbackIds ?? []) as PublicationState["feedbackIds"],
157
- };
158
- },
159
- },
94
+ sharedSources.feedback,
160
95
  {
161
96
  id: "woodpecker_failure_repair",
162
97
  operatorId: "woodpecker_failure_operator",
@@ -168,43 +103,8 @@ export function createForgejoRepoChangeProcess(
168
103
  pipeline: object(event).pipeline as NonNullable<PublicationState["pipeline"]>,
169
104
  }),
170
105
  },
171
- ...(["merged", "closed"] as const).map((terminalOutcome) => ({
172
- id: `forgejo_pr_${terminalOutcome}`,
173
- kind: "terminal" as const,
174
- label: `Forgejo pull request ${terminalOutcome}`,
175
- source: forgejoExternal.pullRequestTerminal<ForgejoRepoChangeParams, RepositoryChangeState>(
176
- ({ params, state }) => ({
177
- profile: params.forgejoProfile,
178
- owner: params.owner,
179
- repo: params.repo,
180
- prNumber: requirePr(state).prNumber,
181
- terminalOutcome,
182
- pollInterval: "30s",
183
- }),
184
- ),
185
- read: ({ event }: { event: unknown }) => ({
186
- kind: "terminal" as const,
187
- request: object(event).pullRequest as ForgejoPullRequest,
188
- }),
189
- })),
190
- {
191
- id: "source_cancelled",
192
- kind: "cancelled",
193
- label: "Source issue cancelled",
194
- enabled: isIssueOrigin,
195
- source: forgejoExternal.issueCancelled(({ params }) => {
196
- const issue = requireIssueOrigin(params);
197
- return {
198
- profile: issue.forgejoProfile,
199
- owner: issue.owner,
200
- repo: issue.repo,
201
- issueNumber: issue.issueNumber,
202
- triggerLabel: issue.triggerLabel,
203
- pollInterval: "30s",
204
- };
205
- }),
206
- read: () => ({ kind: "cancelled" }),
207
- },
106
+ ...sharedSources.terminal,
107
+ sharedSources.cancelled,
208
108
  ];
209
109
  const publicationConfig = createRepositoryChangePublication<ForgejoRepoChangeParams>({
210
110
  namespace: "forgejoRepoChange",
@@ -222,108 +122,15 @@ export function createForgejoRepoChangeProcess(
222
122
  "woodpecker_restart_pipeline",
223
123
  ],
224
124
  },
225
- async identity(ctx) {
226
- return (
227
- pinnedGitIdentity(ctx) ??
228
- (await callFor(ctx)<ForgejoGitIdentity>("forgejo_resolve_git_identity", {}))
229
- );
230
- },
231
- async reconcileTerminal(ctx, _current, pr) {
232
- const call = callFor(ctx);
233
- if (isIssueOrigin(ctx.params)) {
234
- const issue = await call<{
235
- labels: Array<{ id: number; name: string }>;
236
- }>("forgejo_get_issue", {
237
- issueNumber: ctx.params.issueNumber,
238
- });
239
- let labels = issue.labels
240
- .filter((label) => label.name !== ctx.params.triggerLabel)
241
- .map((label) => label.id);
242
- if (pr.merged) {
243
- const done = await call<{ id: number }>("forgejo_ensure_label", {
244
- name: ctx.params.doneLabel,
245
- });
246
- labels = [...new Set([...labels, done.id])];
247
- }
248
- await call("forgejo_update_issue", {
249
- issueNumber: ctx.params.issueNumber,
250
- patch: { labels, ...(pr.merged ? { state: "closed" } : {}) },
251
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`,
252
- });
253
- await call("forgejo_add_issue_comment", {
254
- issueNumber: ctx.params.issueNumber,
255
- body: pr.merged
256
- ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.`
257
- : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
258
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`,
259
- });
260
- }
261
- },
262
- async ensureRequest(ctx) {
263
- const call = callFor(ctx);
264
- const project = ctx.repo.get("repo");
265
- const issueOrigin = isIssueOrigin(ctx.params);
266
- const pr = await call<ForgejoPullRequest>("forgejo_ensure_pull_request", {
267
- title:
268
- ctx.process.title ??
269
- (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
270
- body: issueOrigin
271
- ? `Implements ${ctx.params.issueUrl}\n\nLeitwerk process: ${ctx.process.id}`
272
- : `Leitwerk process: ${ctx.process.id}`,
273
- head: project.workBranch,
274
- base: project.baseBranch,
275
- });
276
- if (!pr) throw new Error("Forgejo pull request could not be created or found");
277
- return pr;
278
- },
279
- async linkIssue(ctx, current) {
280
- const call = callFor(ctx);
281
- if (isIssueOrigin(ctx.params)) {
282
- await call("forgejo_add_issue_comment", {
283
- issueNumber: ctx.params.issueNumber,
284
- body: `Leitwerk opened pull request ${current.prUrl}.`,
285
- writeKey: `forgejo:${ctx.process.id}:source-pr-link:${current.prNumber}`,
286
- });
287
- }
288
- },
289
- async reply(ctx, current) {
290
- const call = callFor(ctx);
291
- for (const feedback of current.feedbackIds) {
292
- await call("forgejo_reply_to_pull_request_feedback", {
293
- pullRequestNumber: current.prNumber,
294
- feedbackKind: feedback.kind,
295
- feedbackId: feedback.id,
296
- body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
297
- writeKey: `forgejo:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`,
298
- });
299
- }
300
- },
301
- async acknowledge(ctx, current) {
302
- const call = callFor(ctx);
303
- for (const feedback of current.feedbackIds) {
304
- if (feedback.kind === "review") continue;
305
- await call("forgejo_add_pull_request_feedback_reaction", {
306
- pullRequestNumber: current.prNumber,
307
- feedbackKind: feedback.kind,
308
- feedbackId: feedback.id,
309
- writeKey: `forgejo:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`,
310
- });
311
- }
312
- },
313
- async head(ctx, current) {
314
- return (
315
- await callFor(ctx)<ForgejoPullRequest>("forgejo_get_pull_request", {
316
- pullRequestNumber: current.prNumber,
317
- })
318
- ).head.sha;
319
- },
320
- async afterRebase(ctx, current) {
321
- await callFor(ctx)("forgejo_add_pull_request_comment", {
322
- pullRequestNumber: current.prNumber,
323
- body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
324
- writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`,
325
- });
326
- },
125
+ identity: (ctx) => resolvePullRequestGitIdentity(ctx, "forgejo", ctx.params.forgejoProfile),
126
+ reconcileTerminal: reconcilePullRequestSourceIssue<ForgejoRepoChangeParams>(
127
+ "forgejo",
128
+ "id",
129
+ (params) => (isIssueOrigin(params) ? params : undefined),
130
+ ),
131
+ ...pullRequestPublicationCallbacks<ForgejoRepoChangeParams>("forgejo", "Forgejo", (params) =>
132
+ isIssueOrigin(params) ? params : undefined,
133
+ ),
327
134
  commitMessage: (kind) =>
328
135
  kind === "feedback"
329
136
  ? "fix: address Forgejo review feedback"
@@ -341,28 +148,7 @@ export function createForgejoRepoChangeProcess(
341
148
  description: "Launch a remote repository change for Forgejo issues carrying the trigger label",
342
149
  source: forgejoIssueWatcherSource,
343
150
  preparationChecks: launcher.preparationChecks,
344
- async resolveLaunchConfig({ profile, repository, issue, labels }) {
345
- const issueNumber = issue.number;
346
- const title = issue.title.trim();
347
- const body = issue.body?.trim() ?? "";
348
- const issueUrl = issue.html_url;
349
- const binding = launcher.resolveProfiles(profile);
350
- const gitIdentity = await launcher.resolveGitIdentity(profile);
351
- const params: ForgejoRepoChangeParams = {
352
- ...forgejoRepoChangeParams(repository, {
353
- ...binding,
354
- profile,
355
- workBranch: `leitwerk/issue-${issueNumber}`,
356
- prompt: `${title}${body ? `\n\n${body}` : ""}`,
357
- }),
358
- origin: "issue",
359
- issueNumber,
360
- issueUrl,
361
- triggerLabel: labels.trigger,
362
- doneLabel: labels.done,
363
- };
364
- return forgejoRepoChangeLaunchConfig(params, title, gitIdentity);
365
- },
151
+ resolveLaunchConfig: launcher.launcher.resolveIssueLaunchConfig,
366
152
  });
367
153
 
368
154
  const definition = createRepositoryChangeProcess<ForgejoRepoChangeParams>({
@@ -1,3 +1,5 @@
1
+ import { parseRepositoryProfileBindings } from "@leitwerk-dev/coding/repository-change-launch";
2
+
1
3
  /** Server-owned, non-secret wiring for future launches. @internal */
2
4
  export interface ProfileBinding {
3
5
  /** @internal */
@@ -8,48 +10,12 @@ export interface ProfileBinding {
8
10
  /** @internal */
9
11
  export type ProfileBindings = Readonly<Record<string, Readonly<ProfileBinding>>>;
10
12
 
11
- function record(value: unknown, label: string): Record<string, unknown> {
12
- if (!value || typeof value !== "object" || Array.isArray(value))
13
- throw new Error(`${label} must be an object`);
14
- return value as Record<string, unknown>;
15
- }
16
- function field(value: unknown, fallback: string, label: string): string {
17
- if (value === undefined) return fallback;
18
- if (typeof value !== "string" || !value.trim())
19
- throw new Error(`${label} must be a non-empty string`);
20
- return value.trim();
21
- }
22
13
  /** @internal */
23
14
  export function parseProfileBindings(raw: unknown): ProfileBindings {
24
- const config = raw === undefined ? {} : record(raw, "forgejo-repo-change configuration");
25
- if (config.profile_bindings === undefined) return Object.freeze({});
26
- const mappings = record(config.profile_bindings, "profile_bindings");
27
- const entries = Object.entries(mappings).map(([profile, value]) => {
28
- if (!profile.trim() || profile.trim() !== profile)
29
- throw new Error(
30
- "profile_bindings keys must be non-empty profile names without surrounding whitespace",
31
- );
32
- const mapping = record(value, `profile_bindings.${profile}`);
33
- for (const key of Object.keys(mapping))
34
- if (key !== "woodpecker_profile" && key !== "ssh_credential_ref")
35
- throw new Error(`Unknown profile_bindings.${profile}.${key}`);
36
- return [
37
- profile,
38
- Object.freeze({
39
- woodpeckerProfile: field(
40
- mapping.woodpecker_profile,
41
- profile,
42
- `profile_bindings.${profile}.woodpecker_profile`,
43
- ),
44
- sshCredentialRef: field(
45
- mapping.ssh_credential_ref,
46
- profile,
47
- `profile_bindings.${profile}.ssh_credential_ref`,
48
- ),
49
- }),
50
- ];
15
+ return parseRepositoryProfileBindings(raw, "forgejo-repo-change", {
16
+ woodpeckerProfile: "woodpecker_profile",
17
+ sshCredentialRef: "ssh_credential_ref",
51
18
  });
52
- return Object.freeze(Object.fromEntries(entries));
53
19
  }
54
20
  /** @internal */
55
21
  export function resolveProfileBinding(bindings: ProfileBindings, profile: string): ProfileBinding {