@leitwerk-dev/gitlab 0.0.0-bootstrap.0 → 0.2.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 +39 -1
- package/dist/LICENSE +13 -0
- package/dist/capability.d.ts +10 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/chunk-5GBBPAG5.js +656 -0
- package/dist/chunk-5GBBPAG5.js.map +1 -0
- package/dist/client.d.ts +179 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/external.d.ts +32 -0
- package/dist/external.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -0
- package/dist/merge-request.test-fixture.d.ts +3 -0
- package/dist/merge-request.test-fixture.d.ts.map +1 -0
- package/dist/selection.d.ts +17 -0
- package/dist/selection.d.ts.map +1 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +209 -0
- package/dist/testing.js.map +1 -0
- package/dist/tools.d.ts +33 -0
- package/dist/tools.d.ts.map +1 -0
- package/package.json +54 -14
- package/src/capability.ts +24 -0
- package/src/client.ts +483 -0
- package/src/external.ts +144 -0
- package/src/index.ts +54 -0
- package/src/merge-request.test-fixture.ts +16 -0
- package/src/selection.ts +61 -0
- package/src/testing.ts +239 -0
- package/src/tools.ts +182 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import { asUnknownRecord } from "@leitwerk-dev/domain";
|
|
2
|
+
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
3
|
+
|
|
4
|
+
export interface GitLabProfile {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
token: string;
|
|
7
|
+
gitIdentity?: { name: string; email: string };
|
|
8
|
+
}
|
|
9
|
+
export interface GitLabProject {
|
|
10
|
+
id: number;
|
|
11
|
+
path_with_namespace: string;
|
|
12
|
+
http_url_to_repo: string;
|
|
13
|
+
web_url: string;
|
|
14
|
+
default_branch: string;
|
|
15
|
+
archived?: boolean;
|
|
16
|
+
permissions?: {
|
|
17
|
+
project_access?: { access_level: number } | null;
|
|
18
|
+
group_access?: { access_level: number } | null;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export interface GitLabGroup {
|
|
22
|
+
id: number;
|
|
23
|
+
full_path: string;
|
|
24
|
+
}
|
|
25
|
+
export interface GitLabMergeRequest {
|
|
26
|
+
iid: number;
|
|
27
|
+
project_id: number;
|
|
28
|
+
source_project_id: number;
|
|
29
|
+
target_project_id: number;
|
|
30
|
+
title: string;
|
|
31
|
+
description: string | null;
|
|
32
|
+
state: string;
|
|
33
|
+
labels: string[];
|
|
34
|
+
sha: string;
|
|
35
|
+
source_branch: string;
|
|
36
|
+
target_branch: string;
|
|
37
|
+
web_url: string;
|
|
38
|
+
merge_commit_sha?: string | null;
|
|
39
|
+
diff_refs?: { base_sha: string; head_sha: string; start_sha: string };
|
|
40
|
+
}
|
|
41
|
+
export interface GitLabCommit {
|
|
42
|
+
id: string;
|
|
43
|
+
parent_ids: string[];
|
|
44
|
+
message: string;
|
|
45
|
+
web_url?: string;
|
|
46
|
+
}
|
|
47
|
+
export interface GitLabBranch {
|
|
48
|
+
name: string;
|
|
49
|
+
can_push: boolean;
|
|
50
|
+
protected: boolean;
|
|
51
|
+
commit: GitLabCommit;
|
|
52
|
+
}
|
|
53
|
+
export interface GitLabPipeline {
|
|
54
|
+
id: number;
|
|
55
|
+
project_id: number;
|
|
56
|
+
sha: string;
|
|
57
|
+
ref: string;
|
|
58
|
+
status: string;
|
|
59
|
+
source?: string;
|
|
60
|
+
web_url: string;
|
|
61
|
+
}
|
|
62
|
+
export interface GitLabJob {
|
|
63
|
+
id: number;
|
|
64
|
+
name: string;
|
|
65
|
+
status: string;
|
|
66
|
+
web_url: string;
|
|
67
|
+
failure_reason?: string;
|
|
68
|
+
}
|
|
69
|
+
export interface GitLabDiff {
|
|
70
|
+
old_path: string;
|
|
71
|
+
new_path: string;
|
|
72
|
+
diff: string;
|
|
73
|
+
new_file: boolean;
|
|
74
|
+
deleted_file: boolean;
|
|
75
|
+
renamed_file: boolean;
|
|
76
|
+
}
|
|
77
|
+
export interface GitLabNote {
|
|
78
|
+
id: number;
|
|
79
|
+
body: string;
|
|
80
|
+
}
|
|
81
|
+
export interface GitLabNoteReaction {
|
|
82
|
+
id: number;
|
|
83
|
+
name: string;
|
|
84
|
+
user: { username: string };
|
|
85
|
+
}
|
|
86
|
+
export interface GitLabFeedback {
|
|
87
|
+
id: number;
|
|
88
|
+
discussionId: string;
|
|
89
|
+
body: string;
|
|
90
|
+
author: string;
|
|
91
|
+
createdAt: string;
|
|
92
|
+
path?: string;
|
|
93
|
+
line?: number;
|
|
94
|
+
}
|
|
95
|
+
export interface GitLabDiscussion {
|
|
96
|
+
id: string;
|
|
97
|
+
notes: (GitLabNote & {
|
|
98
|
+
system: boolean;
|
|
99
|
+
created_at: string;
|
|
100
|
+
author: { username: string; bot?: boolean };
|
|
101
|
+
resolved?: boolean;
|
|
102
|
+
position?: { new_path?: string; old_path?: string; new_line?: number; old_line?: number };
|
|
103
|
+
})[];
|
|
104
|
+
}
|
|
105
|
+
export interface GitLabIdentity {
|
|
106
|
+
name: string;
|
|
107
|
+
email: string;
|
|
108
|
+
username: string;
|
|
109
|
+
}
|
|
110
|
+
export interface GitLabObservation {
|
|
111
|
+
mr: GitLabMergeRequest;
|
|
112
|
+
pipeline: GitLabPipeline | null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class GitLabError extends Error {
|
|
116
|
+
constructor(
|
|
117
|
+
readonly status: number,
|
|
118
|
+
readonly retryable: boolean,
|
|
119
|
+
) {
|
|
120
|
+
super(
|
|
121
|
+
`GitLab request failed (${status || "network unavailable"})${retryable ? "; retryable" : "; check profile and project access"}`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export function parseGitLabProfiles(raw: unknown): Map<string, GitLabProfile> {
|
|
126
|
+
const profiles = new Map<string, GitLabProfile>();
|
|
127
|
+
for (const [name, value] of Object.entries(
|
|
128
|
+
asUnknownRecord(asUnknownRecord(raw)?.profiles) ?? {},
|
|
129
|
+
)) {
|
|
130
|
+
const item = asUnknownRecord(value) ?? {};
|
|
131
|
+
const baseUrl = typeof item.base_url === "string" ? item.base_url.replace(/\/+$/, "") : "";
|
|
132
|
+
const url = repositoryHttpsUrl(`${baseUrl}/` === "/" ? "" : `${baseUrl}/repository`);
|
|
133
|
+
if (url.origin !== baseUrl)
|
|
134
|
+
throw new Error(`GitLab profile '${name}' requires an HTTPS origin base_url`);
|
|
135
|
+
const configuredToken = typeof item.token === "string" ? item.token : "";
|
|
136
|
+
const token = configuredToken.startsWith("env:")
|
|
137
|
+
? (process.env[configuredToken.slice(4)] ?? "")
|
|
138
|
+
: configuredToken;
|
|
139
|
+
if (!token || /[\r\n\0]/.test(token))
|
|
140
|
+
throw new Error(`GitLab profile '${name}' requires a token`);
|
|
141
|
+
const identity = asUnknownRecord(item.git_identity);
|
|
142
|
+
if (
|
|
143
|
+
identity &&
|
|
144
|
+
[identity.name, identity.email].some(
|
|
145
|
+
(v) => typeof v !== "string" || !v.trim() || /[\r\n<>]/.test(v),
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
throw new Error(`GitLab profile '${name}' requires a valid git_identity name and email`);
|
|
149
|
+
profiles.set(name, {
|
|
150
|
+
baseUrl,
|
|
151
|
+
token,
|
|
152
|
+
...(identity
|
|
153
|
+
? { gitIdentity: { name: String(identity.name), email: String(identity.email) } }
|
|
154
|
+
: {}),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return profiles;
|
|
158
|
+
}
|
|
159
|
+
const projectPath = (id: number | string) => `/projects/${encodeURIComponent(id)}`;
|
|
160
|
+
const mrPath = (id: number, iid: number) => `${projectPath(id)}/merge_requests/${iid}`;
|
|
161
|
+
|
|
162
|
+
/** GitLab v4 API. Errors deliberately omit response bodies, headers and tokens. */
|
|
163
|
+
export class GitLabClient {
|
|
164
|
+
readonly baseUrl: string;
|
|
165
|
+
readonly #profile: GitLabProfile;
|
|
166
|
+
readonly #fetch: typeof fetch;
|
|
167
|
+
readonly #sleep: (ms: number) => Promise<unknown>;
|
|
168
|
+
constructor(
|
|
169
|
+
profile: GitLabProfile,
|
|
170
|
+
options: { fetch?: typeof fetch; sleep?: (ms: number) => Promise<unknown> } = {},
|
|
171
|
+
) {
|
|
172
|
+
if (repositoryHttpsUrl(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
|
|
173
|
+
throw new Error("GitLab requires an HTTPS origin baseUrl");
|
|
174
|
+
if (!profile.token || /[\r\n\0]/.test(profile.token))
|
|
175
|
+
throw new Error("GitLab requires a valid token");
|
|
176
|
+
this.#profile = profile;
|
|
177
|
+
this.baseUrl = profile.baseUrl;
|
|
178
|
+
this.#fetch = options.fetch ?? fetch;
|
|
179
|
+
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
180
|
+
}
|
|
181
|
+
private async response(path: string, signal?: AbortSignal, body?: unknown): Promise<Response> {
|
|
182
|
+
for (let attempt = 0; ; attempt++) {
|
|
183
|
+
let response: Response;
|
|
184
|
+
try {
|
|
185
|
+
response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
|
|
186
|
+
method: body === undefined ? "GET" : "POST",
|
|
187
|
+
redirect: "error",
|
|
188
|
+
headers: {
|
|
189
|
+
"PRIVATE-TOKEN": this.#profile.token,
|
|
190
|
+
Accept: "application/json",
|
|
191
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
192
|
+
},
|
|
193
|
+
signal: signal
|
|
194
|
+
? AbortSignal.any([signal, AbortSignal.timeout(30_000)])
|
|
195
|
+
: AbortSignal.timeout(30_000),
|
|
196
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
197
|
+
});
|
|
198
|
+
} catch {
|
|
199
|
+
if (signal?.aborted) throw new GitLabError(0, true);
|
|
200
|
+
if (body !== undefined || attempt >= 2) throw new GitLabError(0, true);
|
|
201
|
+
await this.#sleep(1_000 * 2 ** attempt);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (response.ok) return response;
|
|
205
|
+
const retryable =
|
|
206
|
+
response.status === 429 || response.status >= 500 || response.status === 408;
|
|
207
|
+
await response.body?.cancel();
|
|
208
|
+
if (!retryable || body !== undefined || attempt >= 2)
|
|
209
|
+
throw new GitLabError(response.status, retryable);
|
|
210
|
+
const seconds = Number(response.headers.get("retry-after"));
|
|
211
|
+
await this.#sleep(Math.min(30_000, seconds > 0 ? seconds * 1_000 : 1_000 * 2 ** attempt));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
private async request<T>(path: string, signal?: AbortSignal, body?: unknown): Promise<T> {
|
|
215
|
+
return this.json<T>(await this.response(path, signal, body));
|
|
216
|
+
}
|
|
217
|
+
private async json<T>(response: Response): Promise<T> {
|
|
218
|
+
try {
|
|
219
|
+
return (await response.json()) as T;
|
|
220
|
+
} catch {
|
|
221
|
+
throw new GitLabError(502, true);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
private async pages<T>(path: string, signal?: AbortSignal): Promise<T[]> {
|
|
225
|
+
const rows: T[] = [];
|
|
226
|
+
let page = 1;
|
|
227
|
+
for (let n = 0; n < 10_000; n++) {
|
|
228
|
+
const response = await this.response(
|
|
229
|
+
`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
|
|
230
|
+
signal,
|
|
231
|
+
);
|
|
232
|
+
const batch = await this.json<T[]>(response);
|
|
233
|
+
if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
|
|
234
|
+
rows.push(...batch);
|
|
235
|
+
const next = response.headers.get("x-next-page");
|
|
236
|
+
if (next === "" || (next === null && batch.length < 100)) return rows;
|
|
237
|
+
const nextPage = next === null ? page + 1 : Number(next);
|
|
238
|
+
if (!Number.isInteger(nextPage) || nextPage <= page)
|
|
239
|
+
throw new Error("Invalid GitLab pagination");
|
|
240
|
+
page = nextPage;
|
|
241
|
+
}
|
|
242
|
+
throw new Error("GitLab pagination limit exceeded; discovery incomplete");
|
|
243
|
+
}
|
|
244
|
+
getProject(id: number | string, signal?: AbortSignal): Promise<GitLabProject> {
|
|
245
|
+
return this.request(projectPath(id), signal);
|
|
246
|
+
}
|
|
247
|
+
listProjects(signal?: AbortSignal): Promise<GitLabProject[]> {
|
|
248
|
+
return this.pages("/projects?archived=false", signal);
|
|
249
|
+
}
|
|
250
|
+
getGroup(id: number | string, signal?: AbortSignal): Promise<GitLabGroup> {
|
|
251
|
+
return this.request(`/groups/${encodeURIComponent(id)}`, signal);
|
|
252
|
+
}
|
|
253
|
+
listGroupProjects(id: number | string, signal?: AbortSignal): Promise<GitLabProject[]> {
|
|
254
|
+
return this.pages(
|
|
255
|
+
`/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
|
|
256
|
+
signal,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
listMergeRequests(
|
|
260
|
+
id: number,
|
|
261
|
+
label: string,
|
|
262
|
+
signal?: AbortSignal,
|
|
263
|
+
): Promise<GitLabMergeRequest[]> {
|
|
264
|
+
return this.pages(
|
|
265
|
+
`${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
|
|
266
|
+
signal,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
getMergeRequest(id: number, iid: number, signal?: AbortSignal): Promise<GitLabMergeRequest> {
|
|
270
|
+
return this.request(mrPath(id, iid), signal);
|
|
271
|
+
}
|
|
272
|
+
getChanges(id: number, iid: number, signal?: AbortSignal): Promise<GitLabDiff[]> {
|
|
273
|
+
return this.pages(`${mrPath(id, iid)}/diffs`, signal);
|
|
274
|
+
}
|
|
275
|
+
getBranch(id: number, branch: string, signal?: AbortSignal): Promise<GitLabBranch> {
|
|
276
|
+
return this.request(
|
|
277
|
+
`${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
|
|
278
|
+
signal,
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
getCommit(id: number, sha: string, signal?: AbortSignal): Promise<GitLabCommit> {
|
|
282
|
+
return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
|
|
283
|
+
}
|
|
284
|
+
listMergeRequestPipelines(
|
|
285
|
+
id: number,
|
|
286
|
+
iid: number,
|
|
287
|
+
signal?: AbortSignal,
|
|
288
|
+
): Promise<GitLabPipeline[]> {
|
|
289
|
+
return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
|
|
290
|
+
}
|
|
291
|
+
listBranchPipelines(
|
|
292
|
+
id: number,
|
|
293
|
+
branch: string,
|
|
294
|
+
sha: string,
|
|
295
|
+
signal?: AbortSignal,
|
|
296
|
+
): Promise<GitLabPipeline[]> {
|
|
297
|
+
return this.pages(
|
|
298
|
+
`${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
|
|
299
|
+
signal,
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
getPipeline(id: number, pipeline: number, signal?: AbortSignal): Promise<GitLabPipeline> {
|
|
303
|
+
return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
|
|
304
|
+
}
|
|
305
|
+
listFailedJobs(id: number, pipeline: number, signal?: AbortSignal): Promise<GitLabJob[]> {
|
|
306
|
+
return this.pages(
|
|
307
|
+
`${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
|
|
308
|
+
signal,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
listNotes(id: number, iid: number, signal?: AbortSignal): Promise<GitLabNote[]> {
|
|
312
|
+
return this.pages(`${mrPath(id, iid)}/notes`, signal);
|
|
313
|
+
}
|
|
314
|
+
getDiscussion(
|
|
315
|
+
id: number,
|
|
316
|
+
iid: number,
|
|
317
|
+
discussionId: string,
|
|
318
|
+
signal?: AbortSignal,
|
|
319
|
+
): Promise<GitLabDiscussion> {
|
|
320
|
+
return this.request(
|
|
321
|
+
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
|
|
322
|
+
signal,
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
replyToDiscussion(
|
|
326
|
+
id: number,
|
|
327
|
+
iid: number,
|
|
328
|
+
discussionId: string,
|
|
329
|
+
body: string,
|
|
330
|
+
signal?: AbortSignal,
|
|
331
|
+
): Promise<GitLabNote> {
|
|
332
|
+
return this.request(
|
|
333
|
+
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
|
|
334
|
+
signal,
|
|
335
|
+
{ body },
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
listNoteReactions(
|
|
339
|
+
id: number,
|
|
340
|
+
iid: number,
|
|
341
|
+
noteId: number,
|
|
342
|
+
signal?: AbortSignal,
|
|
343
|
+
): Promise<GitLabNoteReaction[]> {
|
|
344
|
+
return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
|
|
345
|
+
}
|
|
346
|
+
addNoteReaction(
|
|
347
|
+
id: number,
|
|
348
|
+
iid: number,
|
|
349
|
+
noteId: number,
|
|
350
|
+
name: string,
|
|
351
|
+
signal?: AbortSignal,
|
|
352
|
+
): Promise<GitLabNoteReaction> {
|
|
353
|
+
return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
|
|
354
|
+
}
|
|
355
|
+
async listMergeRequestFeedback(
|
|
356
|
+
id: number,
|
|
357
|
+
iid: number,
|
|
358
|
+
signal?: AbortSignal,
|
|
359
|
+
): Promise<GitLabFeedback[]> {
|
|
360
|
+
const [discussions, identity] = await Promise.all([
|
|
361
|
+
this.pages<GitLabDiscussion>(`${mrPath(id, iid)}/discussions`, signal),
|
|
362
|
+
this.resolveGitIdentity(signal),
|
|
363
|
+
]);
|
|
364
|
+
const feedback: GitLabFeedback[] = [];
|
|
365
|
+
for (const discussion of discussions) {
|
|
366
|
+
for (const note of discussion.notes) {
|
|
367
|
+
if (
|
|
368
|
+
note.system ||
|
|
369
|
+
note.resolved ||
|
|
370
|
+
note.author.bot ||
|
|
371
|
+
note.author.username === identity.username ||
|
|
372
|
+
!note.body.trim() ||
|
|
373
|
+
!Number.isFinite(Date.parse(note.created_at))
|
|
374
|
+
)
|
|
375
|
+
continue;
|
|
376
|
+
const position = note.position ?? discussion.notes[0]?.position;
|
|
377
|
+
feedback.push({
|
|
378
|
+
id: note.id,
|
|
379
|
+
discussionId: discussion.id,
|
|
380
|
+
body: note.body,
|
|
381
|
+
author: note.author.username,
|
|
382
|
+
createdAt: note.created_at,
|
|
383
|
+
...(position
|
|
384
|
+
? {
|
|
385
|
+
path: position.new_path ?? position.old_path,
|
|
386
|
+
line: position.new_line ?? position.old_line,
|
|
387
|
+
}
|
|
388
|
+
: {}),
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return feedback.sort((a, b) => a.id - b.id);
|
|
393
|
+
}
|
|
394
|
+
addNote(id: number, iid: number, body: string, signal?: AbortSignal): Promise<GitLabNote> {
|
|
395
|
+
return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
|
|
396
|
+
}
|
|
397
|
+
async resolveGitIdentity(signal?: AbortSignal): Promise<GitLabIdentity> {
|
|
398
|
+
const user = await this.request<{
|
|
399
|
+
name?: string;
|
|
400
|
+
username?: string;
|
|
401
|
+
email?: string;
|
|
402
|
+
commit_email?: string;
|
|
403
|
+
}>("/user", signal);
|
|
404
|
+
const name = this.#profile.gitIdentity?.name ?? user.name;
|
|
405
|
+
const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
|
|
406
|
+
if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
|
|
407
|
+
throw new Error(
|
|
408
|
+
"GitLab bot Git identity is unavailable; configure git_identity on the profile",
|
|
409
|
+
);
|
|
410
|
+
return { name, email, username: user.username };
|
|
411
|
+
}
|
|
412
|
+
async getJobTrace(
|
|
413
|
+
id: number,
|
|
414
|
+
job: number,
|
|
415
|
+
maxBytes = 65_536,
|
|
416
|
+
signal?: AbortSignal,
|
|
417
|
+
): Promise<{ text: string; truncated: boolean }> {
|
|
418
|
+
const limit = Math.min(262_144, Math.max(1, Math.floor(maxBytes) || 65_536));
|
|
419
|
+
const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
|
|
420
|
+
const reader = response.body?.getReader();
|
|
421
|
+
if (!reader) return { text: "", truncated: false };
|
|
422
|
+
const chunks: Uint8Array[] = [];
|
|
423
|
+
let size = 0;
|
|
424
|
+
let truncated = false;
|
|
425
|
+
try {
|
|
426
|
+
while (true) {
|
|
427
|
+
const item = await reader.read();
|
|
428
|
+
if (item.done) break;
|
|
429
|
+
const take = Math.min(item.value.length, limit - size);
|
|
430
|
+
chunks.push(item.value.slice(0, take));
|
|
431
|
+
size += take;
|
|
432
|
+
if (size >= limit) {
|
|
433
|
+
truncated = true;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
} finally {
|
|
438
|
+
await reader.cancel();
|
|
439
|
+
}
|
|
440
|
+
return { text: Buffer.concat(chunks).toString("utf8"), truncated };
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
export type GitLabClientLike = Pick<GitLabClient, keyof GitLabClient>;
|
|
444
|
+
|
|
445
|
+
/** A pending current pipeline supersedes every older result. Synthetic merges must contain this source head. */
|
|
446
|
+
export async function observeMergeRequest(
|
|
447
|
+
client: GitLabClientLike,
|
|
448
|
+
projectId: number,
|
|
449
|
+
iid: number,
|
|
450
|
+
signal?: AbortSignal,
|
|
451
|
+
): Promise<GitLabObservation> {
|
|
452
|
+
const mr = await client.getMergeRequest(projectId, iid, signal);
|
|
453
|
+
if (mr.state !== "opened") return { mr, pipeline: null };
|
|
454
|
+
const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
|
|
455
|
+
(a, b) => b.id - a.id,
|
|
456
|
+
);
|
|
457
|
+
for (const candidate of associated) {
|
|
458
|
+
const id = candidate.project_id ?? projectId;
|
|
459
|
+
let matches = candidate.sha === mr.sha;
|
|
460
|
+
if (
|
|
461
|
+
!matches &&
|
|
462
|
+
(candidate.ref === `refs/merge-requests/${iid}/merge` ||
|
|
463
|
+
candidate.sha === mr.merge_commit_sha)
|
|
464
|
+
) {
|
|
465
|
+
const commit = await client.getCommit(id, candidate.sha, signal);
|
|
466
|
+
matches = commit.parent_ids.includes(mr.sha);
|
|
467
|
+
}
|
|
468
|
+
if (matches) return { mr, pipeline: await client.getPipeline(id, candidate.id, signal) };
|
|
469
|
+
}
|
|
470
|
+
const candidates = await client.listBranchPipelines(
|
|
471
|
+
mr.source_project_id,
|
|
472
|
+
mr.source_branch,
|
|
473
|
+
mr.sha,
|
|
474
|
+
signal,
|
|
475
|
+
);
|
|
476
|
+
const latest = candidates
|
|
477
|
+
.filter((p) => p.sha === mr.sha && p.ref === mr.source_branch && p.source === "push")
|
|
478
|
+
.sort((a, b) => b.id - a.id)[0];
|
|
479
|
+
return {
|
|
480
|
+
mr,
|
|
481
|
+
pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null,
|
|
482
|
+
};
|
|
483
|
+
}
|
package/src/external.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type CoreServerSetupDeps,
|
|
3
|
+
createExternalSourcePollReporter,
|
|
4
|
+
type ExternalActionSource,
|
|
5
|
+
} from "@leitwerk-dev/process-sdk";
|
|
6
|
+
import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
|
|
7
|
+
import type { GitLabIntegration } from "./capability.js";
|
|
8
|
+
import { type GitLabFeedback, type GitLabObservation, observeMergeRequest } from "./client.js";
|
|
9
|
+
export const GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
|
|
10
|
+
export interface GitLabSourceConfig {
|
|
11
|
+
profile: string;
|
|
12
|
+
projectId: number;
|
|
13
|
+
iid: number;
|
|
14
|
+
pollInterval?: string;
|
|
15
|
+
afterKey?: string;
|
|
16
|
+
/** Optional timer also wakes retry work when GitLab facts have not changed. */
|
|
17
|
+
wakeAt?: number;
|
|
18
|
+
feedback?: { afterId: number; since?: string; quietPeriodMs: number };
|
|
19
|
+
}
|
|
20
|
+
/** A trailing quiet period survives restarts because it uses the newest unseen note's timestamp. */
|
|
21
|
+
export function pendingGitLabFeedback(
|
|
22
|
+
items: GitLabFeedback[],
|
|
23
|
+
afterId: number,
|
|
24
|
+
since?: string,
|
|
25
|
+
): GitLabFeedback[] {
|
|
26
|
+
const start = since ? Date.parse(since) : 0;
|
|
27
|
+
return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
|
|
28
|
+
}
|
|
29
|
+
export function gitLabFeedbackReadyAt(
|
|
30
|
+
items: GitLabFeedback[],
|
|
31
|
+
quietPeriodMs: number,
|
|
32
|
+
): number | null {
|
|
33
|
+
return items.length
|
|
34
|
+
? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs
|
|
35
|
+
: null;
|
|
36
|
+
}
|
|
37
|
+
export const observationKey = ({ mr, pipeline }: GitLabObservation): string =>
|
|
38
|
+
JSON.stringify([
|
|
39
|
+
mr.state,
|
|
40
|
+
mr.sha,
|
|
41
|
+
[...mr.labels].sort(),
|
|
42
|
+
pipeline?.project_id,
|
|
43
|
+
pipeline?.id,
|
|
44
|
+
pipeline?.status,
|
|
45
|
+
]);
|
|
46
|
+
export const gitlabExternal = {
|
|
47
|
+
mergeRequest<P, S>(
|
|
48
|
+
resolve: (ctx: { params: P; state: S }) => GitLabSourceConfig,
|
|
49
|
+
): ExternalActionSource<P, S, GitLabObservation> {
|
|
50
|
+
return {
|
|
51
|
+
kind: GITLAB_MR_KIND,
|
|
52
|
+
label: "GitLab merge request",
|
|
53
|
+
description: "Observe MR state, current source head and revision-correlated CI",
|
|
54
|
+
config: {},
|
|
55
|
+
inputMode: "none",
|
|
56
|
+
resolve,
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
export function createGitLabProvider(
|
|
61
|
+
deps: CoreServerSetupDeps,
|
|
62
|
+
integration: GitLabIntegration,
|
|
63
|
+
options: { now?: () => number } = {},
|
|
64
|
+
) {
|
|
65
|
+
const schedule = new Map<string, { at: number; failures: number }>();
|
|
66
|
+
const now = options.now ?? Date.now;
|
|
67
|
+
return deps.polling.create({
|
|
68
|
+
id: "gitlab",
|
|
69
|
+
pollInterval: () => "5s",
|
|
70
|
+
isEnabled: () => true,
|
|
71
|
+
defaultIntervalMs: 5000,
|
|
72
|
+
async pollOnce() {
|
|
73
|
+
const result = emptyPollResult();
|
|
74
|
+
const report = createExternalSourcePollReporter(deps.externalSources, result);
|
|
75
|
+
await report.poll(GITLAB_MR_KIND, async (armed) => {
|
|
76
|
+
const c = armed.resolved as unknown as GitLabSourceConfig;
|
|
77
|
+
if (
|
|
78
|
+
!c ||
|
|
79
|
+
typeof c.profile !== "string" ||
|
|
80
|
+
!Number.isInteger(c.projectId) ||
|
|
81
|
+
!Number.isInteger(c.iid)
|
|
82
|
+
)
|
|
83
|
+
throw new Error("Invalid GitLab external source");
|
|
84
|
+
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
85
|
+
const previous = schedule.get(key);
|
|
86
|
+
if (previous && previous.at > now()) return;
|
|
87
|
+
try {
|
|
88
|
+
const observation = await observeMergeRequest(
|
|
89
|
+
integration.client(c.profile),
|
|
90
|
+
c.projectId,
|
|
91
|
+
c.iid,
|
|
92
|
+
);
|
|
93
|
+
const observedKey = observationKey(observation);
|
|
94
|
+
const feedback =
|
|
95
|
+
c.feedback && observation.mr.state === "opened"
|
|
96
|
+
? pendingGitLabFeedback(
|
|
97
|
+
await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
|
|
98
|
+
c.feedback.afterId,
|
|
99
|
+
c.feedback.since,
|
|
100
|
+
)
|
|
101
|
+
: [];
|
|
102
|
+
const feedbackReadyAt = gitLabFeedbackReadyAt(
|
|
103
|
+
feedback,
|
|
104
|
+
c.feedback?.quietPeriodMs ?? 120_000,
|
|
105
|
+
);
|
|
106
|
+
const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
|
|
107
|
+
await report.observe(armed, {
|
|
108
|
+
observation: {
|
|
109
|
+
summary: `${observation.mr.state} · ${observation.pipeline?.status ?? "no current pipeline"}`,
|
|
110
|
+
observedAt: new Date(now()).toISOString(),
|
|
111
|
+
subject: observation.mr.web_url,
|
|
112
|
+
revision: observation.mr.sha,
|
|
113
|
+
},
|
|
114
|
+
});
|
|
115
|
+
if (
|
|
116
|
+
observedKey !== c.afterKey ||
|
|
117
|
+
feedbackReady ||
|
|
118
|
+
(c.wakeAt !== undefined && c.wakeAt <= now())
|
|
119
|
+
)
|
|
120
|
+
await report.fire(
|
|
121
|
+
armed,
|
|
122
|
+
{ ...observation },
|
|
123
|
+
`${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`,
|
|
124
|
+
);
|
|
125
|
+
schedule.set(key, {
|
|
126
|
+
at: now() + parseDurationMs(c.pollInterval ?? "30s", 30000),
|
|
127
|
+
failures: 0,
|
|
128
|
+
});
|
|
129
|
+
} catch (error) {
|
|
130
|
+
const failures = (previous?.failures ?? 0) + 1;
|
|
131
|
+
schedule.set(key, {
|
|
132
|
+
at: now() + Math.min(300000, 30000 * 2 ** Math.min(failures - 1, 4)),
|
|
133
|
+
failures,
|
|
134
|
+
});
|
|
135
|
+
await report.observe(armed, {
|
|
136
|
+
refreshError: error instanceof Error ? error.message : "GitLab observation unavailable",
|
|
137
|
+
});
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
return result;
|
|
142
|
+
},
|
|
143
|
+
});
|
|
144
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ExternalWriteLogRepoLike } from "@leitwerk-dev/external-writes";
|
|
2
|
+
import {
|
|
3
|
+
coreHostCapabilities,
|
|
4
|
+
type LeitwerkExtensionModule,
|
|
5
|
+
type ServerExtensionAPI,
|
|
6
|
+
} from "@leitwerk-dev/process-sdk";
|
|
7
|
+
import { type GitLabIntegration, gitlabIntegration } from "./capability.js";
|
|
8
|
+
import { GitLabClient, parseGitLabProfiles } from "./client.js";
|
|
9
|
+
import { createGitLabProvider } from "./external.js";
|
|
10
|
+
import { registerGitLabTools } from "./tools.js";
|
|
11
|
+
export const manifest = { id: "gitlab", version: "0.1.9" } as const;
|
|
12
|
+
export function setupGitLabIntegration(
|
|
13
|
+
api: ServerExtensionAPI,
|
|
14
|
+
integration: GitLabIntegration,
|
|
15
|
+
options: { now?: () => number } = {},
|
|
16
|
+
) {
|
|
17
|
+
api.provide(gitlabIntegration, integration);
|
|
18
|
+
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
19
|
+
if (!deps || Array.isArray(deps)) return;
|
|
20
|
+
registerGitLabTools(api, integration, deps.externalWrites as ExternalWriteLogRepoLike);
|
|
21
|
+
return createGitLabProvider(deps, integration, options);
|
|
22
|
+
}
|
|
23
|
+
const extension: LeitwerkExtensionModule = {
|
|
24
|
+
manifest,
|
|
25
|
+
setupServer(api, config) {
|
|
26
|
+
const profiles = parseGitLabProfiles(config);
|
|
27
|
+
const clients = new Map([...profiles].map(([id, profile]) => [id, new GitLabClient(profile)]));
|
|
28
|
+
setupGitLabIntegration(api, {
|
|
29
|
+
profiles: () => [...profiles.keys()],
|
|
30
|
+
client: (profile) => {
|
|
31
|
+
const client = clients.get(profile);
|
|
32
|
+
if (!client) throw new Error(`Unknown GitLab profile '${profile}'`);
|
|
33
|
+
return client;
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
37
|
+
if (!deps || Array.isArray(deps)) return;
|
|
38
|
+
deps.repositoryCredentials.register({
|
|
39
|
+
kind: "git_https",
|
|
40
|
+
resolve(ref) {
|
|
41
|
+
const profile = ref.startsWith("gitlab:") ? profiles.get(ref.slice(7)) : undefined;
|
|
42
|
+
return profile
|
|
43
|
+
? { origin: profile.baseUrl, username: "oauth2", password: profile.token }
|
|
44
|
+
: null;
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
export default extension;
|
|
50
|
+
export * from "./capability.js";
|
|
51
|
+
export * from "./client.js";
|
|
52
|
+
export * from "./external.js";
|
|
53
|
+
export * from "./selection.js";
|
|
54
|
+
export * from "./tools.js";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { GitLabMergeRequest } from "./client.js";
|
|
2
|
+
|
|
3
|
+
export const mr: GitLabMergeRequest = {
|
|
4
|
+
iid: 1,
|
|
5
|
+
project_id: 7,
|
|
6
|
+
source_project_id: 7,
|
|
7
|
+
target_project_id: 7,
|
|
8
|
+
title: "Upgrade",
|
|
9
|
+
description: null,
|
|
10
|
+
state: "opened",
|
|
11
|
+
labels: ["renovate"],
|
|
12
|
+
sha: "head",
|
|
13
|
+
source_branch: "renovate/dependency",
|
|
14
|
+
target_branch: "main",
|
|
15
|
+
web_url: "https://forge.test/a/-/merge_requests/1",
|
|
16
|
+
};
|