| 1 | import { execSync } from "child_process"; |
| 2 | import * as fs from "fs"; |
| 3 | import * as path from "path"; |
| 4 | |
| 5 | import { |
| 6 | ContextItem, |
| 7 | ContextProviderDescription, |
| 8 | ContextProviderExtras, |
| 9 | } from "../../index.js"; |
| 10 | import { BaseContextProvider } from "../index.js"; |
| 11 | |
| 12 | class 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 | try { |
| 85 | const json = JSON.parse(rawText); |
| 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: |
| 90 | (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "", |
| 91 | })); |
| 92 | } catch (jsonError) { |
| 93 | throw new Error(`Failed to parse Greptile response:\n${rawText}`); |
| 94 | } |
| 95 | } catch (error) { |
| 96 | console.error("Error getting context items from Greptile:", error); |
| 97 | throw new Error("Error getting context items from Greptile"); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | private getGreptileToken(): string | undefined { |
| 102 | return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN; |
| 103 | } |
| 104 | |
| 105 | private getGithubToken(): string | undefined { |
| 106 | return this.options.GithubToken || process.env.GITHUB_TOKEN; |
| 107 | } |
| 108 | |
| 109 | private async getWorkspaceDir( |
| 110 | extras: ContextProviderExtras, |
| 111 | ): Promise<string | null> { |
| 112 | try { |
| 113 | const workspaceDirs = await extras.ide.getWorkspaceDirs(); |
| 114 | if (workspaceDirs && workspaceDirs.length > 0) { |
| 115 | return workspaceDirs[0]; |
| 116 | } else { |
| 117 | console.warn( |
| 118 | "extras.ide.getWorkspaceDirs() returned undefined or empty array.", |
| 119 | ); |
| 120 | } |
| 121 | } catch (err) { |
| 122 | console.warn( |
| 123 | "Failed to get workspace directories from extras.ide.getWorkspaceDirs():", |
| 124 | ); |
| 125 | } |
| 126 | |
| 127 | // Fallback to using Git commands |
| 128 | try { |
| 129 | const currentDir = process.cwd(); |
| 130 | if (this.isGitRepository(currentDir)) { |
| 131 | const workspaceDir = execSync("git rev-parse --show-toplevel") |
| 132 | .toString() |
| 133 | .trim(); |
| 134 | return workspaceDir; |
| 135 | } else { |
| 136 | console.warn( |
| 137 | `Current directory is not a Git repository: ${currentDir}`, |
| 138 | ); |
| 139 | return null; |
| 140 | } |
| 141 | } catch (err) { |
| 142 | console.warn("Failed to get workspace directory using Git commands: "); |
| 143 | return null; |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | private isGitRepository(dir: string): boolean { |
| 148 | try { |
| 149 | const gitDir = path.join(dir, ".git"); |
| 150 | return fs.existsSync(gitDir); |
| 151 | } catch (err) { |
| 152 | console.warn("Failed to check if directory is a Git repository:"); |
| 153 | return false; |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // Helper functions |
| 159 | function getRemoteUrl(absPath: string): string { |
| 160 | try { |
| 161 | const remote = execSync(`git -C ${absPath} remote get-url origin`) |
| 162 | .toString() |
| 163 | .trim(); |
| 164 | return remote; |
| 165 | } catch (err) { |
| 166 | console.warn("Failed to get remote URL"); |
| 167 | return ""; |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | function getCurrentBranch(absPath: string): string { |
| 172 | try { |
| 173 | const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`) |
| 174 | .toString() |
| 175 | .trim(); |
| 176 | return branch; |
| 177 | } catch (err) { |
| 178 | console.warn("Failed to get current branch"); |
| 179 | return "master"; // Default to 'master' if the current branch cannot be determined |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | function extractRepoName(remote: string): string { |
| 184 | if (remote.startsWith("http://") || remote.startsWith("https://")) { |
| 185 | const parts = remote.split("/"); |
| 186 | if (parts.length >= 2) { |
| 187 | return ( |
| 188 | parts[parts.length - 2] + |
| 189 | "/" + |
| 190 | parts[parts.length - 1].replace(".git", "") |
| 191 | ); |
| 192 | } |
| 193 | } else if (remote.startsWith("git@")) { |
| 194 | const parts = remote.split(":"); |
| 195 | if (parts.length >= 2) { |
| 196 | return parts[1].replace(".git", ""); |
| 197 | } |
| 198 | } |
| 199 | return ""; |
| 200 | } |
| 201 | |
| 202 | function getRemoteType(remote: string): string { |
| 203 | if (remote.includes("github.com")) { |
| 204 | return "github"; |
| 205 | } else if (remote.includes("gitlab.com")) { |
| 206 | return "gitlab"; |
| 207 | } else if (remote.includes("azure.com")) { |
| 208 | return "azure"; |
| 209 | } |
| 210 | return ""; |
| 211 | } |
| 212 | |
| 213 | export default GreptileContextProvider; |