@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.
- package/README.md +154 -1
- package/dist/capability.d.ts +3 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/chunk-YPCOVBQS.js +2343 -0
- package/dist/chunk-YPCOVBQS.js.map +1 -0
- package/dist/client.d.ts +99 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/external.d.ts +24 -4
- package/dist/external.d.ts.map +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +512 -10
- package/dist/index.js.map +1 -1
- package/dist/issue-watcher.d.ts +2 -2
- package/dist/issue-watcher.d.ts.map +1 -1
- package/dist/launch.d.ts +40 -0
- package/dist/launch.d.ts.map +1 -0
- package/dist/maintenance-labels.d.ts +30 -0
- package/dist/maintenance-labels.d.ts.map +1 -0
- package/dist/maintenance.d.ts +132 -0
- package/dist/maintenance.d.ts.map +1 -0
- package/dist/publication-maintenance.d.ts +7 -0
- package/dist/publication-maintenance.d.ts.map +1 -0
- package/dist/publication.d.ts +37 -0
- package/dist/publication.d.ts.map +1 -0
- package/dist/repository-catalog.d.ts +16 -0
- package/dist/repository-catalog.d.ts.map +1 -0
- package/dist/setup.d.ts +8 -2
- package/dist/setup.d.ts.map +1 -1
- package/dist/testing.d.ts +10 -1
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +125 -5
- package/dist/testing.js.map +1 -1
- package/dist/ticket-creation.d.ts +5 -0
- package/dist/ticket-creation.d.ts.map +1 -0
- package/dist/tools.d.ts +100 -3
- package/dist/tools.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/capability.ts +3 -0
- package/src/client.ts +275 -12
- package/src/delivery-tools.ts +4 -4
- package/src/external.ts +91 -24
- package/src/index.ts +58 -10
- package/src/issue-watcher.ts +16 -14
- package/src/launch.ts +63 -0
- package/src/maintenance-labels.ts +129 -0
- package/src/maintenance.ts +759 -0
- package/src/publication-maintenance.ts +288 -0
- package/src/publication.ts +234 -0
- package/src/repository-catalog.ts +94 -0
- package/src/setup.ts +115 -6
- package/src/testing.ts +143 -4
- package/src/ticket-creation.ts +145 -0
- package/src/tools.ts +382 -26
- package/dist/chunk-H4JCQNDY.js +0 -1162
- package/dist/chunk-H4JCQNDY.js.map +0 -1
package/dist/chunk-H4JCQNDY.js
DELETED
|
@@ -1,1162 +0,0 @@
|
|
|
1
|
-
// src/client.ts
|
|
2
|
-
import { asUnknownRecord } from "@leitwerk-dev/domain";
|
|
3
|
-
import { repositoryHttpsUrl as repositoryHttpsUrl2 } from "@leitwerk-dev/process-sdk";
|
|
4
|
-
|
|
5
|
-
// src/preflight.ts
|
|
6
|
-
import { execFile } from "child_process";
|
|
7
|
-
import { mkdtemp, rm, writeFile } from "fs/promises";
|
|
8
|
-
import { tmpdir } from "os";
|
|
9
|
-
import { join } from "path";
|
|
10
|
-
import { promisify } from "util";
|
|
11
|
-
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
12
|
-
var exec = promisify(execFile);
|
|
13
|
-
async function preflightGitLabRepository(input) {
|
|
14
|
-
const url = repositoryHttpsUrl(input.url);
|
|
15
|
-
if (url.origin !== input.origin)
|
|
16
|
-
throw new Error("GitLab repository origin does not match its profile");
|
|
17
|
-
const directory = await mkdtemp(join(tmpdir(), "leitwerk-gitlab-preflight-"));
|
|
18
|
-
try {
|
|
19
|
-
const askpass = join(directory, "askpass");
|
|
20
|
-
await writeFile(
|
|
21
|
-
askpass,
|
|
22
|
-
'#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" oauth2;; *) printf "%s\\n" "$LEITWERK_GITLAB_PREFLIGHT_TOKEN";; esac\n',
|
|
23
|
-
{ mode: 448 }
|
|
24
|
-
);
|
|
25
|
-
const env = {
|
|
26
|
-
...process.env,
|
|
27
|
-
GIT_CONFIG_NOSYSTEM: "1",
|
|
28
|
-
GIT_CONFIG_GLOBAL: "/dev/null",
|
|
29
|
-
GIT_TERMINAL_PROMPT: "0",
|
|
30
|
-
GIT_ASKPASS: askpass,
|
|
31
|
-
LEITWERK_GITLAB_PREFLIGHT_TOKEN: input.token
|
|
32
|
-
};
|
|
33
|
-
const git = (args) => exec("git", ["-c", "credential.helper=", "-c", "http.followRedirects=false", ...args], {
|
|
34
|
-
env,
|
|
35
|
-
signal: input.signal
|
|
36
|
-
});
|
|
37
|
-
await git(["check-ref-format", `refs/heads/${input.baseBranch}`]);
|
|
38
|
-
await git(["check-ref-format", `refs/heads/${input.workBranch}`]);
|
|
39
|
-
await git(["ls-remote", "--exit-code", input.url, `refs/heads/${input.baseBranch}`]);
|
|
40
|
-
await git(["init", "--quiet", directory]);
|
|
41
|
-
await git([
|
|
42
|
-
"-C",
|
|
43
|
-
directory,
|
|
44
|
-
"fetch",
|
|
45
|
-
"--quiet",
|
|
46
|
-
"--depth=1",
|
|
47
|
-
input.url,
|
|
48
|
-
`refs/heads/${input.baseBranch}`
|
|
49
|
-
]);
|
|
50
|
-
await git([
|
|
51
|
-
"-C",
|
|
52
|
-
directory,
|
|
53
|
-
"push",
|
|
54
|
-
"--dry-run",
|
|
55
|
-
input.url,
|
|
56
|
-
`FETCH_HEAD:refs/heads/${input.workBranch}`
|
|
57
|
-
]);
|
|
58
|
-
} catch {
|
|
59
|
-
throw new Error(
|
|
60
|
-
"GitLab HTTPS read/write admission failed; check repository access and write_repository scope"
|
|
61
|
-
);
|
|
62
|
-
} finally {
|
|
63
|
-
await rm(directory, { recursive: true, force: true });
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// src/client.ts
|
|
68
|
-
var GitLabError = class extends Error {
|
|
69
|
-
/** @internal */
|
|
70
|
-
constructor(status, retryable) {
|
|
71
|
-
super(
|
|
72
|
-
`GitLab request failed (${status || "network unavailable"})${retryable ? "; retryable" : "; check profile and project access"}`
|
|
73
|
-
);
|
|
74
|
-
this.status = status;
|
|
75
|
-
this.retryable = retryable;
|
|
76
|
-
}
|
|
77
|
-
status;
|
|
78
|
-
retryable;
|
|
79
|
-
};
|
|
80
|
-
function parseGitLabProfiles(raw) {
|
|
81
|
-
const profiles = /* @__PURE__ */ new Map();
|
|
82
|
-
for (const [name, value] of Object.entries(
|
|
83
|
-
asUnknownRecord(asUnknownRecord(raw)?.profiles) ?? {}
|
|
84
|
-
)) {
|
|
85
|
-
const item = asUnknownRecord(value) ?? {};
|
|
86
|
-
const baseUrl = typeof item.base_url === "string" ? item.base_url.replace(/\/+$/, "") : "";
|
|
87
|
-
const url = repositoryHttpsUrl2(`${baseUrl}/` === "/" ? "" : `${baseUrl}/repository`);
|
|
88
|
-
if (url.origin !== baseUrl)
|
|
89
|
-
throw new Error(`GitLab profile '${name}' requires an HTTPS origin base_url`);
|
|
90
|
-
const configuredToken = typeof item.token === "string" ? item.token : "";
|
|
91
|
-
const token = configuredToken.startsWith("env:") ? process.env[configuredToken.slice(4)] ?? "" : configuredToken;
|
|
92
|
-
if (!token || /[\r\n\0]/.test(token))
|
|
93
|
-
throw new Error(`GitLab profile '${name}' requires a token`);
|
|
94
|
-
const identity = asUnknownRecord(item.git_identity);
|
|
95
|
-
if (identity && [identity.name, identity.email].some(
|
|
96
|
-
(v) => typeof v !== "string" || !v.trim() || /[\r\n<>]/.test(v)
|
|
97
|
-
))
|
|
98
|
-
throw new Error(`GitLab profile '${name}' requires a valid git_identity name and email`);
|
|
99
|
-
profiles.set(name, {
|
|
100
|
-
baseUrl,
|
|
101
|
-
token,
|
|
102
|
-
...identity ? { gitIdentity: { name: String(identity.name), email: String(identity.email) } } : {}
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
return profiles;
|
|
106
|
-
}
|
|
107
|
-
var projectPath = (id) => `/projects/${encodeURIComponent(id)}`;
|
|
108
|
-
var mrPath = (id, iid) => `${projectPath(id)}/merge_requests/${iid}`;
|
|
109
|
-
var GitLabClient = class {
|
|
110
|
-
/** @public */
|
|
111
|
-
baseUrl;
|
|
112
|
-
#profile;
|
|
113
|
-
#fetch;
|
|
114
|
-
#sleep;
|
|
115
|
-
/** @internal */
|
|
116
|
-
constructor(profile, options = {}) {
|
|
117
|
-
if (repositoryHttpsUrl2(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
|
|
118
|
-
throw new Error("GitLab requires an HTTPS origin baseUrl");
|
|
119
|
-
if (!profile.token || /[\r\n\0]/.test(profile.token))
|
|
120
|
-
throw new Error("GitLab requires a valid token");
|
|
121
|
-
this.#profile = profile;
|
|
122
|
-
this.baseUrl = profile.baseUrl;
|
|
123
|
-
this.#fetch = options.fetch ?? fetch;
|
|
124
|
-
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
125
|
-
}
|
|
126
|
-
async response(path, signal, body, method) {
|
|
127
|
-
for (let attempt = 0; ; attempt++) {
|
|
128
|
-
let response;
|
|
129
|
-
try {
|
|
130
|
-
response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
|
|
131
|
-
method: method ?? (body === void 0 ? "GET" : "POST"),
|
|
132
|
-
redirect: "error",
|
|
133
|
-
headers: {
|
|
134
|
-
"PRIVATE-TOKEN": this.#profile.token,
|
|
135
|
-
Accept: "application/json",
|
|
136
|
-
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
137
|
-
},
|
|
138
|
-
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4),
|
|
139
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
140
|
-
});
|
|
141
|
-
} catch {
|
|
142
|
-
if (signal?.aborted) throw new GitLabError(0, true);
|
|
143
|
-
if (body !== void 0 || attempt >= 2) throw new GitLabError(0, true);
|
|
144
|
-
await this.#sleep(1e3 * 2 ** attempt);
|
|
145
|
-
continue;
|
|
146
|
-
}
|
|
147
|
-
if (response.ok) return response;
|
|
148
|
-
const retryable = response.status === 429 || response.status >= 500 || response.status === 408;
|
|
149
|
-
await response.body?.cancel();
|
|
150
|
-
if (!retryable || body !== void 0 || attempt >= 2)
|
|
151
|
-
throw new GitLabError(response.status, retryable);
|
|
152
|
-
const seconds = Number(response.headers.get("retry-after"));
|
|
153
|
-
await this.#sleep(Math.min(3e4, seconds > 0 ? seconds * 1e3 : 1e3 * 2 ** attempt));
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
async request(path, signal, body, method) {
|
|
157
|
-
return this.json(await this.response(path, signal, body, method));
|
|
158
|
-
}
|
|
159
|
-
async json(response) {
|
|
160
|
-
try {
|
|
161
|
-
return await response.json();
|
|
162
|
-
} catch {
|
|
163
|
-
throw new GitLabError(502, true);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
async pages(path, signal) {
|
|
167
|
-
const rows = [];
|
|
168
|
-
let page = 1;
|
|
169
|
-
for (let n = 0; n < 1e4; n++) {
|
|
170
|
-
const response = await this.response(
|
|
171
|
-
`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
|
|
172
|
-
signal
|
|
173
|
-
);
|
|
174
|
-
const batch = await this.json(response);
|
|
175
|
-
if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
|
|
176
|
-
rows.push(...batch);
|
|
177
|
-
const next = response.headers.get("x-next-page");
|
|
178
|
-
if (next === "" || next === null && batch.length < 100) return rows;
|
|
179
|
-
const nextPage = next === null ? page + 1 : Number(next);
|
|
180
|
-
if (!Number.isInteger(nextPage) || nextPage <= page)
|
|
181
|
-
throw new Error("Invalid GitLab pagination");
|
|
182
|
-
page = nextPage;
|
|
183
|
-
}
|
|
184
|
-
throw new Error("GitLab pagination limit exceeded; discovery incomplete");
|
|
185
|
-
}
|
|
186
|
-
/** @public */
|
|
187
|
-
listIssues(id, signal) {
|
|
188
|
-
return this.pages(`${projectPath(id)}/issues?state=opened&scope=all`, signal);
|
|
189
|
-
}
|
|
190
|
-
/** @public */
|
|
191
|
-
getIssue(id, iid, signal) {
|
|
192
|
-
return this.request(`${projectPath(id)}/issues/${iid}`, signal);
|
|
193
|
-
}
|
|
194
|
-
/** @public */
|
|
195
|
-
updateIssue(id, iid, patch, signal) {
|
|
196
|
-
return this.request(`${projectPath(id)}/issues/${iid}`, signal, patch, "PUT");
|
|
197
|
-
}
|
|
198
|
-
/** @public */
|
|
199
|
-
listIssueNotes(id, iid, signal) {
|
|
200
|
-
return this.pages(`${projectPath(id)}/issues/${iid}/notes`, signal);
|
|
201
|
-
}
|
|
202
|
-
/** @public */
|
|
203
|
-
addIssueNote(id, iid, body, signal) {
|
|
204
|
-
return this.request(`${projectPath(id)}/issues/${iid}/notes`, signal, { body });
|
|
205
|
-
}
|
|
206
|
-
/** @public */
|
|
207
|
-
/** @public */
|
|
208
|
-
listLabels(id, signal) {
|
|
209
|
-
return this.pages(`${projectPath(id)}/labels`, signal);
|
|
210
|
-
}
|
|
211
|
-
/** @public */
|
|
212
|
-
/** @public */
|
|
213
|
-
createLabel(id, name, signal) {
|
|
214
|
-
return this.request(`${projectPath(id)}/labels`, signal, { name, color: "#2da44e" });
|
|
215
|
-
}
|
|
216
|
-
/** @public */
|
|
217
|
-
listBranchMergeRequests(id, source, target, signal) {
|
|
218
|
-
return this.pages(
|
|
219
|
-
`${projectPath(id)}/merge_requests?state=all&source_branch=${encodeURIComponent(source)}&target_branch=${encodeURIComponent(target)}`,
|
|
220
|
-
signal
|
|
221
|
-
);
|
|
222
|
-
}
|
|
223
|
-
/** @public */
|
|
224
|
-
createMergeRequest(id, input, signal) {
|
|
225
|
-
return this.request(`${projectPath(id)}/merge_requests`, signal, {
|
|
226
|
-
...input,
|
|
227
|
-
remove_source_branch: false
|
|
228
|
-
});
|
|
229
|
-
}
|
|
230
|
-
/** @public */
|
|
231
|
-
async preflightRepository(projectId, baseBranch, workBranch, signal) {
|
|
232
|
-
const project = await this.getProject(projectId, signal);
|
|
233
|
-
await preflightGitLabRepository({
|
|
234
|
-
url: project.http_url_to_repo,
|
|
235
|
-
origin: this.baseUrl,
|
|
236
|
-
token: this.#profile.token,
|
|
237
|
-
baseBranch,
|
|
238
|
-
workBranch,
|
|
239
|
-
signal
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
/** @public */
|
|
243
|
-
getProject(id, signal) {
|
|
244
|
-
return this.request(projectPath(id), signal);
|
|
245
|
-
}
|
|
246
|
-
/** @internal */
|
|
247
|
-
listProjects(signal) {
|
|
248
|
-
return this.pages("/projects?archived=false", signal);
|
|
249
|
-
}
|
|
250
|
-
/** @internal */
|
|
251
|
-
getGroup(id, signal) {
|
|
252
|
-
return this.request(`/groups/${encodeURIComponent(id)}`, signal);
|
|
253
|
-
}
|
|
254
|
-
/** @internal */
|
|
255
|
-
listGroupProjects(id, signal) {
|
|
256
|
-
return this.pages(
|
|
257
|
-
`/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
|
|
258
|
-
signal
|
|
259
|
-
);
|
|
260
|
-
}
|
|
261
|
-
/** @public */
|
|
262
|
-
listMergeRequests(id, label, signal) {
|
|
263
|
-
return this.pages(
|
|
264
|
-
`${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
|
|
265
|
-
signal
|
|
266
|
-
);
|
|
267
|
-
}
|
|
268
|
-
/** @internal */
|
|
269
|
-
getMergeRequest(id, iid, signal) {
|
|
270
|
-
return this.request(mrPath(id, iid), signal);
|
|
271
|
-
}
|
|
272
|
-
/** @public */
|
|
273
|
-
getChanges(id, iid, signal) {
|
|
274
|
-
return this.pages(`${mrPath(id, iid)}/diffs`, signal);
|
|
275
|
-
}
|
|
276
|
-
/** @public */
|
|
277
|
-
getBranch(id, branch, signal) {
|
|
278
|
-
return this.request(
|
|
279
|
-
`${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
|
|
280
|
-
signal
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
/** @internal */
|
|
284
|
-
getCommit(id, sha, signal) {
|
|
285
|
-
return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
|
|
286
|
-
}
|
|
287
|
-
/** @internal */
|
|
288
|
-
listMergeRequestPipelines(id, iid, signal) {
|
|
289
|
-
return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
|
|
290
|
-
}
|
|
291
|
-
/** @internal */
|
|
292
|
-
listBranchPipelines(id, branch, sha, signal) {
|
|
293
|
-
return this.pages(
|
|
294
|
-
`${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
|
|
295
|
-
signal
|
|
296
|
-
);
|
|
297
|
-
}
|
|
298
|
-
/** @internal */
|
|
299
|
-
getPipeline(id, pipeline, signal) {
|
|
300
|
-
return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
|
|
301
|
-
}
|
|
302
|
-
/** @public */
|
|
303
|
-
listFailedJobs(id, pipeline, signal) {
|
|
304
|
-
return this.pages(
|
|
305
|
-
`${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
|
|
306
|
-
signal
|
|
307
|
-
);
|
|
308
|
-
}
|
|
309
|
-
/** @internal */
|
|
310
|
-
listNotes(id, iid, signal) {
|
|
311
|
-
return this.pages(`${mrPath(id, iid)}/notes`, signal);
|
|
312
|
-
}
|
|
313
|
-
/** @internal */
|
|
314
|
-
getDiscussion(id, iid, discussionId, signal) {
|
|
315
|
-
return this.request(
|
|
316
|
-
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
|
|
317
|
-
signal
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
/** @internal */
|
|
321
|
-
replyToDiscussion(id, iid, discussionId, body, signal) {
|
|
322
|
-
return this.request(
|
|
323
|
-
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
|
|
324
|
-
signal,
|
|
325
|
-
{ body }
|
|
326
|
-
);
|
|
327
|
-
}
|
|
328
|
-
/** @internal */
|
|
329
|
-
listNoteReactions(id, iid, noteId, signal) {
|
|
330
|
-
return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
|
|
331
|
-
}
|
|
332
|
-
/** @internal */
|
|
333
|
-
addNoteReaction(id, iid, noteId, name, signal) {
|
|
334
|
-
return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
|
|
335
|
-
}
|
|
336
|
-
/** @public */
|
|
337
|
-
async listMergeRequestFeedback(id, iid, signal) {
|
|
338
|
-
const discussions = await this.pages(
|
|
339
|
-
`${mrPath(id, iid)}/discussions`,
|
|
340
|
-
signal
|
|
341
|
-
);
|
|
342
|
-
const feedback = [];
|
|
343
|
-
for (const discussion of discussions) {
|
|
344
|
-
for (const note of discussion.notes) {
|
|
345
|
-
if (note.system || note.resolved || note.author.bot || /<!-- leitwerk:gitlab:[a-f0-9]{64} -->/.test(note.body) || !note.body.trim() || !Number.isFinite(Date.parse(note.created_at)))
|
|
346
|
-
continue;
|
|
347
|
-
const position = note.position ?? discussion.notes[0]?.position;
|
|
348
|
-
feedback.push({
|
|
349
|
-
id: note.id,
|
|
350
|
-
discussionId: discussion.id,
|
|
351
|
-
body: note.body,
|
|
352
|
-
author: note.author.username,
|
|
353
|
-
createdAt: note.created_at,
|
|
354
|
-
...position ? {
|
|
355
|
-
path: position.new_path ?? position.old_path,
|
|
356
|
-
line: position.new_line ?? position.old_line
|
|
357
|
-
} : {}
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
return feedback.sort((a, b) => a.id - b.id);
|
|
362
|
-
}
|
|
363
|
-
/** @internal */
|
|
364
|
-
addNote(id, iid, body, signal) {
|
|
365
|
-
return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
|
|
366
|
-
}
|
|
367
|
-
/** @public */
|
|
368
|
-
async resolveGitIdentity(signal) {
|
|
369
|
-
const user = await this.request("/user", signal);
|
|
370
|
-
const name = this.#profile.gitIdentity?.name ?? user.name;
|
|
371
|
-
const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
|
|
372
|
-
if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
|
|
373
|
-
throw new Error(
|
|
374
|
-
"GitLab bot Git identity is unavailable; configure git_identity on the profile"
|
|
375
|
-
);
|
|
376
|
-
return { name, email, username: user.username };
|
|
377
|
-
}
|
|
378
|
-
/** @public */
|
|
379
|
-
async getJobTrace(id, job, maxBytes = 65536, signal) {
|
|
380
|
-
const limit = Math.min(262144, Math.max(1, Math.floor(maxBytes) || 65536));
|
|
381
|
-
const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
|
|
382
|
-
const reader = response.body?.getReader();
|
|
383
|
-
if (!reader) return { text: "", truncated: false };
|
|
384
|
-
const chunks = [];
|
|
385
|
-
let size = 0;
|
|
386
|
-
let truncated = false;
|
|
387
|
-
try {
|
|
388
|
-
while (true) {
|
|
389
|
-
const item = await reader.read();
|
|
390
|
-
if (item.done) break;
|
|
391
|
-
const take = Math.min(item.value.length, limit - size);
|
|
392
|
-
chunks.push(item.value.slice(0, take));
|
|
393
|
-
size += take;
|
|
394
|
-
if (size >= limit) {
|
|
395
|
-
truncated = true;
|
|
396
|
-
break;
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
} finally {
|
|
400
|
-
await reader.cancel();
|
|
401
|
-
}
|
|
402
|
-
return { text: Buffer.concat(chunks).toString("utf8"), truncated };
|
|
403
|
-
}
|
|
404
|
-
};
|
|
405
|
-
async function observeMergeRequest(client, projectId, iid, signal) {
|
|
406
|
-
const mr = await client.getMergeRequest(projectId, iid, signal);
|
|
407
|
-
if (mr.state !== "opened") return { mr, pipeline: null };
|
|
408
|
-
const targetHead = (await client.getBranch(mr.target_project_id, mr.target_branch, signal)).commit.id;
|
|
409
|
-
const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
|
|
410
|
-
(a, b) => b.id - a.id
|
|
411
|
-
);
|
|
412
|
-
for (const candidate of associated) {
|
|
413
|
-
const id = candidate.project_id ?? projectId;
|
|
414
|
-
let matches = candidate.sha === mr.sha;
|
|
415
|
-
if (!matches && (candidate.ref === `refs/merge-requests/${iid}/merge` || candidate.sha === mr.merge_commit_sha)) {
|
|
416
|
-
const commit = await client.getCommit(id, candidate.sha, signal);
|
|
417
|
-
matches = commit.parent_ids.includes(mr.sha);
|
|
418
|
-
}
|
|
419
|
-
if (matches)
|
|
420
|
-
return { mr, targetHead, pipeline: await client.getPipeline(id, candidate.id, signal) };
|
|
421
|
-
}
|
|
422
|
-
const candidates = await client.listBranchPipelines(
|
|
423
|
-
mr.source_project_id,
|
|
424
|
-
mr.source_branch,
|
|
425
|
-
mr.sha,
|
|
426
|
-
signal
|
|
427
|
-
);
|
|
428
|
-
const latest = candidates.filter((p) => p.sha === mr.sha && p.ref === mr.source_branch && p.source === "push").sort((a, b) => b.id - a.id)[0];
|
|
429
|
-
return {
|
|
430
|
-
mr,
|
|
431
|
-
targetHead,
|
|
432
|
-
pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null
|
|
433
|
-
};
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// src/capability.ts
|
|
437
|
-
import {
|
|
438
|
-
createCapabilityToken
|
|
439
|
-
} from "@leitwerk-dev/process-sdk";
|
|
440
|
-
var gitlabIntegration = createCapabilityToken(
|
|
441
|
-
"@leitwerk-dev/gitlab.integration"
|
|
442
|
-
);
|
|
443
|
-
function gitlabRepositoryCredentials(profile, projects) {
|
|
444
|
-
return projects.map((project) => ({
|
|
445
|
-
projectKey: project.key,
|
|
446
|
-
kind: "git_https",
|
|
447
|
-
credentialRef: `gitlab:${profile}`
|
|
448
|
-
}));
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
// src/tools.ts
|
|
452
|
-
import { createHash } from "crypto";
|
|
453
|
-
import {
|
|
454
|
-
numberArg,
|
|
455
|
-
projectParameters,
|
|
456
|
-
stringArg
|
|
457
|
-
} from "@leitwerk-dev/process-sdk";
|
|
458
|
-
async function existingRemote(read) {
|
|
459
|
-
try {
|
|
460
|
-
return await read();
|
|
461
|
-
} catch (error) {
|
|
462
|
-
if (error instanceof GitLabError && error.status === 404) return null;
|
|
463
|
-
throw error;
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
function resolveGitLabRepositoryBinding(ctx) {
|
|
467
|
-
if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
|
|
468
|
-
throw new Error("An authorized GitLab process project is required");
|
|
469
|
-
const binding = ctx.project.metadata?.gitlab;
|
|
470
|
-
if (!binding || typeof binding.profile !== "string" || !binding.profile.trim() || typeof binding.projectId !== "number" || !Number.isSafeInteger(binding.projectId) || binding.projectId <= 0)
|
|
471
|
-
throw new Error("Invalid GitLab project binding");
|
|
472
|
-
return { profile: binding.profile, projectId: binding.projectId };
|
|
473
|
-
}
|
|
474
|
-
function resolveGitLabBinding(ctx) {
|
|
475
|
-
const repository = resolveGitLabRepositoryBinding(ctx);
|
|
476
|
-
const iid = ctx.project?.metadata?.gitlab?.iid;
|
|
477
|
-
if (typeof iid !== "number" || !Number.isSafeInteger(iid) || iid <= 0)
|
|
478
|
-
throw new Error("Invalid GitLab project binding: a merge request is required");
|
|
479
|
-
return { ...repository, iid };
|
|
480
|
-
}
|
|
481
|
-
async function ensureGitLabComment(input) {
|
|
482
|
-
const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
|
|
483
|
-
const identity = [client.baseUrl, projectId, iid, instanceId, writeKey];
|
|
484
|
-
if (input.discussionId) identity.push(input.discussionId);
|
|
485
|
-
const digest = createHash("sha256").update(JSON.stringify(identity)).digest("hex");
|
|
486
|
-
const marker = `<!-- leitwerk:gitlab:${digest} -->`;
|
|
487
|
-
const find = async () => {
|
|
488
|
-
const notes = input.discussionId ? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes : await client.listNotes(projectId, iid, signal);
|
|
489
|
-
return notes.find((note) => note.body.includes(marker));
|
|
490
|
-
};
|
|
491
|
-
await writes.ensure(
|
|
492
|
-
{ writeType: "gitlab.comment", dedupKey: digest },
|
|
493
|
-
{
|
|
494
|
-
reconcile: () => existingRemote(async () => await find() ?? null),
|
|
495
|
-
execute: () => {
|
|
496
|
-
const body = `${input.body}
|
|
497
|
-
|
|
498
|
-
${marker}`;
|
|
499
|
-
return input.discussionId ? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal) : client.addNote(projectId, iid, body, signal);
|
|
500
|
-
},
|
|
501
|
-
toMetadata: (note) => ({ projectId, iid, noteId: note.id, marker })
|
|
502
|
-
}
|
|
503
|
-
);
|
|
504
|
-
return { marker };
|
|
505
|
-
}
|
|
506
|
-
async function ensureGitLabSeenReaction(input) {
|
|
507
|
-
const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
|
|
508
|
-
const digest = createHash("sha256").update(JSON.stringify([client.baseUrl, projectId, iid, instanceId, "eyes", noteId])).digest("hex");
|
|
509
|
-
await writes.ensure(
|
|
510
|
-
{ writeType: "gitlab.reaction", dedupKey: digest },
|
|
511
|
-
{
|
|
512
|
-
reconcile: () => existingRemote(async () => {
|
|
513
|
-
const identity = await client.resolveGitIdentity(signal);
|
|
514
|
-
return (await client.listNoteReactions(projectId, iid, noteId, signal)).find(
|
|
515
|
-
(reaction) => reaction.name === "eyes" && reaction.user.username === identity.username
|
|
516
|
-
) ?? null;
|
|
517
|
-
}),
|
|
518
|
-
execute: () => client.addNoteReaction(projectId, iid, noteId, "eyes", signal),
|
|
519
|
-
toMetadata: (reaction) => ({ projectId, iid, noteId, reactionId: reaction.id, name: "eyes" })
|
|
520
|
-
}
|
|
521
|
-
);
|
|
522
|
-
}
|
|
523
|
-
function registerGitLabTools(api, integration) {
|
|
524
|
-
for (const [name, description, required] of [
|
|
525
|
-
["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
|
|
526
|
-
["gitlab_get_changes", "Read the MR changes", []],
|
|
527
|
-
["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
|
|
528
|
-
["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
|
|
529
|
-
[
|
|
530
|
-
"gitlab_get_job_trace",
|
|
531
|
-
"Read a bounded trace from a failed MR pipeline job",
|
|
532
|
-
["pipelineId", "jobId"]
|
|
533
|
-
],
|
|
534
|
-
["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
|
|
535
|
-
[
|
|
536
|
-
"gitlab_reply",
|
|
537
|
-
"Post a retry-safe reply in an MR discussion",
|
|
538
|
-
["body", "writeKey", "discussionId"]
|
|
539
|
-
]
|
|
540
|
-
]) {
|
|
541
|
-
api.tool({
|
|
542
|
-
name,
|
|
543
|
-
description,
|
|
544
|
-
parameters: projectParameters(
|
|
545
|
-
{
|
|
546
|
-
pipelineId: { type: "integer" },
|
|
547
|
-
jobId: { type: "integer" },
|
|
548
|
-
maxBytes: { type: "integer" },
|
|
549
|
-
body: { type: "string" },
|
|
550
|
-
writeKey: { type: "string" },
|
|
551
|
-
discussionId: { type: "string" }
|
|
552
|
-
},
|
|
553
|
-
[...required]
|
|
554
|
-
),
|
|
555
|
-
async execute(ctx, args) {
|
|
556
|
-
if (name === "gitlab_get_identity")
|
|
557
|
-
return integration.client(resolveGitLabRepositoryBinding(ctx).profile).resolveGitIdentity(ctx.signal);
|
|
558
|
-
const b = resolveGitLabBinding(ctx);
|
|
559
|
-
const client = integration.client(b.profile);
|
|
560
|
-
if (name === "gitlab_observe_merge_request")
|
|
561
|
-
return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
562
|
-
if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
|
|
563
|
-
if (name === "gitlab_comment" || name === "gitlab_reply")
|
|
564
|
-
return ensureGitLabComment({
|
|
565
|
-
client,
|
|
566
|
-
writes: ctx.externalWrites,
|
|
567
|
-
instanceId: ctx.process.id,
|
|
568
|
-
projectId: b.projectId,
|
|
569
|
-
iid: b.iid,
|
|
570
|
-
writeKey: stringArg(args, "writeKey"),
|
|
571
|
-
body: stringArg(args, "body"),
|
|
572
|
-
...name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {},
|
|
573
|
-
signal: ctx.signal
|
|
574
|
-
});
|
|
575
|
-
const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
576
|
-
if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
|
|
577
|
-
throw new Error("Pipeline is not current for the authorized MR");
|
|
578
|
-
const jobs = await client.listFailedJobs(
|
|
579
|
-
observation.pipeline.project_id,
|
|
580
|
-
observation.pipeline.id,
|
|
581
|
-
ctx.signal
|
|
582
|
-
);
|
|
583
|
-
if (name === "gitlab_list_failed_jobs") return jobs;
|
|
584
|
-
const job = jobs.find((job2) => job2.id === numberArg(args, "jobId"));
|
|
585
|
-
if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
|
|
586
|
-
return client.getJobTrace(
|
|
587
|
-
observation.pipeline.project_id,
|
|
588
|
-
job.id,
|
|
589
|
-
typeof args.maxBytes === "number" ? args.maxBytes : void 0,
|
|
590
|
-
ctx.signal
|
|
591
|
-
);
|
|
592
|
-
}
|
|
593
|
-
});
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
// src/selection.ts
|
|
598
|
-
function parseGitLabSelection(raw) {
|
|
599
|
-
const list = (value) => {
|
|
600
|
-
if (value === void 0) return [];
|
|
601
|
-
if (!Array.isArray(value) || value.some(
|
|
602
|
-
(v) => typeof v !== "string" || !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(v) || v.split("/").some((p) => p === "." || p === "..")
|
|
603
|
-
))
|
|
604
|
-
throw new Error("GitLab selectors require exact namespace paths");
|
|
605
|
-
return [...new Set(value)];
|
|
606
|
-
};
|
|
607
|
-
const pair = (value) => {
|
|
608
|
-
if (value !== void 0 && (!value || typeof value !== "object" || Array.isArray(value)))
|
|
609
|
-
throw new Error("GitLab selectors must be objects");
|
|
610
|
-
const item = value;
|
|
611
|
-
return { include: list(item?.include), exclude: list(item?.exclude) };
|
|
612
|
-
};
|
|
613
|
-
if (raw.all_accessible !== void 0 && typeof raw.all_accessible !== "boolean")
|
|
614
|
-
throw new Error("all_accessible must be a boolean");
|
|
615
|
-
const parsed = {
|
|
616
|
-
projects: pair(raw.projects),
|
|
617
|
-
groups: pair(raw.groups),
|
|
618
|
-
allAccessible: raw.all_accessible === true
|
|
619
|
-
};
|
|
620
|
-
if (!parsed.allAccessible && !parsed.projects.include.length && !parsed.groups.include.length)
|
|
621
|
-
throw new Error("GitLab requires explicit project/group includes or all_accessible: true");
|
|
622
|
-
return parsed;
|
|
623
|
-
}
|
|
624
|
-
function projectExcluded(selection, name) {
|
|
625
|
-
return selection.projects.exclude.includes(name) || selection.groups.exclude.some((group) => name.startsWith(`${group}/`));
|
|
626
|
-
}
|
|
627
|
-
async function selectGitLabProjects(client, selection) {
|
|
628
|
-
const candidates = selection.allAccessible ? await client.listProjects() : [];
|
|
629
|
-
for (const name of selection.projects.include) candidates.push(await client.getProject(name));
|
|
630
|
-
for (const group of selection.groups.include)
|
|
631
|
-
candidates.push(...await client.listGroupProjects(group));
|
|
632
|
-
return [
|
|
633
|
-
...new Map(
|
|
634
|
-
candidates.filter((p) => !p.archived && !projectExcluded(selection, p.path_with_namespace)).map((p) => [p.id, p])
|
|
635
|
-
).values()
|
|
636
|
-
];
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
// src/issue-watcher.ts
|
|
640
|
-
import { asUnknownRecord as asUnknownRecord2 } from "@leitwerk-dev/domain";
|
|
641
|
-
import {
|
|
642
|
-
defineProcessWatcherSource,
|
|
643
|
-
parseProcessWatcherLaunchModelConfig
|
|
644
|
-
} from "@leitwerk-dev/process-sdk";
|
|
645
|
-
import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
|
|
646
|
-
var gitlabIssueExternalId = (origin, projectId, iid) => `gitlab:${origin}:${projectId}#${iid}`;
|
|
647
|
-
var gitlabIssueWatcherSource = defineProcessWatcherSource({
|
|
648
|
-
id: "@leitwerk-dev/gitlab.issue",
|
|
649
|
-
label: "GitLab issue",
|
|
650
|
-
parseConfig(raw) {
|
|
651
|
-
const c = asUnknownRecord2(raw);
|
|
652
|
-
if (!c || typeof c.enabled !== "boolean") throw new Error("GitLab watcher requires enabled");
|
|
653
|
-
const text = (value, name) => {
|
|
654
|
-
if (typeof value !== "string" || !value.trim())
|
|
655
|
-
throw new Error(`GitLab watcher requires ${name}`);
|
|
656
|
-
return value.trim();
|
|
657
|
-
};
|
|
658
|
-
const labels = asUnknownRecord2(c.labels) ?? {};
|
|
659
|
-
const trigger = text(labels.trigger, "labels.trigger");
|
|
660
|
-
const done = text(labels.done, "labels.done");
|
|
661
|
-
if (trigger === done || trigger.includes(",") || done.includes(","))
|
|
662
|
-
throw new Error("GitLab trigger/done labels must be distinct and contain no comma");
|
|
663
|
-
const pollInterval = text(c.poll_interval ?? "30s", "poll_interval");
|
|
664
|
-
if (parseDurationMs(pollInterval, -1) <= 0) throw new Error("Invalid GitLab polling interval");
|
|
665
|
-
return {
|
|
666
|
-
enabled: c.enabled,
|
|
667
|
-
config: {
|
|
668
|
-
...parseGitLabSelection(c),
|
|
669
|
-
profile: text(c.profile, "profile"),
|
|
670
|
-
pollInterval,
|
|
671
|
-
labels: { trigger, done }
|
|
672
|
-
},
|
|
673
|
-
launchModelConfig: parseProcessWatcherLaunchModelConfig(c.launch)
|
|
674
|
-
};
|
|
675
|
-
},
|
|
676
|
-
presentConfig(c) {
|
|
677
|
-
return {
|
|
678
|
-
targetSummary: `Profile ${c.profile} \xB7 trigger ${c.labels.trigger}`,
|
|
679
|
-
details: [
|
|
680
|
-
{ label: "Projects", value: c.projects.include.join(", ") || "selected groups" },
|
|
681
|
-
{ label: "Groups", value: c.groups.include.join(", ") || "none" }
|
|
682
|
-
]
|
|
683
|
-
};
|
|
684
|
-
}
|
|
685
|
-
});
|
|
686
|
-
function createGitLabIssueDiscovery(deps, integration, now) {
|
|
687
|
-
const due = /* @__PURE__ */ new Map();
|
|
688
|
-
return async (result) => {
|
|
689
|
-
for (const watcher of deps.processWatchers?.listBySource(gitlabIssueWatcherSource) ?? []) {
|
|
690
|
-
if (!watcher.enabled) continue;
|
|
691
|
-
const key = `${watcher.processId}:${watcher.watcherId}`;
|
|
692
|
-
const c = watcher.config;
|
|
693
|
-
if ((due.get(key) ?? 0) > now()) continue;
|
|
694
|
-
due.set(key, now() + parseDurationMs(c.pollInterval, 3e4));
|
|
695
|
-
const client = integration.client(c.profile);
|
|
696
|
-
for (const repository of await selectGitLabProjects(client, c))
|
|
697
|
-
for (const issue of await client.listIssues(repository.id)) {
|
|
698
|
-
if (issue.state !== "opened" || !issue.labels.includes(c.labels.trigger) || issue.labels.includes(c.labels.done))
|
|
699
|
-
continue;
|
|
700
|
-
const id = gitlabIssueExternalId(client.baseUrl, repository.id, issue.iid);
|
|
701
|
-
if (deps.processes.listAll().some((p) => p.externalId === id)) {
|
|
702
|
-
result.skipped.push(id);
|
|
703
|
-
continue;
|
|
704
|
-
}
|
|
705
|
-
const guarded = {
|
|
706
|
-
...watcher,
|
|
707
|
-
async resolveLaunchAttempt(...args) {
|
|
708
|
-
const attempt = await watcher.resolveLaunchAttempt(...args);
|
|
709
|
-
if (!attempt) return null;
|
|
710
|
-
return {
|
|
711
|
-
...attempt,
|
|
712
|
-
preparationChecks: [
|
|
713
|
-
...attempt.preparationChecks,
|
|
714
|
-
{
|
|
715
|
-
id: "gitlab-issue-eligibility",
|
|
716
|
-
label: "Recheck GitLab source issue",
|
|
717
|
-
async run() {
|
|
718
|
-
const fresh = await client.getIssue(repository.id, issue.iid);
|
|
719
|
-
if (fresh.state !== "opened" || !fresh.labels.includes(c.labels.trigger) || fresh.labels.includes(c.labels.done))
|
|
720
|
-
throw new Error("GitLab source issue eligibility changed before launch");
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
]
|
|
724
|
-
};
|
|
725
|
-
}
|
|
726
|
-
};
|
|
727
|
-
const launched = await deps.launchRuns.startWatcher(
|
|
728
|
-
guarded,
|
|
729
|
-
{ profile: c.profile, repository, issue, labels: c.labels },
|
|
730
|
-
{ idempotencyKey: id }
|
|
731
|
-
);
|
|
732
|
-
if (launched.error) result.errors.push(`${id}:launch_failed`);
|
|
733
|
-
else if (launched.process) result.created.push(id);
|
|
734
|
-
else result.skipped.push(id);
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
};
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
// src/external.ts
|
|
741
|
-
import {
|
|
742
|
-
createExternalSourcePollReporter
|
|
743
|
-
} from "@leitwerk-dev/process-sdk";
|
|
744
|
-
import { conflictKey } from "@leitwerk-dev/repository-rebase";
|
|
745
|
-
import { emptyPollResult, parseDurationMs as parseDurationMs2 } from "@leitwerk-dev/watcher-utils";
|
|
746
|
-
var GITLAB_ISSUE_CANCELLED_KIND = "@leitwerk-dev/gitlab.issue-cancelled";
|
|
747
|
-
var GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
|
|
748
|
-
function pendingGitLabFeedback(items, afterId, since) {
|
|
749
|
-
const start = since ? Date.parse(since) : 0;
|
|
750
|
-
return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
|
|
751
|
-
}
|
|
752
|
-
function gitLabFeedbackReadyAt(items, quietPeriodMs) {
|
|
753
|
-
return items.length ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs : null;
|
|
754
|
-
}
|
|
755
|
-
var observationKey = ({ mr, pipeline, targetHead }) => JSON.stringify([
|
|
756
|
-
mr.state,
|
|
757
|
-
mr.sha,
|
|
758
|
-
[...mr.labels].sort(),
|
|
759
|
-
pipeline?.project_id,
|
|
760
|
-
pipeline?.id,
|
|
761
|
-
pipeline?.status,
|
|
762
|
-
mr.source_project_id,
|
|
763
|
-
mr.source_branch,
|
|
764
|
-
mr.target_project_id,
|
|
765
|
-
mr.target_branch,
|
|
766
|
-
targetHead,
|
|
767
|
-
mr.has_conflicts,
|
|
768
|
-
mr.merge_status,
|
|
769
|
-
mr.detailed_merge_status
|
|
770
|
-
]);
|
|
771
|
-
var gitlabExternal = {
|
|
772
|
-
/** @public */
|
|
773
|
-
issueCancelled(resolve) {
|
|
774
|
-
return {
|
|
775
|
-
kind: GITLAB_ISSUE_CANCELLED_KIND,
|
|
776
|
-
label: "GitLab source issue cancelled",
|
|
777
|
-
config: {},
|
|
778
|
-
inputMode: "none",
|
|
779
|
-
resolve
|
|
780
|
-
};
|
|
781
|
-
},
|
|
782
|
-
/** @public */
|
|
783
|
-
mergeRequest(resolve) {
|
|
784
|
-
return {
|
|
785
|
-
kind: GITLAB_MR_KIND,
|
|
786
|
-
label: "GitLab merge request",
|
|
787
|
-
description: "Observe MR state, current source head and revision-correlated CI",
|
|
788
|
-
config: {},
|
|
789
|
-
inputMode: "none",
|
|
790
|
-
resolve
|
|
791
|
-
};
|
|
792
|
-
}
|
|
793
|
-
};
|
|
794
|
-
function createGitLabProvider(deps, integration, options = {}) {
|
|
795
|
-
const schedule = /* @__PURE__ */ new Map();
|
|
796
|
-
const now = options.now ?? Date.now;
|
|
797
|
-
const discover = createGitLabIssueDiscovery(deps, integration, now);
|
|
798
|
-
return deps.polling.create({
|
|
799
|
-
id: "gitlab",
|
|
800
|
-
pollInterval: () => "5s",
|
|
801
|
-
isEnabled: () => true,
|
|
802
|
-
defaultIntervalMs: 5e3,
|
|
803
|
-
async pollOnce() {
|
|
804
|
-
const result = emptyPollResult();
|
|
805
|
-
try {
|
|
806
|
-
await discover(result);
|
|
807
|
-
} catch (error) {
|
|
808
|
-
result.errors.push(error instanceof Error ? error.message : "GitLab discovery failed");
|
|
809
|
-
}
|
|
810
|
-
const reporter = createExternalSourcePollReporter(deps.externalSources, result, {
|
|
811
|
-
forwardGeneration: true
|
|
812
|
-
});
|
|
813
|
-
const current = (armed) => [GITLAB_MR_KIND, GITLAB_ISSUE_CANCELLED_KIND].some(
|
|
814
|
-
(kind) => reporter.isCurrent(kind, armed)
|
|
815
|
-
);
|
|
816
|
-
const report = {
|
|
817
|
-
...reporter,
|
|
818
|
-
fire(armed, event, mergeKey) {
|
|
819
|
-
return current(armed) ? reporter.fire(armed, event, mergeKey) : Promise.resolve(false);
|
|
820
|
-
},
|
|
821
|
-
observe(armed, input) {
|
|
822
|
-
if (current(armed)) return reporter.observe(armed, input);
|
|
823
|
-
}
|
|
824
|
-
};
|
|
825
|
-
await report.poll(GITLAB_MR_KIND, async (armed) => {
|
|
826
|
-
const c = armed.resolved;
|
|
827
|
-
if (!c || typeof c.profile !== "string" || !Number.isInteger(c.projectId) || !Number.isInteger(c.iid))
|
|
828
|
-
throw new Error("Invalid GitLab external source");
|
|
829
|
-
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
830
|
-
const previous = schedule.get(key);
|
|
831
|
-
if (previous && previous.at > now()) return;
|
|
832
|
-
try {
|
|
833
|
-
const observation = await observeMergeRequest(
|
|
834
|
-
integration.client(c.profile),
|
|
835
|
-
c.projectId,
|
|
836
|
-
c.iid
|
|
837
|
-
);
|
|
838
|
-
let conflict;
|
|
839
|
-
const client = integration.client(c.profile);
|
|
840
|
-
if (c.delivery && observation.mr.state === "opened" && observation.mr.sha === c.delivery.headSha && (observation.mr.has_conflicts === true || observation.mr.detailed_merge_status === "conflict")) {
|
|
841
|
-
const mr = observation.mr;
|
|
842
|
-
const d = c.delivery;
|
|
843
|
-
if (mr.source_project_id !== c.projectId || mr.target_project_id !== c.projectId || mr.source_branch !== d.headBranch || mr.target_branch !== d.baseBranch)
|
|
844
|
-
throw new Error("GitLab merge request branches changed");
|
|
845
|
-
const base = await client.getBranch(c.projectId, d.baseBranch);
|
|
846
|
-
const evidence = {
|
|
847
|
-
owner: d.owner,
|
|
848
|
-
repo: d.repo,
|
|
849
|
-
prNumber: c.iid,
|
|
850
|
-
headBranch: d.headBranch,
|
|
851
|
-
baseBranch: d.baseBranch,
|
|
852
|
-
headSha: mr.sha,
|
|
853
|
-
baseSha: base.commit.id,
|
|
854
|
-
url: mr.web_url
|
|
855
|
-
};
|
|
856
|
-
if (conflictKey(evidence) !== d.lastConflictKey) conflict = evidence;
|
|
857
|
-
}
|
|
858
|
-
const observedKey = observationKey(observation) + (c.delivery ? `:${conflict ? conflictKey(conflict) : ""}` : "");
|
|
859
|
-
const feedback = c.feedback && observation.mr.state === "opened" ? pendingGitLabFeedback(
|
|
860
|
-
await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
|
|
861
|
-
c.feedback.afterId,
|
|
862
|
-
c.feedback.since
|
|
863
|
-
) : [];
|
|
864
|
-
const feedbackReadyAt = gitLabFeedbackReadyAt(
|
|
865
|
-
feedback,
|
|
866
|
-
c.feedback?.quietPeriodMs ?? 12e4
|
|
867
|
-
);
|
|
868
|
-
const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
|
|
869
|
-
if (c.delivery) {
|
|
870
|
-
const fresh = await client.getMergeRequest(c.projectId, c.iid);
|
|
871
|
-
if (fresh.sha !== observation.mr.sha || fresh.state !== observation.mr.state) return;
|
|
872
|
-
}
|
|
873
|
-
await report.observe(armed, {
|
|
874
|
-
observation: {
|
|
875
|
-
summary: `${observation.mr.state} \xB7 ${observation.pipeline?.status ?? "no current pipeline"}`,
|
|
876
|
-
observedAt: new Date(now()).toISOString(),
|
|
877
|
-
subject: observation.mr.web_url,
|
|
878
|
-
revision: observation.mr.sha
|
|
879
|
-
}
|
|
880
|
-
});
|
|
881
|
-
if (observedKey !== c.afterKey || feedbackReady || c.wakeAt !== void 0 && c.wakeAt <= now())
|
|
882
|
-
await report.fire(
|
|
883
|
-
armed,
|
|
884
|
-
{
|
|
885
|
-
...observation,
|
|
886
|
-
...c.delivery ? {
|
|
887
|
-
observationKey: observedKey,
|
|
888
|
-
feedback: feedbackReady ? feedback : [],
|
|
889
|
-
...conflict ? { conflict } : {}
|
|
890
|
-
} : {}
|
|
891
|
-
},
|
|
892
|
-
`${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`
|
|
893
|
-
);
|
|
894
|
-
schedule.set(key, {
|
|
895
|
-
at: now() + parseDurationMs2(c.pollInterval ?? "30s", 3e4),
|
|
896
|
-
failures: 0
|
|
897
|
-
});
|
|
898
|
-
} catch (error) {
|
|
899
|
-
const failures = (previous?.failures ?? 0) + 1;
|
|
900
|
-
schedule.set(key, {
|
|
901
|
-
at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
|
|
902
|
-
failures
|
|
903
|
-
});
|
|
904
|
-
await report.observe(armed, {
|
|
905
|
-
refreshError: error instanceof Error ? error.message : "GitLab observation unavailable"
|
|
906
|
-
});
|
|
907
|
-
throw error;
|
|
908
|
-
}
|
|
909
|
-
});
|
|
910
|
-
await report.poll(GITLAB_ISSUE_CANCELLED_KIND, async (armed) => {
|
|
911
|
-
const c = armed.resolved;
|
|
912
|
-
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
913
|
-
if ((schedule.get(key)?.at ?? 0) > now()) return;
|
|
914
|
-
const client = integration.client(c.profile);
|
|
915
|
-
const issue = await client.getIssue(c.projectId, c.issueIid);
|
|
916
|
-
if (issue.state !== "opened" || !issue.labels.includes(c.triggerLabel)) {
|
|
917
|
-
const mr = await client.getMergeRequest(c.projectId, c.iid);
|
|
918
|
-
if (mr.state !== "opened") return;
|
|
919
|
-
await report.fire(
|
|
920
|
-
armed,
|
|
921
|
-
{ issue },
|
|
922
|
-
`${issue.iid}:${issue.state}:${issue.labels.includes(c.triggerLabel)}`
|
|
923
|
-
);
|
|
924
|
-
}
|
|
925
|
-
schedule.set(key, {
|
|
926
|
-
at: now() + parseDurationMs2(c.pollInterval ?? "30s", 3e4),
|
|
927
|
-
failures: 0
|
|
928
|
-
});
|
|
929
|
-
});
|
|
930
|
-
return result;
|
|
931
|
-
}
|
|
932
|
-
});
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
// src/setup.ts
|
|
936
|
-
import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
|
|
937
|
-
|
|
938
|
-
// src/delivery-tools.ts
|
|
939
|
-
import { createHash as createHash2 } from "crypto";
|
|
940
|
-
import {
|
|
941
|
-
numberArg as numberArg2,
|
|
942
|
-
projectParameters as projectParameters2,
|
|
943
|
-
stringArg as stringArg2
|
|
944
|
-
} from "@leitwerk-dev/process-sdk";
|
|
945
|
-
function registerGitLabDeliveryTools(api, integration, projects) {
|
|
946
|
-
api.tool({
|
|
947
|
-
name: "gitlab_ensure_merge_request",
|
|
948
|
-
description: "Create or reconcile and pin the process merge request",
|
|
949
|
-
parameters: projectParameters2({ title: { type: "string" }, body: { type: "string" } }, [
|
|
950
|
-
"title",
|
|
951
|
-
"body"
|
|
952
|
-
]),
|
|
953
|
-
async execute(ctx, args) {
|
|
954
|
-
const binding = resolveGitLabRepositoryBinding(ctx);
|
|
955
|
-
const client = integration.client(binding.profile);
|
|
956
|
-
const project = projects.getByInstanceAndKey(ctx.process.id, ctx.project?.key ?? "");
|
|
957
|
-
if (!project?.workBranch || project.workBranch === project.baseBranch)
|
|
958
|
-
throw new Error("A process feature branch is required");
|
|
959
|
-
const workBranch = project.workBranch;
|
|
960
|
-
const identity = {
|
|
961
|
-
writeType: "gitlab.ensure_mr",
|
|
962
|
-
dedupKey: `${binding.projectId}:${project.key}:${workBranch}:${project.baseBranch}`
|
|
963
|
-
};
|
|
964
|
-
const marker = `<!-- leitwerk:gitlab:merge-request:${ctx.process.id}:${project.key} -->`;
|
|
965
|
-
const find = async () => (await client.listBranchMergeRequests(
|
|
966
|
-
binding.projectId,
|
|
967
|
-
workBranch,
|
|
968
|
-
project.baseBranch,
|
|
969
|
-
ctx.signal
|
|
970
|
-
)).find(
|
|
971
|
-
(mr) => mr.source_project_id === binding.projectId && mr.target_project_id === binding.projectId && mr.source_branch === project.workBranch && mr.target_branch === project.baseBranch && mr.description?.includes(marker)
|
|
972
|
-
);
|
|
973
|
-
const request = await ctx.externalWrites.ensure(identity, {
|
|
974
|
-
reconcile: async () => await find() ?? null,
|
|
975
|
-
execute: () => client.createMergeRequest(
|
|
976
|
-
binding.projectId,
|
|
977
|
-
{
|
|
978
|
-
title: stringArg2(args, "title"),
|
|
979
|
-
description: `${stringArg2(args, "body")}
|
|
980
|
-
|
|
981
|
-
${marker}`,
|
|
982
|
-
source_branch: workBranch,
|
|
983
|
-
target_branch: project.baseBranch
|
|
984
|
-
},
|
|
985
|
-
ctx.signal
|
|
986
|
-
),
|
|
987
|
-
toMetadata: (mr) => ({ iid: mr.iid, url: mr.web_url })
|
|
988
|
-
});
|
|
989
|
-
const latest = projects.getByInstanceAndKey(ctx.process.id, project.key);
|
|
990
|
-
if (!latest || latest.workBranch !== project.workBranch || latest.baseBranch !== project.baseBranch)
|
|
991
|
-
throw new Error("Process repository binding changed during publication");
|
|
992
|
-
const metadata = latest.metadata ?? {};
|
|
993
|
-
const previous = metadata.gitlab;
|
|
994
|
-
if (previous.iid && previous.iid !== request.iid)
|
|
995
|
-
throw new Error("Process is already bound to another merge request");
|
|
996
|
-
projects.update(latest.id, {
|
|
997
|
-
metadata: { ...metadata, gitlab: { ...previous, ...binding, iid: request.iid } },
|
|
998
|
-
externalId: String(request.iid),
|
|
999
|
-
externalUrl: request.web_url
|
|
1000
|
-
});
|
|
1001
|
-
return request;
|
|
1002
|
-
}
|
|
1003
|
-
});
|
|
1004
|
-
api.tool({
|
|
1005
|
-
name: "gitlab_list_merge_request_feedback",
|
|
1006
|
-
description: "Read human discussion feedback on the bound merge request",
|
|
1007
|
-
parameters: projectParameters2(),
|
|
1008
|
-
async execute(ctx) {
|
|
1009
|
-
const b = resolveGitLabBinding(ctx);
|
|
1010
|
-
return integration.client(b.profile).listMergeRequestFeedback(b.projectId, b.iid, ctx.signal);
|
|
1011
|
-
}
|
|
1012
|
-
});
|
|
1013
|
-
api.tool({
|
|
1014
|
-
name: "gitlab_acknowledge_feedback",
|
|
1015
|
-
description: "Reconcile the bot's seen reaction on bound merge request feedback",
|
|
1016
|
-
parameters: projectParameters2({ noteId: { type: "integer" } }, ["noteId"]),
|
|
1017
|
-
async execute(ctx, args) {
|
|
1018
|
-
const b = resolveGitLabBinding(ctx);
|
|
1019
|
-
const client = integration.client(b.profile);
|
|
1020
|
-
const noteId = numberArg2(args, "noteId");
|
|
1021
|
-
if (!(await client.listMergeRequestFeedback(b.projectId, b.iid, ctx.signal)).some(
|
|
1022
|
-
(n) => n.id === noteId
|
|
1023
|
-
))
|
|
1024
|
-
throw new Error("Note is not actionable feedback on the bound merge request");
|
|
1025
|
-
await ensureGitLabSeenReaction({
|
|
1026
|
-
client,
|
|
1027
|
-
writes: ctx.externalWrites,
|
|
1028
|
-
instanceId: ctx.process.id,
|
|
1029
|
-
projectId: b.projectId,
|
|
1030
|
-
iid: b.iid,
|
|
1031
|
-
noteId,
|
|
1032
|
-
signal: ctx.signal
|
|
1033
|
-
});
|
|
1034
|
-
return { ok: true };
|
|
1035
|
-
}
|
|
1036
|
-
});
|
|
1037
|
-
for (const name of [
|
|
1038
|
-
"gitlab_get_issue",
|
|
1039
|
-
"gitlab_add_issue_comment",
|
|
1040
|
-
"gitlab_finalize_source_issue"
|
|
1041
|
-
]) {
|
|
1042
|
-
api.tool({
|
|
1043
|
-
name,
|
|
1044
|
-
description: "Read or reconcile the process source issue",
|
|
1045
|
-
parameters: projectParameters2(
|
|
1046
|
-
{
|
|
1047
|
-
issueNumber: { type: "integer" },
|
|
1048
|
-
body: { type: "string" },
|
|
1049
|
-
writeKey: { type: "string" },
|
|
1050
|
-
merged: { type: "boolean" },
|
|
1051
|
-
triggerLabel: { type: "string" },
|
|
1052
|
-
doneLabel: { type: "string" }
|
|
1053
|
-
},
|
|
1054
|
-
["issueNumber"]
|
|
1055
|
-
),
|
|
1056
|
-
async execute(ctx, args) {
|
|
1057
|
-
const b = resolveGitLabRepositoryBinding(ctx);
|
|
1058
|
-
const client = integration.client(b.profile);
|
|
1059
|
-
const iid = numberArg2(args, "issueNumber");
|
|
1060
|
-
const bound = ctx.project?.metadata?.gitlab?.issueIid;
|
|
1061
|
-
if (bound !== iid) throw new Error("Issue does not match the process source issue");
|
|
1062
|
-
if (name === "gitlab_get_issue") return client.getIssue(b.projectId, iid, ctx.signal);
|
|
1063
|
-
const key = stringArg2(args, "writeKey");
|
|
1064
|
-
const digest = createHash2("sha256").update(JSON.stringify([client.baseUrl, b.projectId, iid, ctx.process.id, key])).digest("hex");
|
|
1065
|
-
if (name === "gitlab_add_issue_comment") {
|
|
1066
|
-
const marker = `<!-- leitwerk:gitlab:issue:${digest} -->`;
|
|
1067
|
-
const note = await ctx.externalWrites.ensure(
|
|
1068
|
-
{ writeType: name, dedupKey: digest },
|
|
1069
|
-
{
|
|
1070
|
-
reconcile: async () => (await client.listIssueNotes(b.projectId, iid, ctx.signal)).find(
|
|
1071
|
-
(n) => n.body.includes(marker)
|
|
1072
|
-
) ?? null,
|
|
1073
|
-
execute: () => client.addIssueNote(
|
|
1074
|
-
b.projectId,
|
|
1075
|
-
iid,
|
|
1076
|
-
`${stringArg2(args, "body")}
|
|
1077
|
-
|
|
1078
|
-
${marker}`,
|
|
1079
|
-
ctx.signal
|
|
1080
|
-
),
|
|
1081
|
-
toMetadata: (note2) => ({ noteId: note2.id })
|
|
1082
|
-
}
|
|
1083
|
-
);
|
|
1084
|
-
return { noteId: note.id };
|
|
1085
|
-
}
|
|
1086
|
-
const merged = args.merged === true;
|
|
1087
|
-
const trigger = stringArg2(args, "triggerLabel");
|
|
1088
|
-
const done = stringArg2(args, "doneLabel");
|
|
1089
|
-
if (merged) {
|
|
1090
|
-
await ctx.externalWrites.ensure(
|
|
1091
|
-
{
|
|
1092
|
-
writeType: "gitlab.ensure_label",
|
|
1093
|
-
dedupKey: JSON.stringify([client.baseUrl, b.projectId, done])
|
|
1094
|
-
},
|
|
1095
|
-
{
|
|
1096
|
-
reconcile: async () => (await client.listLabels(b.projectId, ctx.signal)).find((l) => l.name === done) ?? null,
|
|
1097
|
-
execute: () => client.createLabel(b.projectId, done, ctx.signal),
|
|
1098
|
-
toMetadata: (label) => ({ name: label.name })
|
|
1099
|
-
}
|
|
1100
|
-
);
|
|
1101
|
-
}
|
|
1102
|
-
await ctx.externalWrites.ensure(
|
|
1103
|
-
{ writeType: name, dedupKey: digest },
|
|
1104
|
-
{
|
|
1105
|
-
reconcile: async () => {
|
|
1106
|
-
const fresh = await client.getIssue(b.projectId, iid, ctx.signal);
|
|
1107
|
-
return !fresh.labels.includes(trigger) && (!merged || fresh.state === "closed" && fresh.labels.includes(done)) ? fresh : null;
|
|
1108
|
-
},
|
|
1109
|
-
execute: async () => {
|
|
1110
|
-
const issue = await client.getIssue(b.projectId, iid, ctx.signal);
|
|
1111
|
-
const labels = [
|
|
1112
|
-
.../* @__PURE__ */ new Set([
|
|
1113
|
-
...issue.labels.filter((l) => l !== trigger),
|
|
1114
|
-
...merged ? [done] : []
|
|
1115
|
-
])
|
|
1116
|
-
];
|
|
1117
|
-
return client.updateIssue(
|
|
1118
|
-
b.projectId,
|
|
1119
|
-
iid,
|
|
1120
|
-
{ labels: labels.join(","), ...merged ? { state_event: "close" } : {} },
|
|
1121
|
-
ctx.signal
|
|
1122
|
-
);
|
|
1123
|
-
},
|
|
1124
|
-
toMetadata: () => ({ issueIid: iid, merged })
|
|
1125
|
-
}
|
|
1126
|
-
);
|
|
1127
|
-
return { issueIid: iid, merged };
|
|
1128
|
-
}
|
|
1129
|
-
});
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
// src/setup.ts
|
|
1134
|
-
function setupGitLabIntegration(api, integration, options = {}) {
|
|
1135
|
-
api.provide(gitlabIntegration, integration);
|
|
1136
|
-
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
1137
|
-
if (!deps || Array.isArray(deps)) return;
|
|
1138
|
-
registerGitLabTools(api, integration);
|
|
1139
|
-
registerGitLabDeliveryTools(api, integration, deps.projects);
|
|
1140
|
-
return createGitLabProvider(deps, integration, options);
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
export {
|
|
1144
|
-
parseGitLabProfiles,
|
|
1145
|
-
GitLabClient,
|
|
1146
|
-
observeMergeRequest,
|
|
1147
|
-
gitlabIntegration,
|
|
1148
|
-
gitlabRepositoryCredentials,
|
|
1149
|
-
resolveGitLabBinding,
|
|
1150
|
-
ensureGitLabSeenReaction,
|
|
1151
|
-
parseGitLabSelection,
|
|
1152
|
-
selectGitLabProjects,
|
|
1153
|
-
gitlabIssueExternalId,
|
|
1154
|
-
gitlabIssueWatcherSource,
|
|
1155
|
-
GITLAB_MR_KIND,
|
|
1156
|
-
pendingGitLabFeedback,
|
|
1157
|
-
gitLabFeedbackReadyAt,
|
|
1158
|
-
observationKey,
|
|
1159
|
-
gitlabExternal,
|
|
1160
|
-
setupGitLabIntegration
|
|
1161
|
-
};
|
|
1162
|
-
//# sourceMappingURL=chunk-H4JCQNDY.js.map
|