Elffuss BraidHub

kikocis/continue public

21cf25b4ed37 · 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 } 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";
32import { tagToString } from "./utils";
33
34type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
35
36export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
37 relativeExpectedTime: number = 1;
38 artifactId = "codeSnippets";
39
40 constructor(private readonly ide: IDE) {}
41
42 private static async _createTables(db: DatabaseConnection) {
43 await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets (
44 id INTEGER PRIMARY KEY,
45 path TEXT NOT NULL,
46 cacheKey TEXT NOT NULL,
47 content TEXT NOT NULL,
48 title TEXT NOT NULL,
49 signature TEXT,
50 startLine INTEGER NOT NULL,
51 endLine INTEGER NOT NULL
52 )`);
53
54 await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags (
55 id INTEGER PRIMARY KEY AUTOINCREMENT,
56 tag TEXT NOT NULL,
57 snippetId INTEGER NOT NULL,
58 FOREIGN KEY (snippetId) REFERENCES code_snippets (id)
59 )`);
60
61 await migrate("add_signature_column", async () => {
62 const tableInfo = await db.all("PRAGMA table_info(code_snippets)");
63 const signatureColumnExists = tableInfo.some(
64 (column) => column.name === "signature",
65 );
66
67 if (!signatureColumnExists) {
68 await db.exec(`
69 ALTER TABLE code_snippets
70 ADD COLUMN signature TEXT;
71 `);
72 }
73 });
74
75 await migrate("delete_duplicate_code_snippets", async () => {
76 // Delete duplicate entries in code_snippets
77 await db.exec(`
78 DELETE FROM code_snippets
79 WHERE id NOT IN (
80 SELECT MIN(id)
81 FROM code_snippets
82 GROUP BY path, cacheKey, content, title, startLine, endLine
83 )
84 `);
85
86 // Add unique constraint if it doesn't exist
87 await db.exec(`
88 CREATE UNIQUE INDEX IF NOT EXISTS idx_code_snippets_unique
89 ON code_snippets (path, cacheKey, content, title, startLine, endLine)
90 `);
91
92 // Delete code_snippets associated with duplicate code_snippets_tags entries
93 await db.exec(`
94 DELETE FROM code_snippets
95 WHERE id IN (
96 SELECT snippetId
97 FROM code_snippets_tags
98 WHERE (snippetId, tag) IN (
99 SELECT snippetId, tag
100 FROM code_snippets_tags
101 GROUP BY snippetId, tag
102 HAVING COUNT(*) > 1
103 )
104 )
105 `);
106
107 // Delete duplicate entries
108 await db.exec(`
109 DELETE FROM code_snippets_tags
110 WHERE id NOT IN (
111 SELECT MIN(id)
112 FROM code_snippets_tags
113 GROUP BY snippetId, tag
114 )
115 `);
116
117 // Add unique constraint if it doesn't exist
118 await db.exec(`
119 CREATE UNIQUE INDEX IF NOT EXISTS idx_snippetId_tag
120 ON code_snippets_tags (snippetId, tag)
121 `);
122 });
123 }
124
125 private getSnippetsFromMatch(match: Parser.QueryMatch): SnippetChunk {
126 const bodyTypesToTreatAsSignatures = [
127 "interface_declaration", // TypeScript, Java
128 "struct_item", // Rust
129 "type_spec", // Go
130 ];
131
132 const bodyCaptureGroupPrefixes = ["definition", "reference"];
133
134 let title = "",
135 content = "",
136 signature = "",
137 startLine = 0,
138 endLine = 0,
139 hasSeenBody = false;
140
141 // This loop assumes that the ordering of the capture groups is represenatative
142 // of the structure of the language, e.g. for a TypeScript match on a function,
143 // `function myFunc(param: string): string`, the first capture would be the `myFunc`
144 // the second capture would be the `(param: string)`, etc
145 for (const { name, node } of match.captures) {
146 // Assume we are capturing groups using a dot syntax for more precise groupings
147 // However, for this case, we only care about the first substring
148 const trimmedCaptureName = name.split(".")[0];
149
150 const nodeText = node.text;
151 const nodeType = node.type;
152
153 if (bodyCaptureGroupPrefixes.includes(trimmedCaptureName)) {
154 if (bodyTypesToTreatAsSignatures.includes(nodeType)) {
155 // Note we override whatever existing value there is here
156 signature = nodeText;
157 hasSeenBody = true;
158 }
159
160 content = nodeText;
161 startLine = node.startPosition.row;
162 endLine = node.endPosition.row;
163 } else {
164 if (trimmedCaptureName === "name") {
165 title = nodeText;
166 }
167
168 if (!hasSeenBody) {
169 signature += nodeText + " ";
170
171 if (trimmedCaptureName === "comment") {
172 signature += "\n";
173 }
174 }
175 }
176 }
177
178 return { title, content, signature, startLine, endLine };
179 }
180
181 async getSnippetsInFile(
182 filepath: string,
183 contents: string,
184 ): Promise<SnippetChunk[]> {
185 const parser = await getParserForFile(filepath);
186
187 if (!parser) {
188 return [];
189 }
190
191 const ast = parser.parse(contents);
192
193 const language = getFullLanguageName(filepath);
194 if (!language) {
195 return [];
196 }
197 const query = await getQueryForFile(
198 filepath,
199 `code-snippet-queries/${language}.scm`,
200 );
201 const matches = query?.matches(ast.rootNode);
202
203 if (!matches) {
204 return [];
205 }
206
207 return matches.map(this.getSnippetsFromMatch);
208 }
209
210 async *update(
211 tag: IndexTag,
212 results: RefreshIndexResults,
213 markComplete: MarkCompleteCallback,
214 repoName: string | undefined,
215 ): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
216 const db = await SqliteDb.get();
217 await CodeSnippetsCodebaseIndex._createTables(db);
218 const tagString = tagToString(tag);
219
220 // Compute
221 for (let i = 0; i < results.compute.length; i++) {
222 const compute = results.compute[i];
223
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}