Elffuss BraidHub

kikocis/continue public

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