@open-cr-agent/vcs-gitlab 0.9.0 → 0.11.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/dist/adapter.js CHANGED
@@ -1,6 +1,9 @@
1
- import { errorMessage, OcraError } from "@open-cr-agent/core";
1
+ import { errorMessage, OcraError, } from "@open-cr-agent/core";
2
2
  import { gitlabSuggestion, PlatformReview, } from "@open-cr-agent/vcs-platform";
3
3
  import { DEVELOPER, GitLabApiError, } from "./client.js";
4
+ import { gitlabCommit } from "./commit.js";
5
+ import { gitlabDiscussion } from "./discussion.js";
6
+ import { gitlabLinkedTasks } from "./tasks.js";
4
7
  // A GitLab merge request as ocra's review conversation (vcs-platform).
5
8
  export class GitLabAdapter extends PlatformReview {
6
9
  constructor(options) {
@@ -57,6 +60,9 @@ class GitLabPlatform {
57
60
  }
58
61
  return editors.get(id);
59
62
  }
63
+ linkedTasks() {
64
+ return gitlabLinkedTasks(this.options.api, this.options.iid);
65
+ }
60
66
  async canWrite(login) {
61
67
  const id = this.ids.get(login) ?? (await this.options.api.findUser(login));
62
68
  if (id === undefined)
@@ -132,6 +138,18 @@ class GitLabPlatform {
132
138
  resolveThread(id) {
133
139
  return this.options.api.resolveDiscussion(this.options.iid, id);
134
140
  }
141
+ discussion(ref) {
142
+ return gitlabDiscussion(this.options.api, this.options.iid, ref);
143
+ }
144
+ async reply(discussion, body) {
145
+ if (discussion.replyTo === undefined)
146
+ await this.options.api.createNote(this.options.iid, body);
147
+ else
148
+ await this.options.api.replyToDiscussion(this.options.iid, discussion.replyTo, body);
149
+ }
150
+ commit(commit) {
151
+ return gitlabCommit(this.options.api, this.options.iid, commit);
152
+ }
135
153
  remember(note) {
136
154
  this.ids.set(note.author.username, note.author.id);
137
155
  if (note.resolved_by)
@@ -160,6 +178,7 @@ export function mergeRequestOf(mr) {
160
178
  baseSha: refs.start_sha,
161
179
  headSha: refs.head_sha,
162
180
  mergeBaseSha: refs.base_sha,
181
+ branch: mr.source_branch,
163
182
  ...(mr.author ? { author: mr.author.username } : {}),
164
183
  };
165
184
  }
package/dist/client.d.ts CHANGED
@@ -11,6 +11,7 @@ declare const mergeRequestSchema: z.ZodObject<{
11
11
  web_url: z.ZodString;
12
12
  source_project_id: z.ZodNumber;
13
13
  target_project_id: z.ZodNumber;
14
+ source_branch: z.ZodString;
14
15
  diff_refs: z.ZodNullable<z.ZodObject<{
15
16
  base_sha: z.ZodString;
16
17
  start_sha: z.ZodString;
@@ -18,6 +19,23 @@ declare const mergeRequestSchema: z.ZodObject<{
18
19
  }, z.core.$strip>>;
19
20
  }, z.core.$strip>;
20
21
  export type MergeRequest = z.infer<typeof mergeRequestSchema>;
22
+ declare const issueSchema: z.ZodObject<{
23
+ iid: z.ZodNumber;
24
+ project_id: z.ZodNumber;
25
+ title: z.ZodString;
26
+ description: z.ZodPipe<z.ZodNullable<z.ZodString>, z.ZodTransform<string, string | null>>;
27
+ state: z.ZodEnum<{
28
+ closed: "closed";
29
+ opened: "opened";
30
+ }>;
31
+ labels: z.ZodArray<z.ZodString>;
32
+ web_url: z.ZodString;
33
+ epic: z.ZodOptional<z.ZodNullable<z.ZodObject<{
34
+ iid: z.ZodNumber;
35
+ title: z.ZodString;
36
+ }, z.core.$strip>>>;
37
+ }, z.core.$strip>;
38
+ export type Issue = z.infer<typeof issueSchema>;
21
39
  declare const noteSchema: z.ZodObject<{
22
40
  id: z.ZodNumber;
23
41
  body: z.ZodString;
@@ -33,6 +51,10 @@ declare const noteSchema: z.ZodObject<{
33
51
  id: z.ZodNumber;
34
52
  username: z.ZodString;
35
53
  }, z.core.$strip>>>;
54
+ position: z.ZodOptional<z.ZodNullable<z.ZodObject<{
55
+ new_path: z.ZodString;
56
+ new_line: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
57
+ }, z.core.$strip>>>;
36
58
  }, z.core.$strip>;
37
59
  export type Note = z.infer<typeof noteSchema>;
38
60
  declare const discussionSchema: z.ZodObject<{
@@ -53,6 +75,10 @@ declare const discussionSchema: z.ZodObject<{
53
75
  id: z.ZodNumber;
54
76
  username: z.ZodString;
55
77
  }, z.core.$strip>>>;
78
+ position: z.ZodOptional<z.ZodNullable<z.ZodObject<{
79
+ new_path: z.ZodString;
80
+ new_line: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
81
+ }, z.core.$strip>>>;
56
82
  }, z.core.$strip>>;
57
83
  }, z.core.$strip>;
58
84
  export type Discussion = z.infer<typeof discussionSchema>;
@@ -90,11 +116,14 @@ export declare class GitLabApi {
90
116
  fullPath(): Promise<string>;
91
117
  resolvesOutdatedThreads(): Promise<boolean | undefined>;
92
118
  getMergeRequest(iid: number): Promise<MergeRequest>;
119
+ closesIssues(iid: number): Promise<Issue[]>;
120
+ getIssue(iid: number): Promise<Issue | undefined>;
93
121
  listNotes(iid: number): Promise<Note[]>;
94
122
  listDiscussions(iid: number): Promise<Discussion[]>;
95
123
  createNote(iid: number, body: string): Promise<void>;
96
124
  updateNote(iid: number, noteId: number, body: string): Promise<void>;
97
125
  createDiscussion(iid: number, body: string, position: Position): Promise<void>;
126
+ replyToDiscussion(iid: number, discussionId: string, body: string): Promise<void>;
98
127
  resolveDiscussion(iid: number, discussionId: string): Promise<void>;
99
128
  accessLevel(userId: number): Promise<number>;
100
129
  findUser(username: string): Promise<number | undefined>;
package/dist/client.js CHANGED
@@ -12,9 +12,24 @@ const mergeRequestSchema = z.object({
12
12
  web_url: z.string(),
13
13
  source_project_id: z.number(),
14
14
  target_project_id: z.number(),
15
+ source_branch: z.string(),
15
16
  // Null while GitLab is still preparing the diff of a new merge request.
16
17
  diff_refs: z.object({ base_sha: sha, start_sha: sha, head_sha: sha }).nullable(),
17
18
  });
19
+ const issueSchema = z.object({
20
+ iid: z.number(),
21
+ project_id: z.number(),
22
+ title: z.string(),
23
+ description: z
24
+ .string()
25
+ .nullable()
26
+ .transform((d) => d ?? ""),
27
+ state: z.enum(["opened", "closed"]),
28
+ labels: z.array(z.string()),
29
+ web_url: z.string(),
30
+ // Only on tiers with epics.
31
+ epic: z.object({ iid: z.number(), title: z.string() }).nullish(),
32
+ });
18
33
  const noteSchema = z.object({
19
34
  id: z.number(),
20
35
  body: z.string(),
@@ -25,6 +40,12 @@ const noteSchema = z.object({
25
40
  resolvable: z.boolean().optional(),
26
41
  resolved: z.boolean().optional(),
27
42
  resolved_by: user.nullable().optional(),
43
+ // On a line of the diff: the file and the new side's line, unset on a
44
+ // removed line.
45
+ position: z
46
+ .object({ new_path: z.string(), new_line: z.number().nullable().optional() })
47
+ .nullable()
48
+ .optional(),
28
49
  });
29
50
  const discussionSchema = z.object({
30
51
  id: z.string(),
@@ -108,6 +129,23 @@ export class GitLabApi {
108
129
  async getMergeRequest(iid) {
109
130
  return mergeRequestSchema.parse(await this.request("GET", `/merge_requests/${iid}`));
110
131
  }
132
+ // The issues the merge request closes when it merges, in GitLab's order.
133
+ async closesIssues(iid) {
134
+ return z
135
+ .array(issueSchema)
136
+ .parse(await this.request("GET", `/merge_requests/${iid}/closes_issues?per_page=10`));
137
+ }
138
+ // The project's issue, or undefined when it has none by that number.
139
+ async getIssue(iid) {
140
+ try {
141
+ return issueSchema.parse(await this.request("GET", `/issues/${iid}`));
142
+ }
143
+ catch (error) {
144
+ if (error instanceof GitLabApiError && error.status === 404)
145
+ return undefined;
146
+ throw error;
147
+ }
148
+ }
111
149
  async listNotes(iid) {
112
150
  return this.pages(`/merge_requests/${iid}/notes?sort=asc&order_by=created_at`, noteSchema, MAX_NOTE_PAGES);
113
151
  }
@@ -123,6 +161,9 @@ export class GitLabApi {
123
161
  async createDiscussion(iid, body, position) {
124
162
  await this.request("POST", `/merge_requests/${iid}/discussions`, { body, position });
125
163
  }
164
+ async replyToDiscussion(iid, discussionId, body) {
165
+ await this.request("POST", `/merge_requests/${iid}/discussions/${encodeURIComponent(discussionId)}/notes`, { body });
166
+ }
126
167
  async resolveDiscussion(iid, discussionId) {
127
168
  await this.request("PUT", `/merge_requests/${iid}/discussions/${encodeURIComponent(discussionId)}?resolved=true`);
128
169
  }
@@ -0,0 +1,3 @@
1
+ import type { ChangeCommit, CommitResult } from "@open-cr-agent/core";
2
+ import { type GitLabApi } from "./client.js";
3
+ export declare function gitlabCommit(api: GitLabApi, iid: number, commit: ChangeCommit): Promise<CommitResult>;
package/dist/commit.js ADDED
@@ -0,0 +1,63 @@
1
+ import { z } from "zod";
2
+ import { GitLabApiError } from "./client.js";
3
+ const sourceSchema = z.object({
4
+ source_branch: z.string(),
5
+ source_project_id: z.number(),
6
+ target_project_id: z.number(),
7
+ });
8
+ const branchSchema = z.object({
9
+ commit: z.object({ id: z.string() }),
10
+ can_push: z.boolean().optional(),
11
+ });
12
+ const fileSchema = z.object({ last_commit_id: z.string() });
13
+ const createdSchema = z.object({ id: z.string() });
14
+ // One commit through the commits API on the merge request's source branch.
15
+ // GitLab takes no parent for it, so the branch is compared first, each
16
+ // updated file carries the commit that last changed it (GitLab refuses the
17
+ // update when another has since) and each new file is created (refused
18
+ // when one is there): a push in between never loses a line.
19
+ export async function gitlabCommit(api, iid, commit) {
20
+ const source = sourceSchema.parse(await api.request("GET", `/merge_requests/${iid}`));
21
+ if (source.source_project_id !== source.target_project_id) {
22
+ return refused("not_writable", "the branch is on a fork, which ocra's token cannot write to");
23
+ }
24
+ const branch = branchSchema.parse(await api.request("GET", `/repository/branches/${encodeURIComponent(source.source_branch)}`));
25
+ if (branch.commit.id !== commit.parent) {
26
+ return refused("head_moved", "the branch moved after ocra read it");
27
+ }
28
+ if (branch.can_push === false) {
29
+ return refused("not_writable", "ocra's token may not push to the branch");
30
+ }
31
+ const actions = [];
32
+ for (const f of commit.files) {
33
+ if (f.created) {
34
+ actions.push({ action: "create", file_path: f.path, content: f.content });
35
+ continue;
36
+ }
37
+ const path = `/repository/files/${encodeURIComponent(f.path)}?ref=${commit.parent}`;
38
+ const { last_commit_id } = fileSchema.parse(await api.request("GET", path));
39
+ actions.push({ action: "update", file_path: f.path, content: f.content, last_commit_id });
40
+ }
41
+ try {
42
+ const created = createdSchema.parse(await api.request("POST", "/repository/commits", {
43
+ branch: source.source_branch,
44
+ commit_message: commit.message,
45
+ actions,
46
+ }));
47
+ return { committed: true, sha: created.id };
48
+ }
49
+ catch (error) {
50
+ if (!(error instanceof GitLabApiError))
51
+ throw error;
52
+ if (error.status === 400 && /already exists|changed since/i.test(error.message)) {
53
+ return refused("head_moved", "the branch moved after ocra read it");
54
+ }
55
+ if (error.status === 403) {
56
+ return refused("not_writable", `GitLab refused the commit: ${error.message}`);
57
+ }
58
+ throw error;
59
+ }
60
+ }
61
+ function refused(outcome, reason) {
62
+ return { committed: false, outcome, reason };
63
+ }
@@ -0,0 +1,4 @@
1
+ import { type MentionRef } from "@open-cr-agent/core";
2
+ import type { PlatformDiscussion } from "@open-cr-agent/vcs-platform";
3
+ import type { GitLabApi } from "./client.js";
4
+ export declare function gitlabDiscussion(api: GitLabApi, iid: number, ref: MentionRef): Promise<PlatformDiscussion | undefined>;
@@ -0,0 +1,51 @@
1
+ import { OcraError } from "@open-cr-agent/core";
2
+ // A note on the merge request and the discussion it is in. Every note is in
3
+ // one on GitLab, a comment on the merge request as a whole too, so a reply
4
+ // always goes to its discussion; such a comment is read, as on GitHub,
5
+ // among the merge request's other comments.
6
+ export async function gitlabDiscussion(api, iid, ref) {
7
+ const id = Number(ref.id);
8
+ if (!Number.isSafeInteger(id) || id <= 0)
9
+ return undefined;
10
+ const discussions = await api.listDiscussions(iid);
11
+ const discussion = discussions.find((d) => d.notes.some((n) => n.id === id));
12
+ const conversation = discussion?.individual_note
13
+ ? discussions.filter((d) => d.individual_note || d === discussion)
14
+ : discussion
15
+ ? [discussion]
16
+ : [];
17
+ const notes = conversation
18
+ .flatMap((d) => d.notes)
19
+ .filter((n) => !n.system)
20
+ .sort((a, b) => a.id - b.id);
21
+ const note = notes.find((n) => n.id === id);
22
+ if (!discussion || !note)
23
+ return undefined;
24
+ const editors = await api.noteEditors(iid);
25
+ if (!editors.has(id)) {
26
+ throw new OcraError("VCS_API_FAILED", `GitLab did not say who last edited note ${id}`);
27
+ }
28
+ const editor = editors.get(id);
29
+ const said = (n) => ({ author: n.author.username, body: n.body });
30
+ const at = notes.indexOf(note);
31
+ const position = discussion.individual_note ? undefined : notes[0]?.position;
32
+ return {
33
+ comment: {
34
+ id: String(id),
35
+ author: note.author.username,
36
+ body: note.body,
37
+ ...(editor ? { editor } : {}),
38
+ },
39
+ earlier: notes.slice(0, at).map(said),
40
+ later: notes.slice(at + 1).map(said),
41
+ ...(position
42
+ ? {
43
+ on: {
44
+ path: position.new_path,
45
+ ...(position.new_line ? { line: position.new_line } : {}),
46
+ },
47
+ }
48
+ : {}),
49
+ replyTo: discussion.id,
50
+ };
51
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { GitLabApiError } from "./client.js";
2
2
  export { gitlabPlugin } from "./plugin.js";
3
3
  export { proposeOnGitLab } from "./propose.js";
4
+ export { gitlabStackHost } from "./stack.js";
4
5
  export { type GitLabSettings, resolveGitLabTarget } from "./target.js";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { GitLabApiError } from "./client.js";
2
2
  export { gitlabPlugin } from "./plugin.js";
3
3
  export { proposeOnGitLab } from "./propose.js";
4
+ export { gitlabStackHost } from "./stack.js";
4
5
  export { resolveGitLabTarget } from "./target.js";
@@ -0,0 +1,2 @@
1
+ import type { ProposeOptions, StackHost } from "@open-cr-agent/vcs-platform";
2
+ export declare function gitlabStackHost(options: ProposeOptions, warn: (message: string) => void): Promise<StackHost>;
package/dist/stack.js ADDED
@@ -0,0 +1,52 @@
1
+ import { pickStacked } from "@open-cr-agent/vcs-platform";
2
+ import { z } from "zod";
3
+ import { gitlabApi } from "./target.js";
4
+ const mergeRequestSchema = z.object({
5
+ iid: z.number(),
6
+ state: z.string(),
7
+ title: z.string(),
8
+ description: z.string().nullish(),
9
+ web_url: z.string(),
10
+ source_branch: z.string(),
11
+ target_branch: z.string(),
12
+ });
13
+ function stacked(request) {
14
+ return {
15
+ number: request.iid,
16
+ head: request.source_branch,
17
+ base: request.target_branch,
18
+ state: request.state === "opened" ? "open" : request.state === "merged" ? "merged" : "closed",
19
+ title: request.title,
20
+ body: request.description ?? "",
21
+ webUrl: request.web_url,
22
+ };
23
+ }
24
+ // Merge requests between branches of the project itself. The token needs
25
+ // the api scope and the Developer role.
26
+ export async function gitlabStackHost(options, warn) {
27
+ const { api } = await gitlabApi({ ...options, warn }, options.repository, "ocra stack");
28
+ return {
29
+ async find(head) {
30
+ const query = new URLSearchParams({ source_branch: head, per_page: "20" });
31
+ const requests = z
32
+ .array(mergeRequestSchema)
33
+ .parse(await api.request("GET", `/merge_requests?${query}`));
34
+ return pickStacked(requests.map(stacked));
35
+ },
36
+ async open({ head, base, title, body, draft }) {
37
+ return stacked(mergeRequestSchema.parse(await api.request("POST", "/merge_requests", {
38
+ source_branch: head,
39
+ target_branch: base,
40
+ title: draft ? `Draft: ${title}` : title,
41
+ description: body,
42
+ remove_source_branch: true,
43
+ })));
44
+ },
45
+ async update(number, change) {
46
+ await api.request("PUT", `/merge_requests/${number}`, {
47
+ ...(change.base !== undefined ? { target_branch: change.base } : {}),
48
+ ...(change.body !== undefined ? { description: change.body } : {}),
49
+ });
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,3 @@
1
+ import type { LinkedTask } from "@open-cr-agent/core";
2
+ import type { GitLabApi } from "./client.js";
3
+ export declare function gitlabLinkedTasks(api: GitLabApi, iid: number): Promise<LinkedTask[]>;
package/dist/tasks.js ADDED
@@ -0,0 +1,33 @@
1
+ // GitLab names a branch made from an issue "<iid>-<title>".
2
+ const ISSUE_BRANCH = /^(\d+)-/;
3
+ // The issues of this project the merge request closes, or the one its source
4
+ // branch is named after (ADR-0052). Another project's issue is left out: a
5
+ // fork's author could otherwise pull text they cannot read into a review
6
+ // posted where they can.
7
+ export async function gitlabLinkedTasks(api, iid) {
8
+ const [mr, closing] = await Promise.all([api.getMergeRequest(iid), api.closesIssues(iid)]);
9
+ const own = closing.filter((issue) => issue.project_id === mr.target_project_id);
10
+ if (own.length > 0)
11
+ return own.map(linkedTask);
12
+ const branched = ISSUE_BRANCH.exec(mr.source_branch)?.[1];
13
+ if (!branched)
14
+ return [];
15
+ const issue = await api.getIssue(Number(branched));
16
+ return issue ? [linkedTask(issue)] : [];
17
+ }
18
+ function linkedTask(issue) {
19
+ return {
20
+ tracker: "gitlab",
21
+ key: `#${issue.iid}`,
22
+ url: issue.web_url,
23
+ title: issue.title,
24
+ state: issue.state === "opened" ? "open" : "closed",
25
+ labels: issue.labels,
26
+ body: issue.description,
27
+ // The issue names its epic, not the epic's description.
28
+ ...(issue.epic
29
+ ? { parent: { key: `&${issue.epic.iid}`, title: issue.epic.title, body: "" } }
30
+ : {}),
31
+ subtasks: [],
32
+ };
33
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/vcs-gitlab",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "GitLab merge request adapter for Open-CR-Agent",
5
5
  "keywords": [
6
6
  "code-review",
@@ -33,8 +33,8 @@
33
33
  "!dist/**/*.map"
34
34
  ],
35
35
  "dependencies": {
36
- "@open-cr-agent/core": "0.9.0",
37
- "@open-cr-agent/vcs-platform": "0.9.0",
36
+ "@open-cr-agent/core": "0.11.0",
37
+ "@open-cr-agent/vcs-platform": "0.11.0",
38
38
  "zod": "^4.6.6"
39
39
  },
40
40
  "publishConfig": {