@leitwerk-dev/gitlab 0.3.0 → 0.4.0

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.
Files changed (56) hide show
  1. package/README.md +154 -1
  2. package/dist/capability.d.ts +3 -0
  3. package/dist/capability.d.ts.map +1 -1
  4. package/dist/chunk-YPCOVBQS.js +2343 -0
  5. package/dist/chunk-YPCOVBQS.js.map +1 -0
  6. package/dist/client.d.ts +99 -7
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/external.d.ts +24 -4
  9. package/dist/external.d.ts.map +1 -1
  10. package/dist/index.d.ts +8 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +512 -10
  13. package/dist/index.js.map +1 -1
  14. package/dist/issue-watcher.d.ts +2 -2
  15. package/dist/issue-watcher.d.ts.map +1 -1
  16. package/dist/launch.d.ts +40 -0
  17. package/dist/launch.d.ts.map +1 -0
  18. package/dist/maintenance-labels.d.ts +30 -0
  19. package/dist/maintenance-labels.d.ts.map +1 -0
  20. package/dist/maintenance.d.ts +132 -0
  21. package/dist/maintenance.d.ts.map +1 -0
  22. package/dist/publication-maintenance.d.ts +7 -0
  23. package/dist/publication-maintenance.d.ts.map +1 -0
  24. package/dist/publication.d.ts +37 -0
  25. package/dist/publication.d.ts.map +1 -0
  26. package/dist/repository-catalog.d.ts +16 -0
  27. package/dist/repository-catalog.d.ts.map +1 -0
  28. package/dist/setup.d.ts +8 -2
  29. package/dist/setup.d.ts.map +1 -1
  30. package/dist/testing.d.ts +10 -1
  31. package/dist/testing.d.ts.map +1 -1
  32. package/dist/testing.js +125 -5
  33. package/dist/testing.js.map +1 -1
  34. package/dist/ticket-creation.d.ts +5 -0
  35. package/dist/ticket-creation.d.ts.map +1 -0
  36. package/dist/tools.d.ts +100 -3
  37. package/dist/tools.d.ts.map +1 -1
  38. package/package.json +7 -7
  39. package/src/capability.ts +3 -0
  40. package/src/client.ts +275 -12
  41. package/src/delivery-tools.ts +4 -4
  42. package/src/external.ts +91 -24
  43. package/src/index.ts +58 -10
  44. package/src/issue-watcher.ts +16 -14
  45. package/src/launch.ts +63 -0
  46. package/src/maintenance-labels.ts +129 -0
  47. package/src/maintenance.ts +759 -0
  48. package/src/publication-maintenance.ts +288 -0
  49. package/src/publication.ts +234 -0
  50. package/src/repository-catalog.ts +94 -0
  51. package/src/setup.ts +115 -6
  52. package/src/testing.ts +143 -4
  53. package/src/ticket-creation.ts +145 -0
  54. package/src/tools.ts +382 -26
  55. package/dist/chunk-H4JCQNDY.js +0 -1162
  56. package/dist/chunk-H4JCQNDY.js.map +0 -1
package/src/external.ts CHANGED
@@ -1,84 +1,118 @@
1
+ import { type ConflictEvidence, conflictKey } from "@leitwerk-dev/coding/repository-rebase";
1
2
  import {
2
3
  type CoreServerSetupDeps,
3
4
  createExternalSourcePollReporter,
4
5
  type ExternalActionSource,
5
6
  type ExternalSourceArmingLike,
6
7
  } from "@leitwerk-dev/process-sdk";
7
- import { type ConflictEvidence, conflictKey } from "@leitwerk-dev/repository-rebase";
8
8
  import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
9
9
  import type { GitLabIntegration } from "./capability.js";
10
10
  import { type GitLabFeedback, type GitLabObservation, observeMergeRequest } from "./client.js";
11
11
  import { createGitLabIssueDiscovery } from "./issue-watcher.js";
12
+
12
13
  /** @public */
