Elffuss BraidHub

kikocis/continue public

b334cb9dcd5e · 8.1 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 private async getApi(): Promise<AxiosInstance> {
80 const { default: Axios } = await import("axios");
81
82 const domain = this.options.domain ?? "gitlab.com";
83 const token = this.options.token;
84
85 if (!token) {
86 throw new Error("GitLab Private Token is required!");
87 }
88
89 return Axios.create({
90 baseURL: `https://${domain ?? "gitlab.com"}/api/v4`,
91 headers: {
92 "PRIVATE-TOKEN": token,
93 },
94 });
95 }
96
97 private async getRemoteBranchInfo(
98 extras: ContextProviderExtras,
99 ): Promise<RemoteBranchInfo> {
100 const subprocess = await getSubprocess(extras);
101
102 const branchName = await subprocess("git branch --show-current");
103
104 const branchRemote = await subprocess(
105 `git config branch.${branchName}.remote`,
106 );
107
108 const branchInfo = await subprocess("git branch -vv");
109
110 const currentBranchInfo = branchInfo
111 .split("\n")
112 .find((line) => line.startsWith("*"));
113
114 const remoteMatches = RegExp(
115 `\\[${branchRemote}/(?<remote_branch>[^\\]]+)\\]`,
116 ).exec(currentBranchInfo!);
117
118 console.dir({ remoteMatches });
119
120 const remoteBranch = remoteMatches?.groups?.remote_branch ?? null;
121
122 const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
123
124 let urlMatches: RegExpExecArray | null;
125 if (/https?.*/.test(remoteUrl)) {
126 const pathname = new URL(remoteUrl).pathname;
127 urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
128 } else {
129 // ssh
130 urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
131 }
132
133 const project = urlMatches?.groups?.projectPath ?? null;
134
135 return {
136 branch: remoteBranch,
137 project,
138 };
139 }
140
141 async getContextItems(
142 query: string,
143 extras: ContextProviderExtras,
144 ): Promise<ContextItem[]> {
145 const { branch, project } = await this.getRemoteBranchInfo(extras);
146
147 const api = await this.getApi();
148
149 const result = [] as Array<ContextItem>;
150
151 try {
152 const mergeRequests = await api
153 .get<Array<GitLabMergeRequest>>(
154 `/projects/${encodeURIComponent(project!)}/merge_requests`,
155 {
156 params: {
157 source_branch: branch,
158 state: "opened",
159 },
160 },
161 )
162 .then((x) => x.data);
163
164 const subprocess = await getSubprocess(extras);
165
166 for (const mergeRequest of mergeRequests) {
167 const parts = [
168 `# GitLab Merge Request\ntitle: "${
169 mergeRequest.title
170 }"\ndescription: "${mergeRequest.description ?? "None"}"`,
171 "## Comments",
172 ];
173
174 const comments = await api.get<Array<GitLabComment>>(
175 `/projects/${mergeRequest.project_id}/merge_requests/${mergeRequest.iid}/notes`,
176 {
177 params: {
178 sort: "asc",
179 order_by: "created_at",
180 },
181 },
182 );
183
184 const filteredComments = comments.data.filter(
185 (x) => x.type === "DiffNote",
186 );
187
188 const locations = {} as Record<string, Array<GitLabComment>>;
189
190 for (const comment of filteredComments) {
191 const filename = comment.position?.new_path ?? "general";
192
193 if (!locations[filename]) {
194 locations[filename] = [];
195 }
196
197 locations[filename].push(comment);
198 }
199
200 if (extras.selectedCode.length && this.options.filterComments) {
201 const toRemove = Object.keys(locations).filter(
202 (filename) =>
203 !extras.selectedCode.find((selection) =>
204 selection.filepath.endsWith(filename),
205 ) && filename !== "general",
206 );
207 for (const filepath of toRemove) {
208 delete locations[filepath];
209 }
210 }
211
212 const commentFormatter = async (comment: GitLabComment) => {
213 const commentLabel = comment.body.includes("```suggestion")
214 ? "Code Suggestion"
215 : "Comment";
216 let result = `#### ${commentLabel}\nauthor: "${
217 comment.author.name
218 }"\ndate: "${comment.created_at}"\nresolved: ${
219 comment.resolved ? "Yes" : "No"
220 }`;
221
222 if (comment.position?.new_line) {
223 result += `\nline: ${comment.position.new_line}`;
224
225 if (comment.position.head_sha) {
226 const sourceLines = await subprocess(
227 `git show ${comment.position.head_sha}:${comment.position.new_path}`,
228 )
229 .then((result) => result.split("\n"))
230 .catch((ex) => []);
231
232 const line =
233 comment.position.new_line <= sourceLines.length
234 ? sourceLines[comment.position.new_line - 1]
235 : null;
236
237 if (line) {
238 result += `\nsource: \`${line}\``;
239 }
240 }
241 }
242
243 result += `\n\n${comment.body}`;
244
245 return result;
246 };
247
248 for (const [filename, locationComments] of Object.entries(locations)) {
249 if (filename !== "general") {
250 parts.push(`### File ${filename}`);
251 locationComments.sort(
252 (a, b) =>
253 (a.position?.new_line ?? 0) - (b.position?.new_line ?? 0),
254 );
255 } else {
256 parts.push("### General");
257 }
258
259 const commentSections = await Promise.all(
260 locationComments.map(commentFormatter),
261 );
262 parts.push(...commentSections);
263 }
264
265 const content = parts.join("\n\n");
266
267 result.push({
268 name: mergeRequest.title,
269 content,
270 description: "Comments from the Merge Request for this branch.",
271 });
272 }
273 } catch (ex) {
274 let content = "# GitLab Merge Request\n\nError getting merge request. ";
275 if (ex instanceof AxiosError) {
276 if (ex.response) {
277 const errorMessage = ex.response?.data
278 ? (ex.response.data.message ?? JSON.stringify(ex.response?.data))
279 : `${ex.response.status}: ${ex.response.statusText}`;
280 content += `GitLab Error: ${errorMessage}`;
281 } else {
282 content += `GitLab Request Error ${ex.request}`;
283 }
284 } else {
285 // @ts-ignore
286 content += `Unknown error: ${ex.message ?? JSON.stringify(ex)}`;
287 }
288
289 result.push({
290 name: "GitLab Merge Request",
291 content,
292 description: "Error getting the Merge Request for this branch.",
293 });
294 }
295
296 return result;
297 }
298}
299
300export default GitLabMergeRequestContextProvider;