Elffuss BraidHub

kikocis/continue public

main · 8.3 KiBRawPermalink
1import { AxiosError, AxiosInstance } from "axios";
2
3import {
4 ContextItem,
5 ContextProviderDescription,
6 ContextProviderExtras,
7} from "../../index.js";
8import { BaseContextProvider } from "../index.js";
9
10interface RemoteBranchInfo {
11 branch: string | null;
12 project: string | null;
13}
14
15interface GitLabUser {
16 id: number;
17 username: string;
18 name: string;
19 state: "active";
20 locked: boolean;
21 avatar_url: string;
22 web_url: string;
23}
24
25interface GitLabMergeRequest {
26 iid: number;
27 project_id: number;
28 title: string;
29 description: string;
30}
31
32interface GitLabComment {
33 type: null | "DiffNote";
34 resolvable: boolean;
35 resolved?: boolean;
36 body: string;
37 created_at: string;
38 author: GitLabUser;
39 position?: {
40 new_path: string;
41 new_line: number;
42 head_sha: string;
43 line_range: {
44 start: {
45 line_code: string;
46 type: "new";
47 old_line: null;
48 new_line: number;
49 };
50 end: {
51 line_code: string;
52 type: "new";
53 old_line: null;
54 new_line: number;
55 };
56 };
57 };
58}
59
60const trimFirstElement = (args: Array<string>): string => {
61 return args[0].trim();
62};
63
64const getSubprocess = async (extras: ContextProviderExtras) => {
65 const workingDir = await extras.ide.getWorkspaceDirs().then(trimFirstElement);
66
67 return (command: string) =>
68 extras.ide.subprocess(command, workingDir).then(trimFirstElement);
69};
70
71class GitLabMergeRequestContextProvider extends BaseContextProvider {
72 static description: ContextProviderDescription = {
73 title: "gitlab-mr",
74 displayTitle: "GitLab Merge Request",
75 description: "Reference comments in a GitLab Merge Request",
76 type: "normal",
77 };
78
79 get deprecationMessage() {
80 return "The Gitlab Merge Request context provider is now deprecated and will be removed in a later version. Please consider using the GitLab MCP (https://hub.continue.dev/docker/mcp-gitlab) instead.";
81 }
82
83 private async getApi(): Promise<AxiosInstance> {
84 const { default: Axios } = await import("axios");
85
86 const domain = this.options.domain ?? "gitlab.com";
87 const token = this.options.token;
88
89 if (!token) {
90 throw new Error("GitLab Private Token is required!");
91 }
92
93 return Axios.create({
94 baseURL: `https://${domain ?? "gitlab.com"}/api/v4`,
95 headers: {
96 "PRIVATE-TOKEN": token,
97 },
98 });
99 }
100
101 private async getRemoteBranchInfo(
102 extras: ContextProviderExtras,
103 ): Promise<RemoteBranchInfo> {
104 const subprocess = await getSubprocess(extras);
105
106 const branchName = await subprocess("git branch --show-current");
107
108 const branchRemote = await subprocess(
109 `git config branch.${branchName}.remote`,
110 );
111
112 const branchInfo = await subprocess("git branch -vv");
113
114 const currentBranchInfo = branchInfo
115 .split("\n")
116 .find((line) => line.startsWith("*"));
117
118 const remoteMatches = RegExp(
119 `\\[${branchRemote}/(?<remote_branch>[^\\]]+)\\]`,
120 ).exec(currentBranchInfo!);
121
122 console.dir({ remoteMatches });
123
124 const remoteBranch = remoteMatches?.groups?.remote_branch ?? null;
125
126 const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
127
128 let urlMatches: RegExpExecArray | null;
129 if (/https?.*/.test(remoteUrl)) {
130 const pathname = new URL(remoteUrl).pathname;
131 urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
132 } else {
133 // ssh
134 urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
135 }
136
137 const project = urlMatches?.groups?.projectPath ?? null;
138
139 return {
140 branch: remoteBranch,
141 project,
142 };
143 }
144
145 async getContextItems(
146 query: string,
147 extras: ContextProviderExtras,
148 ): Promise<ContextItem[]> {
149 const { branch, project } = await this.getRemoteBranchInfo(extras);
150
151 const api = await this.getApi();
152
153 const result = [] as Array<ContextItem>;
154
155 try {
156 const mergeRequests = await api
157 .get<Array<GitLabMergeRequest>>(
158 `/projects/${encodeURIComponent(project!)}/merge_requests`,
159 {
160 params: {
161 source_branch: branch,
162 state: "opened",
163 },
164 },
165 )
166 .then((x) => x.data);
167
168 const subprocess = await getSubprocess(extras);
169
170 for (const mergeRequest of mergeRequests) {
171 const parts = [
172 `# GitLab Merge Request\ntitle: "${
173 mergeRequest.title
174 }"\ndescription: "${mergeRequest.description ?? "None"}"`,
175 "## Comments",
176 ];
177
178 const comments = await api.get<Array<GitLabComment>>(
179 `/projects/${mergeRequest.project_id}/merge_requests/${mergeRequest.iid}/notes`,
180 {
181 params: {
182 sort: "asc",
183 order_by: "created_at",
184 },
185 },
186 );
187
188 const filteredComments = comments.data.filter(
189 (x) => x.type === "DiffNote",
190 );
191
192 const locations = {} as Record<string, Array<GitLabComment>>;
193
194 for (const comment of filteredComments) {
195 const filename = comment.position?.new_path ?? "general";
196
197 if (!locations[filename]) {
198 locations[filename] = [];
199 }
200
201 locations[filename].push(comment);
202 }
203
204 if (extras.selectedCode.length && this.options.filterComments) {
205 const toRemove = Object.keys(locations).filter(
206 (filename) =>
207 !extras.selectedCode.find((selection) =>
208 selection.filepath.endsWith(filename),
209 ) && filename !== "general",
210 );
211 for (const filepath of toRemove) {
212 delete locations[filepath];
213 }
214 }
215
216 const commentFormatter = async (comment: GitLabComment) => {
217 const commentLabel = comment.body.includes("```suggestion")
218 ? "Code Suggestion"
219 : "Comment";
220 let result = `#### ${commentLabel}\nauthor: "${
221 comment.author.name
222 }"\ndate: "${comment.created_at}"\nresolved: ${
223 comment.resolved ? "Yes" : "No"
224 }`;
225
226 if (comment.position?.new_line) {
227 result += `\nline: ${comment.position.new_line}`;
228
229 if (comment.position.head_sha) {
230 const sourceLines = await subprocess(
231 `git show ${comment.position.head_sha}:${comment.position.new_path}`,
232 )
233 .then((result) => result.split("\n"))
234 .catch((ex) => []);
235
236 const line =
237 comment.position.new_line <= sourceLines.length
238 ? sourceLines[comment.position.new_line - 1]
239 : null;
240
241 if (line) {
242 result += `\nsource: \`${line}\``;
243 }
244 }
245 }
246
247 result += `\n\n${comment.body}`;
248
249 return result;
250 };
251
252 for (const [filename, locationComments] of Object.entries(locations)) {
253 if (filename !== "general") {
254 parts.push(`### File ${filename}`);
255 locationComments.sort(
256 (a, b) =>
257 (a.position?.new_line ?? 0) - (b.position?.new_line ?? 0),
258 );
259 } else {
260 parts.push("### General");
261 }
262
263 const commentSections = await Promise.all(
264 locationComments.map(commentFormatter),
265 );
266 parts.push(...commentSections);
267 }
268
269 const content = parts.join("\n\n");
270
271 result.push({
272 name: mergeRequest.title,
273 content,
274 description: "Comments from the Merge Request for this branch.",
275 });
276 }
277 } catch (ex) {
278 let content = "# GitLab Merge Request\n\nError getting merge request. ";
279 if (ex instanceof AxiosError) {
280 if (ex.response) {
281 const errorMessage = ex.response?.data
282 ? (ex.response.data.message ?? JSON.stringify(ex.response?.data))
283 : `${ex.response.status}: ${ex.response.statusText}`;
284 content += `GitLab Error: ${errorMessage}`;
285 } else {
286 content += `GitLab Request Error ${ex.request}`;
287 }
288 } else {
289 // @ts-ignore
290 content += `Unknown error: ${ex.message ?? JSON.stringify(ex)}`;
291 }
292
293 result.push({
294 name: "GitLab Merge Request",
295 content,
296 description: "Error getting the Merge Request for this branch.",
297 });
298 }
299
300 return result;
301 }
302}
303
304export default GitLabMergeRequestContextProvider;