continue-custom/core/context/providers/GitLabMergeRequestContextProvider.ts
Nate Sesti 3bd9c8996c
💫 Preview (#996)
* feat: add fixed version of the nodejs

* revert accidentally committed files

* add: unified version of the Node.js that is used locally and on Github Actions

* Set itemType for querySubmenuItem

This is necessary before calling props.command the same way we do it for non-query item types. Otherwise we receive an 'Unknow provider...' error message in the 'getContextItems' case in the 'panel.webview.onDidReceiveMessage, callback.

* include @vscode node module folder

we need the @vscode folder containing ripgrep in the distribution.

* Amended path for ripgrep executable

We have to preprend the 'out' folder in order to find the ripgrep executable in the distribution.
Prepending 'out' during development is not necessary. We need a way to distinguish in 'ideProtocol'?

* implemented locals context provider

* normal to submenu(select thread) for the locals provider

* added code context from the call stack

* use parameter for callstack retrieving

* added thread filtering and handle a edge case

* revert accidentally committed file

* temporary fix to use refreshSubmenuItems

* added updateSubmenuItems request

* refactor: changed the interface of threads

* polished format and file reading

* added a little doc

* typo

* revert accidentally committed file

* ✨ UI for JetBrains autocomplete

* 🎨 decouple autocomplete from VS Code extension

* ✨ autocomplete in core protocol

* 🚧 jetbrains autocomplete fixes

* 🐛 successfully get responses for jetbrains autocomplete

* Refactored web crawling code for document indexing. The updated code uses a breadth-first search, filters out specific paths, and ensures that websites are not downloaded twice.

* update hasDocs to use new pattern

* feat: add gitlab context class

* feat: update to work as normal context provider

* fix: add context provider

* feat: add code that comment is based on

* docs: add documentation

* feat: enable comment filtering

* 🐛 fix autocomplete with azure

* ✨ jetbrains multiline completions

* 🐛 fix file reading in autocomplete

* ✨ option to disable jetbrains autocomplete

* 📌 update package-lock files

* 🐛 fix localhost ollama bug with jetbrains binary

* 🔥 disable apply to file in jetbrains for now

* 🚸 fix constant re-rendering of code vision in jetbrains

* 🔖 update package.json versiojn

* 🐛 don't override user temperature value for tab autocomplete model

* Fix chat msg formatting in Output for image models (#971)

* 📝 tweak docs for "locals" ctx provider

* 🩹 small tweak to link filtering logic

* Add more C++ extensions for AST parser (#972)

* 🔥 remove ruby example file

* add claude3 to free trial

* 🐛 fix codelens in tutorial

* 🧱 change server url

* 🐛 don't send image_url if not image type

* 🔧 update config schemas

* 📌 update npm version to v20.11.0

* 📈 Locally track tokens generated and show stats (#987)

* ✨ log tokens generated locally

* 💄 UI for usage stats

* 🔥 delete unused test file

* 🚚 rename core package for publishing on npm

* Remove duplicate itemType property (#986)

* 🔒️ add .env to .gitignore for npm package

* Add SystemContextProvider to context providers so that users can use … (#988)

* Add SystemContextProvider to context providers so that users can use their own system cpu and os for a resource

* change to OSContextProvider

* update descriptor

* 🎨 export transformers.js

* 🐛 fix /edit for anthropic

* 🚑 fix autocomplete by binding function

---------

Co-authored-by: my8bit <mail@my8bit.name>
Co-authored-by: Ihor Pavlenko <my8bit@users.noreply.github.com>
Co-authored-by: Lars Pagh <lp@airsupport.dk>
Co-authored-by: commandblock2 <tony_hu@live.com>
Co-authored-by: Jason Jacobs <nerfnerd@gmail.com>
Co-authored-by: Ben Force <benforce@gmail.com>
Co-authored-by: Peter Zaback <pzaback@gmail.com>
Co-authored-by: SR_team <sr_team@sr.team>
2024-03-19 10:35:28 -07:00

277 lines
No EOL
7.6 KiB
TypeScript

import { AxiosInstance, AxiosError } from "axios";
import {BaseContextProvider} from "..";
import { ContextProviderExtras, ContextItem, ContextProviderDescription } from "../..";
interface RemoteBranchInfo {
branch: string | null;
project: string | null;
}
interface GitLabUser {
id: number;
username: string;
name: string;
state: "active";
locked: boolean;
avatar_url: string;
web_url: string;
}
interface GitLabMergeRequest {
iid: number;
project_id: number;
title: string;
description: string;
}
interface GitLabComment {
type: null | "DiffNote";
resolvable: boolean;
resolved?: boolean;
body: string;
created_at: string;
author: GitLabUser;
position?: {
new_path: string;
new_line: number;
head_sha: string;
line_range: {
start: {
line_code: string;
type: "new";
old_line: null;
new_line: number;
};
end: {
line_code: string;
type: "new";
old_line: null;
new_line: number;
};
};
};
}
const trimFirstElement = (args: Array<string>): string => {
return args[0].trim();
};
const getSubprocess = async (extras: ContextProviderExtras) => {
const workingDir = await extras.ide
.getWorkspaceDirs()
.then(trimFirstElement);
return (command: string) =>
extras.ide
.subprocess(`cd ${workingDir}; ${command}`)
.then(trimFirstElement);
};
class GitLabMergeRequestContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: 'gitlab-mr',
displayTitle: 'GitLab Merge Request',
description: 'Reference comments in a GitLab Merge Request',
type: 'normal'
};
private async getApi(): Promise<AxiosInstance> {
const { default: Axios } = await import("axios");
const domain = this.options.domain ?? "gitlab.com";
const token = this.options.token;
if(!token) {
throw new Error(`GitLab Private Token is required!`);
}
return Axios.create({
baseURL: `https://${domain ?? "gitlab.com"}/api/v4`,
headers: {
"PRIVATE-TOKEN": token,
},
});
};
private async getRemoteBranchName(extras: ContextProviderExtras): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
const branchName = await subprocess(`git branch --show-current`);
const branchRemote = await subprocess(
`git config branch.${branchName}.remote`
);
const branchInfo = await subprocess(`git branch -vv`);
const currentBranchInfo = branchInfo
.split("\n")
.find((line) => line.startsWith("*"));
const remoteMatches = RegExp(
`\\[${branchRemote}/(?<remote_branch>[^\\]]+)\\]`
).exec(currentBranchInfo!);
console.dir({ remoteMatches });
const remoteBranch = remoteMatches?.groups?.["remote_branch"] ?? null;
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = RegExp(`:(?<project>.*).git`).exec(remoteUrl);
const project = urlMatches?.groups?.["project"] ?? null;
return {
branch: remoteBranch,
project,
};
};
async getContextItems(query: string, extras: ContextProviderExtras): Promise<ContextItem[]> {
const { branch, project } = await this.getRemoteBranchName(extras);
const api = await this.getApi();
const result = [] as Array<ContextItem>;
try {
const mergeRequests = await api
.get<Array<GitLabMergeRequest>>(
`/projects/${encodeURIComponent(project!)}/merge_requests`,
{
params: {
source_branch: branch,
state: "opened",
},
}
)
.then((x) => x.data);
const subprocess = await getSubprocess(extras);
for (const mergeRequest of mergeRequests) {
const parts = [
`# GitLab Merge Request\ntitle: "${mergeRequest.title}"\ndescription: "${mergeRequest.description ?? 'None'}"`,
`## Comments`,
];
const comments = await api.get<Array<GitLabComment>>(
`/projects/${mergeRequest.project_id}/merge_requests/${mergeRequest.iid}/notes`,
{
params: {
sort: "asc",
order_by: "created_at",
},
}
);
const filteredComments = comments.data.filter(
(x) => x.type === "DiffNote"
);
const locations = {} as Record<string, Array<GitLabComment>>;
for (const comment of filteredComments) {
const filename = comment.position?.new_path ?? "general";
if (!locations[filename]) {
locations[filename] = [];
}
locations[filename].push(comment);
}
if (extras.selectedCode.length && this.options.filterComments) {
const toRemove = Object.keys(locations).filter(filename => !extras.selectedCode.find(selection => selection.filepath.endsWith(filename)) && filename !== "general");
for (const filepath of toRemove) {
delete locations[filepath];
}
}
const commentFormatter = async (comment: GitLabComment) => {
const commentLabel = comment.body.includes("```suggestion") ? 'Code Suggestion' : 'Comment';
let result = `#### ${commentLabel}\nauthor: "${comment.author.name}"\ndate: "${comment.created_at}"\nresolved: ${
comment.resolved ? "Yes" : "No"
}`;
if (comment.position?.new_line) {
result += `\nline: ${comment.position.new_line}`;
if (comment.position.head_sha) {
const sourceLines = await subprocess(`git show ${comment.position.head_sha}:${comment.position.new_path}`).then(result => result.split("\n")).catch(ex => []);
const line = comment.position.new_line <= sourceLines.length ? sourceLines[comment.position.new_line - 1] : null;
if (line) {
result += `\nsource: \`${line}\``;
}
}
}
result += `\n\n${comment.body}`;
return result;
};
for (const [filename, locationComments] of Object.entries(locations)) {
if (filename !== "general") {
parts.push(`### File ${filename}`);
locationComments.sort(
(a, b) => a.position!.new_line - b.position!.new_line
);
} else {
parts.push("### General");
}
const commentSections = await Promise.all(locationComments.map(commentFormatter));
parts.push(...commentSections);
}
const content = parts.join("\n\n");
result.push(
{
name: mergeRequest.title,
content,
description: `Comments from the Merge Request for this branch.`,
},
);
}
} catch (ex) {
let content = `# GitLab Merge Request\n\nError getting merge request. `;
if (ex instanceof AxiosError) {
if (ex.response) {
const errorMessage = ex.response?.data ? ex.response.data.message ?? JSON.stringify(ex.response?.data) : `${ex.response.status}: ${ex.response.statusText}`;
content += `GitLab Error: ${errorMessage}`;
} else {
content += `GitLab Request Error ${ex.request}`;
}
} else {
// @ts-ignore
content += `Unknown error: ${ex.message ?? JSON.stringify(ex)}`;
}
result.push(
{
name: `GitLab Merge Request`,
content,
description: `Error getting the Merge Request for this branch.`,
},
);
}
return result;
}
}
export default GitLabMergeRequestContextProvider;