Elffuss BraidHub

kikocis/continue public

main · 6.1 KiBRawPermalink
1import { execSync } from "child_process";
2import * as fs from "fs";
3import * as path from "path";
4
5import {
6 ContextItem,
7 ContextProviderDescription,
8 ContextProviderExtras,
9} from "../../index.js";
10import { BaseContextProvider } from "../index.js";
11
12class GreptileContextProvider extends BaseContextProvider {
13 static description: ContextProviderDescription = {
14 title: "greptile",
15 displayTitle: "Greptile",
16 description: "Insert query to Greptile",
17 type: "query",
18 };
19
20 get deprecationMessage() {
21 return "The Greptile context provider is now deprecated and will be removed in a later version. Please consider viewing their docs at greptile.com/docs/code-review-bot/auto-resolve-with-mcp for resolving greptile queries.";
22 }
23
24 async getContextItems(
25 query: string,
26 extras: ContextProviderExtras,
27 ): Promise<ContextItem[]> {
28 const greptileToken = this.getGreptileToken();
29 if (!greptileToken) {
30 throw new Error("Greptile token not found.");
31 }
32
33 const githubToken = this.getGithubToken();
34 if (!githubToken) {
35 throw new Error("GitHub token not found.");
36 }
37
38 let absPath = await this.getWorkspaceDir(extras);
39 if (!absPath) {
40 throw new Error("Failed to determine the workspace directory.");
41 }
42
43 var remoteUrl = getRemoteUrl(absPath);
44 remoteUrl = getRemoteUrl(absPath);
45 const repoName = extractRepoName(remoteUrl);
46 const branch = getCurrentBranch(absPath);
47 const remoteType = getRemoteType(remoteUrl);
48
49 if (!remoteType) {
50 throw new Error("Unable to determine remote type.");
51 }
52
53 const options = {
54 method: "POST",
55 headers: {
56 Authorization: `Bearer ${greptileToken}`,
57 "X-GitHub-Token": githubToken,
58 "Content-Type": "application/json",
59 },
60 body: JSON.stringify({
61 messages: [{ id: "<string>", content: query, role: "user" }],
62 repositories: [
63 {
64 remote: remoteType,
65 branch: branch,
66 repository: repoName,
67 },
68 ],
69 sessionId: extras.config.userToken || "default-session",
70 stream: false,
71 genius: true,
72 }),
73 };
74
75 try {
76 const response = await extras.fetch(
77 "https://api.greptile.com/v2/query",
78 options,
79 );
80 const rawText = await response.text();
81
82 // Check for HTTP errors
83 if (!response.ok) {
84 throw new Error(`HTTP error! status: ${response.status}`);
85 }
86
87 // Parse the response as JSON
88 try {
89 const json = JSON.parse(rawText);
90 return json.sources.map((source: any) => ({
91 description: source.filepath,
92 content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
93 name:
94 (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
95 }));
96 } catch (jsonError) {
97 throw new Error(`Failed to parse Greptile response:\n${rawText}`);
98 }
99 } catch (error) {
100 console.error("Error getting context items from Greptile:", error);
101 throw new Error("Error getting context items from Greptile");
102 }
103 }
104
105 private getGreptileToken(): string | undefined {
106 return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN;
107 }
108
109 private getGithubToken(): string | undefined {
110 return this.options.GithubToken || process.env.GITHUB_TOKEN;
111 }
112
113 private async getWorkspaceDir(
114 extras: ContextProviderExtras,
115 ): Promise<string | null> {
116 try {
117 const workspaceDirs = await extras.ide.getWorkspaceDirs();
118 if (workspaceDirs && workspaceDirs.length > 0) {
119 return workspaceDirs[0];
120 } else {
121 console.warn(
122 "extras.ide.getWorkspaceDirs() returned undefined or empty array.",
123 );
124 }
125 } catch (err) {
126 console.warn(
127 "Failed to get workspace directories from extras.ide.getWorkspaceDirs():",
128 );
129 }
130
131 // Fallback to using Git commands
132 try {
133 const currentDir = process.cwd();
134 if (this.isGitRepository(currentDir)) {
135 const workspaceDir = execSync("git rev-parse --show-toplevel")
136 .toString()
137 .trim();
138 return workspaceDir;
139 } else {
140 console.warn(
141 `Current directory is not a Git repository: ${currentDir}`,
142 );
143 return null;
144 }
145 } catch (err) {
146 console.warn("Failed to get workspace directory using Git commands: ");
147 return null;
148 }
149 }
150
151 private isGitRepository(dir: string): boolean {
152 try {
153 const gitDir = path.join(dir, ".git");
154 return fs.existsSync(gitDir);
155 } catch (err) {
156 console.warn("Failed to check if directory is a Git repository:");
157 return false;
158 }
159 }
160}
161
162// Helper functions
163function getRemoteUrl(absPath: string): string {
164 try {
165 const remote = execSync(`git -C ${absPath} remote get-url origin`)
166 .toString()
167 .trim();
168 return remote;
169 } catch (err) {
170 console.warn("Failed to get remote URL");
171 return "";
172 }
173}
174
175function getCurrentBranch(absPath: string): string {
176 try {
177 const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`)
178 .toString()
179 .trim();
180 return branch;
181 } catch (err) {
182 console.warn("Failed to get current branch");
183 return "master"; // Default to 'master' if the current branch cannot be determined
184 }
185}
186
187function extractRepoName(remote: string): string {
188 if (remote.startsWith("http://") || remote.startsWith("https://")) {
189 const parts = remote.split("/");
190 if (parts.length >= 2) {
191 return (
192 parts[parts.length - 2] +
193 "/" +
194 parts[parts.length - 1].replace(".git", "")
195 );
196 }
197 } else if (remote.startsWith("git@")) {
198 const parts = remote.split(":");
199 if (parts.length >= 2) {
200 return parts[1].replace(".git", "");
201 }
202 }
203 return "";
204}
205
206function getRemoteType(remote: string): string {
207 if (remote.includes("github.com")) {
208 return "github";
209 } else if (remote.includes("gitlab.com")) {
210 return "gitlab";
211 } else if (remote.includes("azure.com")) {
212 return "azure";
213 }
214 return "";
215}
216
217export default GreptileContextProvider;