Elffuss BraidHub

kikocis/continue public

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