@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/selection.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { GitLabClientLike, GitLabProject } from "./client.js";
|
|
2
|
+
export interface GitLabSelection {
|
|
3
|
+
projects: { include: readonly string[]; exclude: readonly string[] };
|
|
4
|
+
groups: { include: readonly string[]; exclude: readonly string[] };
|
|
5
|
+
allAccessible: boolean;
|
|
6
|
+
}
|
|
7
|
+
export function parseGitLabSelection(raw: Record<string, unknown>): GitLabSelection {
|
|
8
|
+
const list = (value: unknown): string[] => {
|
|
9
|
+
if (value === undefined) return [];
|
|
10
|
+
if (
|
|
11
|
+
!Array.isArray(value) ||
|
|
12
|
+
value.some(
|
|
13
|
+
(v) =>
|
|
14
|
+
typeof v !== "string" ||
|
|
15
|
+
!/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(v) ||
|
|
16
|
+
v.split("/").some((p: string) => p === "." || p === ".."),
|
|
17
|
+
)
|
|
18
|
+
)
|
|
19
|
+
throw new Error("GitLab selectors require exact namespace paths");
|
|
20
|
+
return [...new Set(value as string[])];
|
|
21
|
+
};
|
|
22
|
+
const pair = (value: unknown) => {
|
|
23
|
+
if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value)))
|
|
24
|
+
throw new Error("GitLab selectors must be objects");
|
|
25
|
+
const item = value as Record<string, unknown> | undefined;
|
|
26
|
+
return { include: list(item?.include), exclude: list(item?.exclude) };
|
|
27
|
+
};
|
|
28
|
+
if (raw.all_accessible !== undefined && typeof raw.all_accessible !== "boolean")
|
|
29
|
+
throw new Error("all_accessible must be a boolean");
|
|
30
|
+
const parsed = {
|
|
31
|
+
projects: pair(raw.projects),
|
|
32
|
+
groups: pair(raw.groups),
|
|
33
|
+
allAccessible: raw.all_accessible === true,
|
|
34
|
+
};
|
|
35
|
+
if (!parsed.allAccessible && !parsed.projects.include.length && !parsed.groups.include.length)
|
|
36
|
+
throw new Error("GitLab requires explicit project/group includes or all_accessible: true");
|
|
37
|
+
return parsed;
|
|
38
|
+
}
|
|
39
|
+
export function projectExcluded(selection: GitLabSelection, name: string): boolean {
|
|
40
|
+
return (
|
|
41
|
+
selection.projects.exclude.includes(name) ||
|
|
42
|
+
selection.groups.exclude.some((group) => name.startsWith(`${group}/`))
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
/** Include union, subgroup expansion, exclusion precedence, stable-ID deduplication. */
|
|
46
|
+
export async function selectGitLabProjects(
|
|
47
|
+
client: GitLabClientLike,
|
|
48
|
+
selection: GitLabSelection,
|
|
49
|
+
): Promise<GitLabProject[]> {
|
|
50
|
+
const candidates: GitLabProject[] = selection.allAccessible ? await client.listProjects() : [];
|
|
51
|
+
for (const name of selection.projects.include) candidates.push(await client.getProject(name));
|
|
52
|
+
for (const group of selection.groups.include)
|
|
53
|
+
candidates.push(...(await client.listGroupProjects(group)));
|
|
54
|
+
return [
|
|
55
|
+
...new Map(
|
|
56
|
+
candidates
|
|
57
|
+
.filter((p) => !p.archived && !projectExcluded(selection, p.path_with_namespace))
|
|
58
|
+
.map((p) => [p.id, p]),
|
|
59
|
+
).values(),
|
|
60
|
+
];
|
|
61
|
+
}
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import type {
|
|
5
|
+
GitLabClientLike,
|
|
6
|
+
GitLabDiff,
|
|
7
|
+
GitLabFeedback,
|
|
8
|
+
GitLabMergeRequest,
|
|
9
|
+
GitLabNote,
|
|
10
|
+
GitLabNoteReaction,
|
|
11
|
+
GitLabPipeline,
|
|
12
|
+
GitLabProject,
|
|
13
|
+
} from "./client.js";
|
|
14
|
+
|
|
15
|
+
export type {
|
|
16
|
+
GitLabClientLike,
|
|
17
|
+
GitLabMergeRequest,
|
|
18
|
+
GitLabPipeline,
|
|
19
|
+
GitLabProject,
|
|
20
|
+
} from "./client.js";
|
|
21
|
+
export { setupGitLabIntegration } from "./index.js";
|
|
22
|
+
|
|
23
|
+
interface LocalState {
|
|
24
|
+
projects: GitLabProject[];
|
|
25
|
+
mrs: GitLabMergeRequest[];
|
|
26
|
+
pipelines: GitLabPipeline[];
|
|
27
|
+
notes: Record<string, GitLabNote[]>;
|
|
28
|
+
diffs: Record<string, GitLabDiff[]>;
|
|
29
|
+
feedback?: Record<string, GitLabFeedback[]>;
|
|
30
|
+
discussionNotes?: Record<string, GitLabNote[]>;
|
|
31
|
+
reactions?: Record<string, GitLabNoteReaction[]>;
|
|
32
|
+
}
|
|
33
|
+
/** Persistent GitLab test boundary. Repository URLs use local Git's file transport. */
|
|
34
|
+
export class LocalGitLabAdapter {
|
|
35
|
+
state: LocalState;
|
|
36
|
+
loseNextCommentResponse = false;
|
|
37
|
+
loseNextReplyResponse = false;
|
|
38
|
+
loseNextReactionResponse = false;
|
|
39
|
+
constructor(
|
|
40
|
+
readonly root: string,
|
|
41
|
+
readonly baseUrl = "https://gitlab.test",
|
|
42
|
+
) {
|
|
43
|
+
mkdirSync(root, { recursive: true });
|
|
44
|
+
const file = path.join(root, "gitlab.json");
|
|
45
|
+
this.state = existsSync(file)
|
|
46
|
+
? JSON.parse(readFileSync(file, "utf8"))
|
|
47
|
+
: { projects: [], mrs: [], pipelines: [], notes: {}, diffs: {} };
|
|
48
|
+
}
|
|
49
|
+
save() {
|
|
50
|
+
writeFileSync(path.join(this.root, "gitlab.json"), JSON.stringify(this.state), { mode: 0o600 });
|
|
51
|
+
}
|
|
52
|
+
private append<T>(items: T[], item: T, kind: "Comment" | "Reply" | "Reaction"): T {
|
|
53
|
+
items.push(item);
|
|
54
|
+
this.save();
|
|
55
|
+
const flag = `loseNext${kind}Response` as const;
|
|
56
|
+
if (this[flag]) {
|
|
57
|
+
this[flag] = false;
|
|
58
|
+
const action = {
|
|
59
|
+
Comment: "comment write",
|
|
60
|
+
Reply: "discussion reply",
|
|
61
|
+
Reaction: "reaction write",
|
|
62
|
+
};
|
|
63
|
+
throw new Error(`Response lost after ${action[kind]}`);
|
|
64
|
+
}
|
|
65
|
+
return item;
|
|
66
|
+
}
|
|
67
|
+
private project(id: number | string) {
|
|
68
|
+
const p = this.state.projects.find((p) => p.id === id || p.path_with_namespace === id);
|
|
69
|
+
if (!p) throw new Error("Unknown test project");
|
|
70
|
+
return p;
|
|
71
|
+
}
|
|
72
|
+
private git(id: number, args: string[]) {
|
|
73
|
+
return execFileSync(
|
|
74
|
+
"git",
|
|
75
|
+
["-c", "core.hooksPath=/dev/null", "--git-dir", this.project(id).http_url_to_repo, ...args],
|
|
76
|
+
{ encoding: "utf8" },
|
|
77
|
+
).trim();
|
|
78
|
+
}
|
|
79
|
+
addProject(name: string, bare: string): GitLabProject {
|
|
80
|
+
const project: GitLabProject = {
|
|
81
|
+
id: this.state.projects.length + 1,
|
|
82
|
+
path_with_namespace: name,
|
|
83
|
+
http_url_to_repo: bare,
|
|
84
|
+
web_url: `${this.baseUrl}/${name}`,
|
|
85
|
+
default_branch: "main",
|
|
86
|
+
};
|
|
87
|
+
this.state.projects.push(project);
|
|
88
|
+
this.save();
|
|
89
|
+
return project;
|
|
90
|
+
}
|
|
91
|
+
openMr(project: GitLabProject, branch: string): GitLabMergeRequest {
|
|
92
|
+
const mr: GitLabMergeRequest = {
|
|
93
|
+
iid: this.state.mrs.length + 1,
|
|
94
|
+
project_id: project.id,
|
|
95
|
+
target_project_id: project.id,
|
|
96
|
+
source_project_id: project.id,
|
|
97
|
+
title: "Update dependency",
|
|
98
|
+
description: "Renovate upgrade",
|
|
99
|
+
state: "opened",
|
|
100
|
+
labels: ["renovate"],
|
|
101
|
+
sha: this.git(project.id, ["rev-parse", branch]),
|
|
102
|
+
source_branch: branch,
|
|
103
|
+
target_branch: "main",
|
|
104
|
+
web_url: `${project.web_url}/-/merge_requests/${this.state.mrs.length + 1}`,
|
|
105
|
+
};
|
|
106
|
+
this.state.mrs.push(mr);
|
|
107
|
+
this.save();
|
|
108
|
+
return mr;
|
|
109
|
+
}
|
|
110
|
+
pipeline(mr: GitLabMergeRequest, status: string): GitLabPipeline {
|
|
111
|
+
const value: GitLabPipeline = {
|
|
112
|
+
id: this.state.pipelines.length + 1,
|
|
113
|
+
project_id: mr.source_project_id,
|
|
114
|
+
sha: this.git(mr.source_project_id, ["rev-parse", mr.source_branch]),
|
|
115
|
+
ref: mr.source_branch,
|
|
116
|
+
status,
|
|
117
|
+
source: "merge_request_event",
|
|
118
|
+
web_url: `${this.project(mr.source_project_id).web_url}/-/pipelines/${this.state.pipelines.length + 1}`,
|
|
119
|
+
};
|
|
120
|
+
this.state.pipelines.push(value);
|
|
121
|
+
this.save();
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
client(): GitLabClientLike {
|
|
125
|
+
const mr = (id: number, iid: number) => {
|
|
126
|
+
const m = this.state.mrs.find((m) => m.project_id === id && m.iid === iid);
|
|
127
|
+
if (!m) throw new Error("Unknown test MR");
|
|
128
|
+
return m;
|
|
129
|
+
};
|
|
130
|
+
const commit = (id: number, ref: string) => ({
|
|
131
|
+
id: this.git(id, ["rev-parse", ref]),
|
|
132
|
+
parent_ids: this.git(id, ["show", "-s", "--format=%P", ref]).split(" ").filter(Boolean),
|
|
133
|
+
message: this.git(id, ["show", "-s", "--format=%B", ref]),
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
baseUrl: this.baseUrl,
|
|
137
|
+
getProject: async (id) => structuredClone(this.project(id)),
|
|
138
|
+
listProjects: async () => structuredClone(this.state.projects),
|
|
139
|
+
getGroup: async (id) => ({ id: 1, full_path: String(id) }),
|
|
140
|
+
listGroupProjects: async (group) =>
|
|
141
|
+
structuredClone(
|
|
142
|
+
this.state.projects.filter((p) => p.path_with_namespace.startsWith(`${group}/`)),
|
|
143
|
+
),
|
|
144
|
+
getMergeRequest: async (id, iid) => ({
|
|
145
|
+
...structuredClone(mr(id, iid)),
|
|
146
|
+
sha: commit(mr(id, iid).source_project_id, mr(id, iid).source_branch).id,
|
|
147
|
+
}),
|
|
148
|
+
listMergeRequests: async (id, label) =>
|
|
149
|
+
structuredClone(
|
|
150
|
+
this.state.mrs.filter(
|
|
151
|
+
(m) => m.project_id === id && m.state === "opened" && m.labels.includes(label),
|
|
152
|
+
),
|
|
153
|
+
),
|
|
154
|
+
getBranch: async (id, branch) => ({
|
|
155
|
+
name: branch,
|
|
156
|
+
can_push: true,
|
|
157
|
+
protected: false,
|
|
158
|
+
commit: commit(id, branch),
|
|
159
|
+
}),
|
|
160
|
+
getCommit: async (id, ref) => commit(id, ref),
|
|
161
|
+
getChanges: async (id, iid) => structuredClone(this.state.diffs[`${id}:${iid}`] ?? []),
|
|
162
|
+
listMergeRequestPipelines: async (id, iid) =>
|
|
163
|
+
structuredClone(
|
|
164
|
+
this.state.pipelines.filter(
|
|
165
|
+
(p) =>
|
|
166
|
+
p.project_id === mr(id, iid).source_project_id && p.ref === mr(id, iid).source_branch,
|
|
167
|
+
),
|
|
168
|
+
),
|
|
169
|
+
listBranchPipelines: async (id, branch, sha) =>
|
|
170
|
+
structuredClone(
|
|
171
|
+
this.state.pipelines.filter(
|
|
172
|
+
(p) => p.project_id === id && p.ref === branch && p.sha === sha && p.source === "push",
|
|
173
|
+
),
|
|
174
|
+
),
|
|
175
|
+
getPipeline: async (id, pipeline) => {
|
|
176
|
+
const p = this.state.pipelines.find((p) => p.project_id === id && p.id === pipeline);
|
|
177
|
+
if (!p) throw new Error("Unknown test pipeline");
|
|
178
|
+
return structuredClone(p);
|
|
179
|
+
},
|
|
180
|
+
listFailedJobs: async (id, pipeline) => [
|
|
181
|
+
{
|
|
182
|
+
id: pipeline * 100,
|
|
183
|
+
name: "test",
|
|
184
|
+
status: "failed",
|
|
185
|
+
web_url: `${this.project(id).web_url}/-/jobs/${pipeline * 100}`,
|
|
186
|
+
failure_reason: "script_failure",
|
|
187
|
+
},
|
|
188
|
+
],
|
|
189
|
+
getJobTrace: async () => ({
|
|
190
|
+
text: "Expected new dependency API; test failed",
|
|
191
|
+
truncated: false,
|
|
192
|
+
}),
|
|
193
|
+
resolveGitIdentity: async () => ({
|
|
194
|
+
name: "Leitwerk Bot",
|
|
195
|
+
email: "bot@gitlab.test",
|
|
196
|
+
username: "bot",
|
|
197
|
+
}),
|
|
198
|
+
listNotes: async (id, iid) => structuredClone(this.state.notes[`${id}:${iid}`] ?? []),
|
|
199
|
+
listMergeRequestFeedback: async (id, iid) =>
|
|
200
|
+
structuredClone(this.state.feedback?.[`${id}:${iid}`] ?? []),
|
|
201
|
+
getDiscussion: async (id, iid, discussionId) => ({
|
|
202
|
+
id: discussionId,
|
|
203
|
+
notes: (this.state.discussionNotes?.[`${id}:${iid}:${discussionId}`] ?? []).map((note) => ({
|
|
204
|
+
...structuredClone(note),
|
|
205
|
+
system: false,
|
|
206
|
+
created_at: new Date().toISOString(),
|
|
207
|
+
author: { username: "bot" },
|
|
208
|
+
})),
|
|
209
|
+
}),
|
|
210
|
+
replyToDiscussion: async (id, iid, discussionId, body) => {
|
|
211
|
+
const key = `${id}:${iid}:${discussionId}`;
|
|
212
|
+
this.state.discussionNotes ??= {};
|
|
213
|
+
this.state.discussionNotes[key] ??= [];
|
|
214
|
+
const notes = this.state.discussionNotes[key];
|
|
215
|
+
return this.append(notes, { id: notes.length + 1, body }, "Reply");
|
|
216
|
+
},
|
|
217
|
+
listNoteReactions: async (id, iid, noteId) =>
|
|
218
|
+
structuredClone(this.state.reactions?.[`${id}:${iid}:${noteId}`] ?? []),
|
|
219
|
+
addNoteReaction: async (id, iid, noteId, name) => {
|
|
220
|
+
const key = `${id}:${iid}:${noteId}`;
|
|
221
|
+
this.state.reactions ??= {};
|
|
222
|
+
this.state.reactions[key] ??= [];
|
|
223
|
+
const reactions = this.state.reactions[key];
|
|
224
|
+
if (
|
|
225
|
+
reactions.some((reaction) => reaction.name === name && reaction.user.username === "bot")
|
|
226
|
+
)
|
|
227
|
+
throw new Error("Reaction already exists");
|
|
228
|
+
const reaction = { id: reactions.length + 1, name, user: { username: "bot" } };
|
|
229
|
+
return this.append(reactions, reaction, "Reaction");
|
|
230
|
+
},
|
|
231
|
+
addNote: async (id, iid, body) => {
|
|
232
|
+
const key = `${id}:${iid}`;
|
|
233
|
+
this.state.notes[key] ??= [];
|
|
234
|
+
const notes = this.state.notes[key];
|
|
235
|
+
return this.append(notes, { id: notes.length + 1, body }, "Comment");
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
}
|
package/src/tools.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
createWriteIdentity,
|
|
4
|
+
type ExternalWriteLogRepoLike,
|
|
5
|
+
ensureWrite,
|
|
6
|
+
} from "@leitwerk-dev/external-writes";
|
|
7
|
+
import {
|
|
8
|
+
type IntegrationToolExecutionContext,
|
|
9
|
+
numberArg,
|
|
10
|
+
projectParameters,
|
|
11
|
+
type ServerExtensionAPI,
|
|
12
|
+
stringArg,
|
|
13
|
+
} from "@leitwerk-dev/process-sdk";
|
|
14
|
+
import type { GitLabIntegration } from "./capability.js";
|
|
15
|
+
import { type GitLabClientLike, observeMergeRequest } from "./client.js";
|
|
16
|
+
export function resolveGitLabBinding(
|
|
17
|
+
ctx: Pick<IntegrationToolExecutionContext, "project" | "process">,
|
|
18
|
+
): { profile: string; projectId: number; iid: number } {
|
|
19
|
+
if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
|
|
20
|
+
throw new Error("An authorized GitLab process project is required");
|
|
21
|
+
const binding = ctx.project.metadata?.gitlab as
|
|
22
|
+
| { profile?: unknown; projectId?: unknown; iid?: unknown }
|
|
23
|
+
| undefined;
|
|
24
|
+
if (
|
|
25
|
+
!binding ||
|
|
26
|
+
typeof binding.profile !== "string" ||
|
|
27
|
+
typeof binding.projectId !== "number" ||
|
|
28
|
+
typeof binding.iid !== "number"
|
|
29
|
+
)
|
|
30
|
+
throw new Error("Invalid GitLab project binding");
|
|
31
|
+
return { profile: binding.profile, projectId: binding.projectId, iid: binding.iid };
|
|
32
|
+
}
|
|
33
|
+
async function findOrCreate<T>(find: () => Promise<T | undefined>, create: () => Promise<T>) {
|
|
34
|
+
const existing = await find();
|
|
35
|
+
if (existing) return existing;
|
|
36
|
+
try {
|
|
37
|
+
return await create();
|
|
38
|
+
} catch (error) {
|
|
39
|
+
const recovered = await find();
|
|
40
|
+
if (!recovered) throw error;
|
|
41
|
+
return recovered;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function ensureGitLabComment(input: {
|
|
45
|
+
client: GitLabClientLike;
|
|
46
|
+
writes: ExternalWriteLogRepoLike;
|
|
47
|
+
instanceId: string;
|
|
48
|
+
projectId: number;
|
|
49
|
+
iid: number;
|
|
50
|
+
writeKey: string;
|
|
51
|
+
body: string;
|
|
52
|
+
discussionId?: string;
|
|
53
|
+
signal?: AbortSignal;
|
|
54
|
+
}): Promise<{ marker: string }> {
|
|
55
|
+
const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
|
|
56
|
+
const identity = [client.baseUrl, projectId, iid, instanceId, writeKey];
|
|
57
|
+
if (input.discussionId) identity.push(input.discussionId);
|
|
58
|
+
const digest = createHash("sha256").update(JSON.stringify(identity)).digest("hex");
|
|
59
|
+
const marker = `<!-- leitwerk:gitlab:${digest} -->`;
|
|
60
|
+
const find = async () => {
|
|
61
|
+
const notes = input.discussionId
|
|
62
|
+
? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes
|
|
63
|
+
: await client.listNotes(projectId, iid, signal);
|
|
64
|
+
return notes.find((note) => note.body.includes(marker));
|
|
65
|
+
};
|
|
66
|
+
await ensureWrite(writes, instanceId, createWriteIdentity("gitlab.comment", digest), async () => {
|
|
67
|
+
const note = await findOrCreate(find, () => {
|
|
68
|
+
const body = `${input.body}\n\n${marker}`;
|
|
69
|
+
return input.discussionId
|
|
70
|
+
? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal)
|
|
71
|
+
: client.addNote(projectId, iid, body, signal);
|
|
72
|
+
});
|
|
73
|
+
return { projectId, iid, noteId: note.id, marker };
|
|
74
|
+
});
|
|
75
|
+
return { marker };
|
|
76
|
+
}
|
|
77
|
+
export async function ensureGitLabSeenReaction(input: {
|
|
78
|
+
client: GitLabClientLike;
|
|
79
|
+
writes: ExternalWriteLogRepoLike;
|
|
80
|
+
instanceId: string;
|
|
81
|
+
projectId: number;
|
|
82
|
+
iid: number;
|
|
83
|
+
noteId: number;
|
|
84
|
+
signal?: AbortSignal;
|
|
85
|
+
}): Promise<void> {
|
|
86
|
+
const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
|
|
87
|
+
const digest = createHash("sha256")
|
|
88
|
+
.update(JSON.stringify([client.baseUrl, projectId, iid, instanceId, "eyes", noteId]))
|
|
89
|
+
.digest("hex");
|
|
90
|
+
await ensureWrite(
|
|
91
|
+
writes,
|
|
92
|
+
instanceId,
|
|
93
|
+
createWriteIdentity("gitlab.reaction", digest),
|
|
94
|
+
async () => {
|
|
95
|
+
const identity = await client.resolveGitIdentity(signal);
|
|
96
|
+
const find = async () =>
|
|
97
|
+
(await client.listNoteReactions(projectId, iid, noteId, signal)).find(
|
|
98
|
+
(reaction) => reaction.name === "eyes" && reaction.user.username === identity.username,
|
|
99
|
+
);
|
|
100
|
+
const reaction = await findOrCreate(find, () =>
|
|
101
|
+
client.addNoteReaction(projectId, iid, noteId, "eyes", signal),
|
|
102
|
+
);
|
|
103
|
+
return { projectId, iid, noteId, reactionId: reaction.id, name: "eyes" };
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
export function registerGitLabTools(
|
|
108
|
+
api: ServerExtensionAPI,
|
|
109
|
+
integration: GitLabIntegration,
|
|
110
|
+
writes: ExternalWriteLogRepoLike,
|
|
111
|
+
) {
|
|
112
|
+
for (const [name, description, required] of [
|
|
113
|
+
["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
|
|
114
|
+
["gitlab_get_changes", "Read the MR changes", []],
|
|
115
|
+
["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
|
|
116
|
+
["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
|
|
117
|
+
[
|
|
118
|
+
"gitlab_get_job_trace",
|
|
119
|
+
"Read a bounded trace from a failed MR pipeline job",
|
|
120
|
+
["pipelineId", "jobId"],
|
|
121
|
+
],
|
|
122
|
+
["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
|
|
123
|
+
[
|
|
124
|
+
"gitlab_reply",
|
|
125
|
+
"Post a retry-safe reply in an MR discussion",
|
|
126
|
+
["body", "writeKey", "discussionId"],
|
|
127
|
+
],
|
|
128
|
+
] as const) {
|
|
129
|
+
api.tool<Record<string, unknown>>({
|
|
130
|
+
name,
|
|
131
|
+
description,
|
|
132
|
+
parameters: projectParameters(
|
|
133
|
+
{
|
|
134
|
+
pipelineId: { type: "integer" },
|
|
135
|
+
jobId: { type: "integer" },
|
|
136
|
+
maxBytes: { type: "integer" },
|
|
137
|
+
body: { type: "string" },
|
|
138
|
+
writeKey: { type: "string" },
|
|
139
|
+
discussionId: { type: "string" },
|
|
140
|
+
},
|
|
141
|
+
[...required],
|
|
142
|
+
),
|
|
143
|
+
async execute(ctx, args) {
|
|
144
|
+
const b = resolveGitLabBinding(ctx);
|
|
145
|
+
const client = integration.client(b.profile);
|
|
146
|
+
if (name === "gitlab_observe_merge_request")
|
|
147
|
+
return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
148
|
+
if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
|
|
149
|
+
if (name === "gitlab_get_identity") return client.resolveGitIdentity(ctx.signal);
|
|
150
|
+
if (name === "gitlab_comment" || name === "gitlab_reply")
|
|
151
|
+
return ensureGitLabComment({
|
|
152
|
+
client,
|
|
153
|
+
writes,
|
|
154
|
+
instanceId: ctx.process.id,
|
|
155
|
+
projectId: b.projectId,
|
|
156
|
+
iid: b.iid,
|
|
157
|
+
writeKey: stringArg(args, "writeKey"),
|
|
158
|
+
body: stringArg(args, "body"),
|
|
159
|
+
...(name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {}),
|
|
160
|
+
signal: ctx.signal,
|
|
161
|
+
});
|
|
162
|
+
const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
163
|
+
if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
|
|
164
|
+
throw new Error("Pipeline is not current for the authorized MR");
|
|
165
|
+
const jobs = await client.listFailedJobs(
|
|
166
|
+
observation.pipeline.project_id,
|
|
167
|
+
observation.pipeline.id,
|
|
168
|
+
ctx.signal,
|
|
169
|
+
);
|
|
170
|
+
if (name === "gitlab_list_failed_jobs") return jobs;
|
|
171
|
+
const job = jobs.find((job) => job.id === numberArg(args, "jobId"));
|
|
172
|
+
if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
|
|
173
|
+
return client.getJobTrace(
|
|
174
|
+
observation.pipeline.project_id,
|
|
175
|
+
job.id,
|
|
176
|
+
typeof args.maxBytes === "number" ? args.maxBytes : undefined,
|
|
177
|
+
ctx.signal,
|
|
178
|
+
);
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
}
|