13
14
  export interface GitLabDeliveryObservation extends GitLabObservation {
15
+ /** @public */
16
+ projectKey?: string;
17
+ /** Target ancestry suppresses stale conflict/rebase reports after publication. @public */
18
+ targetIntegrated?: boolean;
19
+
14
20
  /** @public */
15
21
  observationKey?: string;
22
+
16
23
  /** @public */
17
24
  feedback?: GitLabFeedback[];
25
+
18
26
  /** @public */
19
27
  conflict?: ConflictEvidence;
20
28
  }
29
+
21
30
  /** @public */
22
31
  export const GITLAB_ISSUE_CANCELLED_KIND = "@leitwerk-dev/gitlab.issue-cancelled";
32
+
23
33
  /** @public */
24
34
  export interface GitLabIssueCancelledConfig {
35
+ /** Pinned provider installation. @public */
36
+ origin?: string;
25
37
  /** @public */
26
38
  profile: string;
39
+
27
40
  /** @public */
28
41
  projectId: number;
42
+
29
43
  /** @public */
30
44
  issueIid: number;
45
+
31
46
  /** @public */
32
47
  iid: number;
48
+
33
49
  /** @public */
34
50
  triggerLabel: string;
51
+
35
52
  /** @public */
36
53
  pollInterval?: string;
37
54
  }
55
+
38
56
  /** @internal */
39
57
  export const GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
58
+
40
59
  /** @public */
41
60
  export interface GitLabSourceConfig {
61
+ /** Pinned provider installation. @public */
62
+ origin?: string;
42
63
  /** @public */
43
64
  profile: string;
65
+
44
66
  /** @public */
45
67
  projectId: number;
68
+
46
69
  /** @public */
47
70
  iid: number;
71
+
48
72
  /** @public */
49
73
  pollInterval?: string;
74
+
50
75
  /** @public */
51
76
  afterKey?: string;
52
77
  /** Optional timer also wakes retry work when GitLab facts have not changed. */
78
+
53
79
  /** @public */
54
80
  wakeAt?: number;
81
+
55
82
  /** @public */
56
83
  delivery?: {
57
84
  /** @public */
58
85
  headSha: string;
86
+
59
87
  /** @public */
60
88
  owner: string;
89
+
61
90
  /** @public */
62
91
  repo: string;
92
+
63
93
  /** @public */
64
94
  headBranch: string;
95
+
65
96
  /** @public */
66
97
  baseBranch: string;
98
+
67
99
  /** @public */
68
100
  lastConflictKey?: string | null;
69
101
  };
70
102
  /** @public */
71
- /** @public */
72
103
  feedback?: {
73
104
  /** @public */
74
105
  afterId: number;
106
+
75
107
  /** @public */
76
108
  since?: string;
109
+
77
110
  /** @public */
78
111
  quietPeriodMs: number;
79
112
  };
80
113
  }
81
114
  /** A trailing quiet period survives restarts because it uses the newest unseen note's timestamp. */
115
+
82
116
  /** @public */
