| 1 | import Parser from "web-tree-sitter"; |
| 2 | |
| 3 | import { migrate } from "../util/paths"; |
| 4 | import { |
| 5 | getFullLanguageName, |
| 6 | getParserForFile, |
| 7 | getQueryForFile, |
| 8 | } from "../util/treeSitter"; |
| 9 | |
| 10 | import { DatabaseConnection, SqliteDb } from "./refreshIndex"; |
| 11 | import { |
| 12 | IndexResultType, |
| 13 | MarkCompleteCallback, |
| 14 | RefreshIndexResults, |
| 15 | type CodebaseIndex, |
| 16 | } from "./types"; |
| 17 | |
| 18 | import type { |
| 19 | ChunkWithoutID, |
| 20 | ContextItem, |
| 21 | ContextSubmenuItem, |
| 22 | IDE, |
| 23 | IndexTag, |
| 24 | IndexingProgressUpdate, |
| 25 | } from "../"; |
| 26 | import { |
| 27 | findUriInDirs, |
| 28 | getLastNPathParts, |
| 29 | getLastNUriRelativePathParts, |
| 30 | getUriPathBasename, |
| 31 | } from "../util/uri"; |
| 32 | import { tagToString } from "./utils"; |
| 33 | |
| 34 | type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; |
| 35 | |
| 36 | export class CodeSnippetsCodebaseIndex implements CodebaseIndex { |
| 37 | relativeExpectedTime: number = 1; |
| 38 | static artifactId = "codeSnippets"; |
| 39 | artifactId: string = CodeSnippetsCodebaseIndex.artifactId; |
| 40 | |
| 41 | constructor(private readonly ide: IDE) {} |
| 42 | |
| 43 | private static async _createTables(db: DatabaseConnection) { |
| 44 | await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets ( |
| 45 | id INTEGER PRIMARY KEY, |
| 46 | path TEXT NOT NULL, |
| 47 | cacheKey TEXT NOT NULL, |
| 48 | content TEXT NOT NULL, |
| 49 | title TEXT NOT NULL, |
| 50 | signature TEXT, |
| 51 | startLine INTEGER NOT NULL, |
| 52 | endLine INTEGER NOT NULL |
| 53 | )`); |
| 54 | |
| 55 | await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags ( |
| 56 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 57 | tag TEXT NOT NULL, |
| 58 | snippetId INTEGER NOT NULL, |
| 59 | FOREIGN KEY (snippetId) REFERENCES code_snippets (id) |
| 60 | )`); |
| 61 | |
| 62 | await migrate("add_signature_column", async () => { |
| 63 | const tableInfo = await db.all("PRAGMA table_info(code_snippets)"); |
| 64 | const signatureColumnExists = tableInfo.some( |
| 65 | (column) => column.name === "signature", |
| 66 | ); |
| 67 | |
| 68 | if (!signatureColumnExists) { |
| 69 | await db.exec(` |
| 70 | ALTER TABLE code_snippets |
| 71 | ADD COLUMN signature TEXT; |
| 72 | `); |
| 73 | } |
| 74 | }); |
| 75 | |
| 76 | await migrate("delete_duplicate_code_snippets", async () => { |
| 77 | // Delete duplicate entries in code_snippets |
| 78 | await db.exec(` |
| 79 | DELETE FROM code_snippets |
| 80 | WHERE id NOT IN ( |
| 81 | SELECT MIN(id) |
| 82 | FROM code_snippets |
| 83 | GROUP BY path, cacheKey, content, title, startLine, endLine |
| 84 | ) |
| 85 | `); |
| 86 | |
| 87 | // Add unique constraint if it doesn't exist |
| 88 | await db.exec(` |
| 89 | CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique |
| 90 | ON code_snippets (path, cacheKey, content, title, startLine, endLine) |
| 91 | `); |
| 92 | |
| 93 | // Delete code_snippets associated with duplicate code_snippets_tags entries |
| 94 | await db.exec(` |
| 95 | DELETE FROM code_snippets |
| 96 | WHERE id IN ( |
| 97 | SELECT snippetId |
| 98 | FROM code_snippets_tags |
| 99 | WHERE (snippetId, tag) IN ( |
| 100 | SELECT snippetId, tag |
| 101 | FROM code_snippets_tags |
| 102 | GROUP BY snippetId, tag |
| 103 | HAVING COUNT(*) > 1 |
| 104 | ) |
| 105 | ) |
| 106 | `); |
| 107 | |
| 108 | // Delete duplicate entries |
| 109 | await db.exec(` |
| 110 | DELETE FROM code_snippets_tags |
| 111 | WHERE id NOT IN ( |
| 112 | SELECT MIN(id) |
| 113 | FROM code_snippets_tags |
| 114 | GROUP BY snippetId, tag |
| 115 | ) |
| 116 | `); |
| 117 | |
| 118 | // Add unique constraint if it doesn't exist |
| 119 | await db.exec(` |
| 120 | CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag |
| 121 | ON code_snippets_tags (snippetId, tag) |
| 122 | `); |
| 123 | }); |
| 124 | } |
| 125 | |
| 126 | private getSnippetsFromMatch(match: Parser.QueryMatch): SnippetChunk { |
| 127 | const bodyTypesToTreatAsSignatures = [ |
| 128 | "interface_declaration", // TypeScript, Java |
| 129 | "struct_item", // Rust |
| 130 | "type_spec", // Go |
| 131 | ]; |
| 132 | |
| 133 | const bodyCaptureGroupPrefixes = ["definition", "reference"]; |
| 134 | |
| 135 | let title = "", |
| 136 | content = "", |
| 137 | signature = "", |
| 138 | startLine = 0, |
| 139 | endLine = 0, |
| 140 | hasSeenBody = false; |
| 141 | |
| 142 | // This loop assumes that the ordering of the capture groups is represenatative |
| 143 | // of the structure of the language, e.g. for a TypeScript match on a function, |
| 144 | // `function myFunc(param: string): string`, the first capture would be the `myFunc` |
| 145 | // the second capture would be the `(param: string)`, etc |
| 146 | for (const { name, node } of match.captures) { |
| 147 | // Assume we are capturing groups using a dot syntax for more precise groupings |
| 148 | // However, for this case, we only care about the first substring |
| 149 | const trimmedCaptureName = name.split(".")[0]; |
| 150 | |
| 151 | const nodeText = node.text; |
| 152 | const nodeType = node.type; |
| 153 | |
| 154 | if (bodyCaptureGroupPrefixes.includes(trimmedCaptureName)) { |
| 155 | if (bodyTypesToTreatAsSignatures.includes(nodeType)) { |
| 156 | // Note we override whatever existing value there is here |
| 157 | signature = nodeText; |
| 158 | hasSeenBody = true; |
| 159 | } |
| 160 | |
| 161 | content = nodeText; |
| 162 | startLine = node.startPosition.row; |
| 163 | endLine = node.endPosition.row; |
| 164 | } else { |
| 165 | if (trimmedCaptureName === "name") { |
| 166 | title = nodeText; |
| 167 | } |
| 168 | |
| 169 | if (!hasSeenBody) { |
| 170 | signature += nodeText + " "; |
| 171 | |
| 172 | if (trimmedCaptureName === "comment") { |
| 173 | signature += "\n"; |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | return { title, content, signature, startLine, endLine }; |
| 180 | } |
| 181 | |
| 182 | async getSnippetsInFile( |
| 183 | filepath: string, |
| 184 | contents: string, |
| 185 | ): Promise<SnippetChunk[]> { |
| 186 | const parser = await getParserForFile(filepath); |
| 187 | |
| 188 | if (!parser) { |
| 189 | return []; |
| 190 | } |
| 191 | |
| 192 | const ast = parser.parse(contents); |
| 193 | |
| 194 | const language = getFullLanguageName(filepath); |
| 195 | if (!language) { |
| 196 | return []; |
| 197 | } |
| 198 | const query = await getQueryForFile( |
| 199 | filepath, |
| 200 | `code-snippet-queries/${language}.scm`, |
| 201 | ); |
| 202 | const matches = query?.matches(ast.rootNode); |
| 203 | |
| 204 | if (!matches) { |
| 205 | return []; |
| 206 | } |
| 207 | |
| 208 | return matches.map(this.getSnippetsFromMatch); |
| 209 | } |
| 210 | |
| 211 | async *update( |
| 212 | tag: IndexTag, |
| 213 | results: RefreshIndexResults, |
| 214 | markComplete: MarkCompleteCallback, |
| 215 | repoName: string | undefined, |
| 216 | ): AsyncGenerator<IndexingProgressUpdate, any, unknown> { |
| 217 | const db = await SqliteDb.get(); |
| 218 | await CodeSnippetsCodebaseIndex._createTables(db); |
| 219 | const tagString = tagToString(tag); |
| 220 | |
| 221 | // Compute |
| 222 | for (let i = 0; i < results.compute.length; i++) { |
| 223 | const compute = results.compute[i]; |
| 224 | let snippets: SnippetChunk[] = []; |
| 225 | try { |
| 226 | snippets = await this.getSnippetsInFile( |
| 227 | compute.path, |
| 228 | await this.ide.readFile(compute.path), |
| 229 | ); |
| 230 | } catch (e) { |
| 231 | // If can't parse, assume malformatted code |
| 232 | } |
| 233 | |
| 234 | // Add snippets to sqlite |
| 235 | for (const snippet of snippets) { |
| 236 | const { lastID } = await db.run( |
| 237 | "REPLACE INTO code_snippets (path, cacheKey, content, title, signature, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?, ?)", |
| 238 | [ |
| 239 | compute.path, |
| 240 | compute.cacheKey, |
| 241 | snippet.content, |
| 242 | snippet.title, |
| 243 | snippet.signature, |
| 244 | snippet.startLine, |
| 245 | snippet.endLine, |
| 246 | ], |
| 247 | ); |
| 248 | |
| 249 | await db.run( |
| 250 | "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", |
| 251 | [lastID, tagString], |
| 252 | ); |
| 253 | } |
| 254 | |
| 255 | yield { |
| 256 | desc: `Indexing ${getUriPathBasename(compute.path)}`, |
| 257 | progress: i / results.compute.length, |
| 258 | status: "indexing", |
| 259 | }; |
| 260 | await markComplete([compute], IndexResultType.Compute); |
| 261 | } |
| 262 | |
| 263 | // Delete |
| 264 | for (let i = 0; i < results.del.length; i++) { |
| 265 | const del = results.del[i]; |
| 266 | |
| 267 | const snippets = await db.all( |
| 268 | "SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?", |
| 269 | [del.path, del.cacheKey], |
| 270 | ); |
| 271 | |
| 272 | if (snippets) { |
| 273 | const snippetIds = snippets.map((row) => row.id).join(","); |
| 274 | |
| 275 | await db.run(`DELETE FROM code_snippets WHERE id IN (${snippetIds})`); |
| 276 | |
| 277 | await db.run( |
| 278 | `DELETE FROM code_snippets_tags WHERE snippetId IN (${snippetIds})`, |
| 279 | ); |
| 280 | } |
| 281 | |
| 282 | await markComplete([del], IndexResultType.Delete); |
| 283 | } |
| 284 | |
| 285 | // Add tag |
| 286 | for (let i = 0; i < results.addTag.length; i++) { |
| 287 | const addTag = results.addTag[i]; |
| 288 | let snippets: SnippetChunk[] = []; |
| 289 | try { |
| 290 | snippets = await this.getSnippetsInFile( |
| 291 | addTag.path, |
| 292 | await this.ide.readFile(addTag.path), |
| 293 | ); |
| 294 | } catch (e) { |
| 295 | // If can't parse, assume malformatted code |
| 296 | } |
| 297 | |
| 298 | for (const snippet of snippets) { |
| 299 | const { lastID } = await db.run( |
| 300 | "REPLACE INTO code_snippets (path, cacheKey, content, title, signature, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?, ?)", |
| 301 | [ |
| 302 | addTag.path, |
| 303 | addTag.cacheKey, |
| 304 | snippet.content, |
| 305 | snippet.title, |
| 306 | snippet.signature, |
| 307 | snippet.startLine, |
| 308 | snippet.endLine, |
| 309 | ], |
| 310 | ); |
| 311 | await db.run( |
| 312 | "REPLACE INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)", |
| 313 | [lastID, tagString], |
| 314 | ); |
| 315 | } |
| 316 | |
| 317 | await markComplete([results.addTag[i]], IndexResultType.AddTag); |
| 318 | } |
| 319 | |
| 320 | // Remove tag |
| 321 | for (let i = 0; i < results.removeTag.length; i++) { |
| 322 | const removeTag = results.removeTag[i]; |
| 323 | |
| 324 | let snippets = await db.get( |
| 325 | `SELECT id FROM code_snippets |
| 326 | WHERE cacheKey = ? AND path = ?`, |
| 327 | [removeTag.cacheKey, removeTag.path], |
| 328 | ); |
| 329 | |
| 330 | if (snippets) { |
| 331 | if (!Array.isArray(snippets)) { |
| 332 | snippets = [snippets]; |
| 333 | } |
| 334 | |
| 335 | const snippetIds = snippets.map((row: any) => row.id).join(","); |
| 336 | |
| 337 | await db.run( |
| 338 | ` |
| 339 | DELETE FROM code_snippets_tags |
| 340 | WHERE tag = ? |
| 341 | AND snippetId IN (${snippetIds}) |
| 342 | `, |
| 343 | [tagString], |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | await markComplete([results.removeTag[i]], IndexResultType.RemoveTag); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | static async getForId( |
| 352 | id: number, |
| 353 | workspaceDirs: string[], |
| 354 | ): Promise<ContextItem> { |
| 355 | const db = await SqliteDb.get(); |
| 356 | const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]); |
| 357 | |
| 358 | const last2Parts = getLastNUriRelativePathParts(workspaceDirs, row.path, 2); |
| 359 | const { relativePathOrBasename } = findUriInDirs(row.path, workspaceDirs); |
| 360 | return { |
| 361 | name: row.title, |
| 362 | description: last2Parts, |
| 363 | content: `\`\`\`${relativePathOrBasename}\n${row.content}\n\`\`\``, |
| 364 | uri: { |
| 365 | type: "file", |
| 366 | value: row.path, |
| 367 | }, |
| 368 | }; |
| 369 | } |
| 370 | |
| 371 | static async getAll(tag: IndexTag): Promise<ContextSubmenuItem[]> { |
| 372 | const db = await SqliteDb.get(); |
| 373 | await CodeSnippetsCodebaseIndex._createTables(db); |
| 374 | try { |
| 375 | const rows = await db.all( |
| 376 | `SELECT cs.id, cs.path, cs.title |
| 377 | FROM code_snippets cs |
| 378 | JOIN code_snippets_tags cst ON cs.id = cst.snippetId |
| 379 | WHERE cst.tag = ?; |
| 380 | `, |
| 381 | [tagToString(tag)], |
| 382 | ); |
| 383 | |
| 384 | return rows.map((row) => ({ |
| 385 | title: row.title, |
| 386 | description: getLastNPathParts(row.path, 2), |
| 387 | id: row.id.toString(), |
| 388 | })); |
| 389 | } catch (e) { |
| 390 | console.warn("Error getting all code snippets: ", e); |
| 391 | return []; |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | static async getPathsAndSignatures( |
| 396 | workspaceDirs: string[], |
| 397 | uriOffset: number = 0, |
| 398 | uriBatchSize: number = 100, |
| 399 | snippetOffset: number = 0, |
| 400 | snippetBatchSize: number = 100, |
| 401 | ): Promise<{ |
| 402 | groupedByUri: { [path: string]: string[] }; |
| 403 | hasMoreSnippets: boolean; |
| 404 | hasMoreUris: boolean; |
| 405 | }> { |
| 406 | const db = await SqliteDb.get(); |
| 407 | await CodeSnippetsCodebaseIndex._createTables(db); |
| 408 | |
| 409 | const endIndex = uriOffset + uriBatchSize; |
| 410 | const uriBatch = workspaceDirs.slice(uriOffset, endIndex); |
| 411 | |
| 412 | const likePatterns = uriBatch.map((dir) => `${dir}%`); |
| 413 | |
| 414 | const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); |
| 415 | |
| 416 | const query = ` |
| 417 | SELECT DISTINCT path, signature |
| 418 | FROM code_snippets |
| 419 | WHERE path LIKE ${placeholders} |
| 420 | ORDER BY path, signature |
| 421 | LIMIT ? OFFSET ? |
| 422 | `; |
| 423 | |
| 424 | const rows = await db.all(query, [ |
| 425 | ...likePatterns, |
| 426 | snippetBatchSize, |
| 427 | snippetOffset, |
| 428 | ]); |
| 429 | |
| 430 | const groupedByUri: { [path: string]: string[] } = {}; |
| 431 | |
| 432 | for (const { path, signature } of rows) { |
| 433 | if (!groupedByUri[path]) { |
| 434 | groupedByUri[path] = []; |
| 435 | } |
| 436 | groupedByUri[path].push(signature); |
| 437 | } |
| 438 | |
| 439 | const hasMoreUris = endIndex < workspaceDirs.length; |
| 440 | const hasMoreSnippets = rows.length === snippetBatchSize; |
| 441 | |
| 442 | return { groupedByUri, hasMoreUris, hasMoreSnippets }; |
| 443 | } |
| 444 | } |