83
117
  export function pendingGitLabFeedback(
84
118
  items: GitLabFeedback[],
@@ -88,6 +122,7 @@ export function pendingGitLabFeedback(
88
122
  const start = since ? Date.parse(since) : 0;
89
123
  return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
90
124
  }
125
+
91
126
  /** @public */
92
127
  export function gitLabFeedbackReadyAt(
93
128
  items: GitLabFeedback[],
@@ -97,6 +132,7 @@ export function gitLabFeedbackReadyAt(
97
132
  ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs
98
133
  : null;
99
134
  }
135
+
100
136
  /** @public */
101
137
  export const observationKey = ({ mr, pipeline, targetHead }: GitLabObservation): string =>
102
138
  JSON.stringify([
@@ -115,15 +151,40 @@ export const observationKey = ({ mr, pipeline, targetHead }: GitLabObservation):
115
151
  mr.merge_status,
116
152
  mr.detailed_merge_status,
117
153
  ]);
154
+
118
155
  /** @public */
119
156
  export const gitlabExternal = {
157
+ /** Observe coordinated repositories with the same revision and feedback policy. @public */
158
+ mergeRequests<P, S>(
159
+ resolve: (ctx: {
160
+ /** @internal */
161
+ params: P;
162
+ /** @internal */
163
+ state: S;
164
+ }) => {
165
+ /** @internal */
166
+ repositories: (GitLabSourceConfig & {
167
+ /** @internal */
168
+ projectKey: string;
169
+ })[];
170
+ },
171
+ ): ExternalActionSource<P, S, GitLabDeliveryObservation> {
172
+ return {
173
+ kind: GITLAB_MR_KIND,
174
+ label: "GitLab merge requests",
175
+ config: {},
176
+ inputMode: "none",
177
+ resolve,
178
+ };
179
+ },
180
+
120
181
  /** @public */
121
182
  issueCancelled<P, S>(
122
- /** @public */
123
183
  /** @public */
124
184
  resolve: (ctx: {
125
185
  /** @public */
126
186
  params: P;
187
+
127
188
  /** @public */
128
189
  state: S;
129
190
  }) => GitLabIssueCancelledConfig,
@@ -136,13 +197,14 @@ export const gitlabExternal = {
136
197
  resolve,
137
198
  };
138
199
  },
200
+
139
201
  /** @public */
140
202
  mergeRequest<P, S>(
141
- /** @public */
142
203
  /** @public */
143
204
  resolve: (ctx: {
144
205
  /** @public */
145
206
  params: P;
207
+
146
208
  /** @public */
147
209
  state: S;
148
210
  }) => GitLabSourceConfig,
@@ -157,14 +219,15 @@ export const gitlabExternal = {
157
219
  };
158
220
  },
159
221
  };
222
+
160
223
  /** @internal */
161
224
  export function createGitLabProvider(
162
225
  deps: CoreServerSetupDeps,
163
226
  integration: GitLabIntegration,
164
227
  /** @public */
165
- /** @public */
166
228
  options: {
167
- /** @internal */ now?: () => number;
229
+ /** @internal */
230
+ now?: () => number;
168
231
  } = {},
169
232
  ) {
170
233
  const schedule = new Map<string, { at: number; failures: number }>();
@@ -182,24 +245,14 @@ export function createGitLabProvider(
182
245
  } catch (error) {
183
246
  result.errors.push(error instanceof Error ? error.message : "GitLab discovery failed");
184
247
  }
185
- const reporter = createExternalSourcePollReporter(deps.externalSources, result, {
248
+ const report = createExternalSourcePollReporter(deps.externalSources, result, {
186
249
  forwardGeneration: true,
250
+ currentKinds: [GITLAB_MR_KIND, GITLAB_ISSUE_CANCELLED_KIND],
187
251
  });
188
- const current = (armed: ExternalSourceArmingLike) =>
189
- [GITLAB_MR_KIND, GITLAB_ISSUE_CANCELLED_KIND].some((kind) =>
190
- reporter.isCurrent(kind, armed),
191
- );
192
- const report = {
193
- ...reporter,
194
- fire(armed: ExternalSourceArmingLike, event: Record<string, unknown>, mergeKey: string) {
195
- return current(armed) ? reporter.fire(armed, event, mergeKey) : Promise.resolve(false);
196
- },
197
- observe(armed: ExternalSourceArmingLike, input: Parameters<typeof reporter.observe>[1]) {
198
- if (current(armed)) return reporter.observe(armed, input);
199
- },
200
- };
201
- await report.poll(GITLAB_MR_KIND, async (armed) => {
202
- const c = armed.resolved as unknown as GitLabSourceConfig;
252
+ const pollRepository = async (
253
+ armed: ExternalSourceArmingLike,
254
+ c: GitLabSourceConfig & { projectKey?: string },
255
+ ) => {
203
256
  if (
204
257
  !c ||
205
258
  typeof c.profile !== "string" ||
@@ -207,10 +260,12 @@ export function createGitLabProvider(
207
260
  !Number.isInteger(c.iid)
208
261
  )
209
262
  throw new Error("Invalid GitLab external source");
210
- const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
263
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}:${c.projectKey ?? ""}`;
211
264
  const previous = schedule.get(key);
212
265
  if (previous && previous.at > now()) return;
213
266
  try {
267
+ if (c.origin && integration.client(c.profile).baseUrl !== c.origin)
268
+ throw new Error("GitLab observation installation changed");
214
269
  const observation = await observeMergeRequest(
215
270
  integration.client(c.profile),
216
271
  c.projectId,
@@ -284,6 +339,7 @@ export function createGitLabProvider(
284
339
  armed,
285
340
  {
286
341
  ...observation,
342
+ ...(c.projectKey ? { projectKey: c.projectKey } : {}),
287
343
  ...(c.delivery
288
344
  ? {
289
345
  observationKey: observedKey,
@@ -292,7 +348,7 @@ export function createGitLabProvider(
292
348
  }
293
349
  : {}),
294
350
  },
295
- `${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`,
351
+ `${c.projectKey ?? ""}:${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`,
296
352
  );
297
353
  schedule.set(key, {
298
354
  at: now() + parseDurationMs(c.pollInterval ?? "30s", 30000),
@@ -309,12 +365,23 @@ export function createGitLabProvider(
309
365
  });
310
366
  throw error;
311
367
  }
368
+ };
369
+ await report.poll(GITLAB_MR_KIND, async (armed) => {
370
+ const config = armed.resolved as unknown as GitLabSourceConfig & {
371
+ repositories?: (GitLabSourceConfig & { projectKey: string })[];
372
+ };
373
+ for (const source of config.repositories ?? [config]) {
374
+ if (!report.isCurrent(GITLAB_MR_KIND, armed)) break;
375
+ await pollRepository(armed, source);
376
+ }
312
377
  });
313
378
  await report.poll(GITLAB_ISSUE_CANCELLED_KIND, async (armed) => {
314
379
  const c = armed.resolved as unknown as GitLabIssueCancelledConfig;
315
380
  const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
316
381
  if ((schedule.get(key)?.at ?? 0) > now()) return;
317
382
  const client = integration.client(c.profile);
383
+ if (c.origin && client.baseUrl !== c.origin)
384
+ throw new Error("GitLab source issue installation changed");
318
385
  const issue = await client.getIssue(c.projectId, c.issueIid);
319
386
  if (issue.state !== "opened" || !issue.labels.includes(c.triggerLabel)) {
320
387
  const mr = await client.getMergeRequest(c.projectId, c.iid);
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
2
- import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
2
+ import { coreHostCapabilities, parseTicketCreationConfig } from "@leitwerk-dev/process-sdk";
3
3
  import { GitLabClient, parseGitLabProfiles } from "./client.js";
4
4
  import { setupGitLabIntegration } from "./setup.js";
5
5
 
@@ -16,14 +16,18 @@ const extension: LeitwerkExtensionModule = {
16
16
  setupServer(api, config) {
17
17
  const profiles = parseGitLabProfiles(config);
18
18
  const clients = new Map([...profiles].map(([id, profile]) => [id, new GitLabClient(profile)]));
19
- setupGitLabIntegration(api, {
20
- profiles: () => [...profiles.keys()],
21
- client: (profile) => {
22
- const client = clients.get(profile);
23
- if (!client) throw new Error(`Unknown GitLab profile '${profile}'`);
24
- return client;
19
+ setupGitLabIntegration(
20
+ api,
21
+ {
22
+ profiles: () => [...profiles.keys()],
23
+ client: (profile) => {
24
+ const client = clients.get(profile);
25
+ if (!client) throw new Error(`Unknown GitLab profile '${profile}'`);
26
+ return client;
27
+ },
25
28
  },
26
- });
29
+ { ticketCreation: parseTicketCreationConfig(config, "GitLab") },
30
+ );
27
31
  const deps = api.get(coreHostCapabilities.serverSetup);
28
32
  if (!deps || Array.isArray(deps)) return;
29
33
  deps.repositoryCredentials.register({
@@ -44,15 +48,17 @@ export {
44
48
  gitlabRepositoryCredentials,
45
49
  } from "./capability.js";
46
50
  export type {
51
+ GitLabClientLike,
47
52
  GitLabDiff,
48
53
  GitLabFeedback,
49
54
  GitLabIdentity,
50
55
  GitLabJob,
56
+ GitLabLabelEvent,
51
57
  GitLabMergeRequest,
52
58
  GitLabObservation,
53
59
  GitLabProject,
54
60
  } from "./client.js";
55
- export { observeMergeRequest } from "./client.js";
61
+ export { GitLabError, observeMergeRequest } from "./client.js";
56
62
  export type { GitLabDeliveryObservation } from "./external.js";
57
63
  export {
58
64
  gitLabFeedbackReadyAt,
@@ -62,9 +68,51 @@ export {
62
68
  } from "./external.js";
63
69
  export type { GitLabIssueWatcherEvent } from "./issue-watcher.js";
64
70
  export { gitlabIssueExternalId, gitlabIssueWatcherSource } from "./issue-watcher.js";
71
+ export { resolveGitLabLaunchProject } from "./launch.js";
72
+ export {
73
+ GITLAB_MAINTAINED_KIND,
74
+ type GitLabMaintainedBinding,
75
+ type GitLabMaintainedProcess,
76
+ type GitLabMaintenance,
77
+ type GitLabMaintenanceContext,
78
+ type GitLabMaintenanceDecision,
79
+ type GitLabMaintenanceDestinations,
80
+ type GitLabMaintenanceEvent,
81
+ type GitLabMaintenanceMessage,
82
+ type GitLabMaintenanceRecord,
83
+ type GitLabMaintenanceRetry,
84
+ type GitLabMaintenanceSettings,
85
+ gitlabMaintenance,
86
+ gitlabMaintenanceSource,
87
+ registerGitLabMaintainedProcess,
88
+ } from "./maintenance.js";
89
+ export {
90
+ GITLAB_ACTIVE_LABEL,
91
+ GITLAB_DONE_LABEL,
92
+ type GitLabLabelState,
93
+ gitLabActivationStatus,
94
+ readGitLabLabels,
95
+ } from "./maintenance-labels.js";
96
+ export {
97
+ createGitLabPublicationAdapter,
98
+ type GitLabPublicationParams,
99
+ gitlabPublicationEvidenceForRequest,
100
+ gitlabPublicationRequest,
101
+ gitlabPublicationSource,
102
+ } from "./publication.js";
103
+ export {
104
+ createGitLabRepositoryCatalog,
105
+ type GitLabRepositoryCatalog,
106
+ } from "./repository-catalog.js";
65
107
  export type { GitLabSelection } from "./selection.js";
66
108
  export {
67
109
  parseGitLabSelection,
68
110
  selectGitLabProjects,
69
111
  } from "./selection.js";
70
- export { ensureGitLabSeenReaction, resolveGitLabBinding } from "./tools.js";
112
+ export {
113
+ ensureGitLabComment,
114
+ ensureGitLabSeenReaction,
115
+ gitLabCommentMarker,
116
+ resolveGitLabBinding,
117
+ resolveGitLabRepositoryBinding,
118
+ } from "./tools.js";
@@ -12,10 +12,10 @@ import { type GitLabSelection, parseGitLabSelection, selectGitLabProjects } from
12
12
  export interface GitLabIssueWatcherConfig extends GitLabSelection {
13
13
  /** @public */
14
14
  profile: string;
15
+ /** @public */ gitSshProfile?: string;
15
16
  /** @public */
16
17
  pollInterval: string;
17
18
  /** @public */
18
- /** @public */
19
19
  labels: {
20
20
  /** @public */ trigger: string /** @public */;
21
21
  /** @public */
@@ -26,12 +26,12 @@ export interface GitLabIssueWatcherConfig extends GitLabSelection {
26
26
  export interface GitLabIssueWatcherEvent {
27
27
  /** @public */
28
28
  profile: string;
29
+ /** @public */ gitSshProfile?: string;
29
30
  /** @public */
30
31
  repository: GitLabProject;
31
32
  /** @public */
32
33
  issue: GitLabIssue;
33
34
  /** @public */
34
- /** @public */
35
35
  labels: {
36
36
  /** @public */ trigger: string /** @public */;
37
37
  /** @public */
@@ -68,6 +68,7 @@ export const gitlabIssueWatcherSource = defineProcessWatcherSource<
68
68
  config: {
69
69
  ...parseGitLabSelection(c),
70
70
  profile: text(c.profile, "profile"),
71
+ ...(typeof c.git_ssh_profile === "string" ? { gitSshProfile: c.git_ssh_profile } : {}),
71
72
  pollInterval,
72
73
  labels: { trigger, done },
73
74
  },
@@ -96,17 +97,16 @@ export function createGitLabIssueDiscovery(
96
97
  if (!watcher.enabled) continue;
97
98
  const key = `${watcher.processId}:${watcher.watcherId}`;
98
99
  const c = watcher.config;
100
+ const eligible = (issue: GitLabIssue) =>
101
+ issue.state === "opened" &&
102
+ issue.labels.includes(c.labels.trigger) &&
103
+ !issue.labels.includes(c.labels.done);
99
104
  if ((due.get(key) ?? 0) > now()) continue;
100
105
  due.set(key, now() + parseDurationMs(c.pollInterval, 30000));
101
106
  const client = integration.client(c.profile);
102
107
  for (const repository of await selectGitLabProjects(client, c))
103
108
  for (const issue of await client.listIssues(repository.id)) {
104
- if (
105
- issue.state !== "opened" ||
106
- !issue.labels.includes(c.labels.trigger) ||
107
- issue.labels.includes(c.labels.done)
108
- )
109
- continue;
109
+ if (!eligible(issue)) continue;
110
110
  const id = gitlabIssueExternalId(client.baseUrl, repository.id, issue.iid);
111
111
  if (deps.processes.listAll().some((p) => p.externalId === id)) {
112
112
  result.skipped.push(id);
@@ -126,11 +126,7 @@ export function createGitLabIssueDiscovery(
126
126
  label: "Recheck GitLab source issue",
127
127
  async run() {
128
128
  const fresh = await client.getIssue(repository.id, issue.iid);
129
- if (
130
- fresh.state !== "opened" ||
131
- !fresh.labels.includes(c.labels.trigger) ||
132
- fresh.labels.includes(c.labels.done)
133
- )
129
+ if (!eligible(fresh))
134
130
  throw new Error("GitLab source issue eligibility changed before launch");
135
131
  },
136
132
  },
@@ -140,7 +136,13 @@ export function createGitLabIssueDiscovery(
140
136
  };
141
137
  const launched = await deps.launchRuns.startWatcher(
142
138
  guarded,
143
- { profile: c.profile, repository, issue, labels: c.labels },
139
+ {
140
+ profile: c.profile,
141
+ gitSshProfile: c.gitSshProfile,
142
+ repository,
143
+ issue,
144
+ labels: c.labels,
145
+ },
144
146
  { idempotencyKey: id },
145
147
  );
146
148
  if (launched.error) result.errors.push(`${id}:launch_failed`);
package/src/launch.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
2
+ import type { GitLabClientLike, GitLabProject } from "./client.js";
3
+
4
+ /** Resolve the shared checkout, provider binding and pinned Git identity. @internal */
5
+ export async function resolveGitLabLaunchProject(
6
+ client: GitLabClientLike,
7
+ profile: string,
8
+ repository: GitLabProject,
9
+ workBranch: string,
10
+ key = "repo",
11
+ transport: "ssh" | "https" = "ssh",
12
+ ) {
13
+ const repoLocator =
14
+ transport === "ssh" ? repository.ssh_url_to_repo : repository.http_url_to_repo;
15
+ if (!repoLocator)
16
+ throw new Error(`GitLab repository has no ${transport.toUpperCase()} clone URL`);
17
+ if (transport === "https" && repositoryHttpsUrl(repoLocator).origin !== client.baseUrl)
18
+ throw new Error("GitLab repository origin does not match its profile");
19
+ const split = repository.path_with_namespace.lastIndexOf("/");
20
+ if (split < 1) throw new Error("Invalid GitLab project path");
21
+ const params = {
22
+ /** @internal */ gitlabProfile: profile,
23
+ /** @internal */ gitlabOrigin: client.baseUrl,
24
+ /** @internal */ projectId: repository.id,
25
+ /** @internal */ owner: repository.path_with_namespace.slice(0, split),
26
+ /** @internal */ repo: repository.path_with_namespace.slice(split + 1),
27
+ /** @internal */ repoLocator,
28
+ /** @internal */ baseBranch: repository.default_branch,
29
+ /** @internal */ workBranch,
30
+ };
31
+ const identity = await client.resolveGitIdentity();
32
+ return {
33
+ /** @internal */ params,
34
+ /** @internal */ project: {
35
+ /** @internal */ key,
36
+ /** @internal */ repoLocator: params.repoLocator,
37
+ /** @internal */ baseBranch: params.baseBranch,
38
+ /** @internal */ workBranch,
39
+ /** @internal */ settingsRepository: {
40
+ /** @internal */ origin: client.baseUrl,
41
+ /** @internal */ repositoryId: repository.id,
42
+ /** @internal */ aliases: [
43
+ repository.http_url_to_repo,
44
+ ...(repository.ssh_url_to_repo ? [repository.ssh_url_to_repo] : []),
45
+ ],
46
+ },
47
+ /** @internal */ metadata: {
48
+ /** @internal */ gitlab: {
49
+ /** @internal */ origin: client.baseUrl,
50
+ /** @internal */ profile,
51
+ /** @internal */ projectId: repository.id,
52
+ },
53
+ /** @internal */ "leitwerk.gitIdentity": {
54
+ /** @internal */ provider: "gitlab",
55
+ /** @internal */ profile,
56
+ /** @internal */ login: identity.username,
57
+ /** @internal */ name: identity.name,
58
+ /** @internal */ email: identity.email,
59
+ },
60
+ },
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,129 @@
1
+ import type { ExternalWrites } from "@leitwerk-dev/external-writes";
2
+ import {
3
+ type GitLabClientLike,
4
+ GitLabError,
5
+ type GitLabLabelEvent,
6
+ type GitLabMergeRequest,
7
+ } from "./client.js";
8
+
9
+ /** @public */
10
+ export const GITLAB_ACTIVE_LABEL = "leitwerk-active";
11
+ /** @public */
12
+ export const GITLAB_DONE_LABEL = "leitwerk-done";
13
+ /** @public */
14
+ export interface GitLabLabelState {
15
+ /** @public */ mr: GitLabMergeRequest;
16
+ /** @public */ events: GitLabLabelEvent[];
17
+ }
18
+ /** Read transitions before the current labels so remove/re-add cannot hide cancellation. @public */
19
+ export async function readGitLabLabels(
20
+ client: GitLabClientLike,
21
+ projectId: number,
22
+ iid: number,
23
+ signal?: AbortSignal,
24
+ ): Promise<GitLabLabelState> {
25
+ const events = await client.listMergeRequestLabelEvents(projectId, iid, signal);
26
+ const mr = await client.getMergeRequest(projectId, iid, signal);
27
+ return { mr, events: events.sort((a, b) => a.id - b.id) };
28
+ }
29
+ /** A missing label endpoint alone does not establish deletion; project access must still work. @internal */
30
+ export async function readMaintainedGitLabLabels(
31
+ client: GitLabClientLike,
32
+ projectId: number,
33
+ iid: number,
34
+ signal?: AbortSignal,
35
+ ): Promise<GitLabLabelState | null> {
36
+ try {
37
+ return await readGitLabLabels(client, projectId, iid, signal);
38
+ } catch (error) {
39
+ if (!(error instanceof GitLabError) || error.status !== 404) throw error;
40
+ try {
41
+ await client.getMergeRequest(projectId, iid, signal);
42
+ } catch (mrError) {
43
+ if (!(mrError instanceof GitLabError) || mrError.status !== 404) throw mrError;
44
+ await client.getProject(projectId, signal);
45
+ return null;
46
+ }
47
+ throw error;
48
+ }
49
+ }
50
+ /** @public */
51
+ export function gitLabActivationStatus(
52
+ after: number,
53
+ labels: GitLabLabelState,
54
+ ): "pending" | "active" | "removed" {
55
+ const events = labels.events.filter(
56
+ (event) => event.label?.name === GITLAB_ACTIVE_LABEL && event.id > after,
57
+ );
58
+ if (events.some((event) => event.action === "remove")) return "removed";
59
+ if (!events.length) return "pending";
60
+ return labels.mr.labels.includes(GITLAB_ACTIVE_LABEL) ? "active" : "removed";
61
+ }
62
+ /** All label updates preserve unrelated labels and reconcile uncertain writes. @internal */
63
+ export async function ensureGitLabMaintenanceLabels(input: {
64
+ client: GitLabClientLike;
65
+ writes: ExternalWrites;
66
+ projectId: number;
67
+ iid: number;
68
+ writeKey: string;
69
+ after: number;
70
+ status: "active" | "merged" | "closed" | "stopped";
71
+ guard(): Promise<boolean>;
72
+ signal?: AbortSignal;
73
+ }): Promise<void> {
74
+ const { client, writes, projectId, iid, status, after, signal } = input;
75
+ const settled = async () => {
76
+ const labels = await readGitLabLabels(client, projectId, iid, signal);
77
+ if (!(await input.guard())) throw new Error("GitLab label write superseded");
78
+ if (status === "active")
79
+ return (
80
+ labels.mr.state !== "opened" ||
81
+ gitLabActivationStatus(after, labels) === "removed" ||
82
+ (labels.mr.labels.includes(GITLAB_ACTIVE_LABEL) &&
83
+ !labels.mr.labels.includes(GITLAB_DONE_LABEL))
84
+ );
85
+ // An operator's newer activation belongs to a future process.
86
+ const active = labels.events.filter(
87
+ (event) => event.label?.name === GITLAB_ACTIVE_LABEL && event.id > after,
88
+ );
89
+ if (
90
+ active.some(
91
+ (event, index) =>
92
+ event.action === "add" &&
93
+ active.slice(0, index).some((before) => before.action === "remove"),
94
+ )
95
+ )
96
+ return true;
97
+ return (
98
+ !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL) &&
99
+ (status !== "merged" ||
100
+ labels.mr.labels.includes(GITLAB_DONE_LABEL) ||
101
+ labels.events.some(
102
+ (event) =>
103
+ event.id > after && event.label?.name === GITLAB_DONE_LABEL && event.action === "add",
104
+ ))
105
+ );
106
+ };
107
+ await writes.ensure(
108
+ { writeType: "gitlab.mr_labels", dedupKey: input.writeKey },
109
+ {
110
+ reconcile: async (phase) => (phase === "already_recorded" || (await settled()) ? true : null),
111
+ execute: async () => {
112
+ if (await settled()) return true;
113
+ await client.updateMergeRequestLabels(
114
+ projectId,
115
+ iid,
116
+ status === "active"
117
+ ? { add_labels: GITLAB_ACTIVE_LABEL, remove_labels: GITLAB_DONE_LABEL }
118
+ : {
119
+ ...(status === "merged" ? { add_labels: GITLAB_DONE_LABEL } : {}),
120
+ remove_labels: GITLAB_ACTIVE_LABEL,
121
+ },
122
+ signal,
123
+ );
124
+ return true;
125
+ },
126
+ toMetadata: () => ({ projectId, iid, status }),
127
+ },
128
+ );
129
+ }