-
Notifications
You must be signed in to change notification settings - Fork 777
/
CodeSnippetsIndex.ts
225 lines (203 loc) · 6.24 KB
/
CodeSnippetsIndex.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import fs from "node:fs";
import path from "node:path";
import type {
ChunkWithoutID,
ContextItem,
ContextSubmenuItem,
IDE,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getBasename } from "../util/index.js";
import {
getLanguageForFile,
getParserForFile,
supportedLanguages,
} from "../util/treeSitter.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types.js";
export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
artifactId = "codeSnippets";
constructor(private readonly ide: IDE) {}
private static async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
cacheKey TEXT NOT NULL,
content TEXT NOT NULL,
title TEXT NOT NULL,
startLine INTEGER NOT NULL,
endLine INTEGER NOT NULL
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
snippetId INTEGER NOT NULL,
FOREIGN KEY (snippetId) REFERENCES code_snippets (id)
)`);
}
private getQuerySource(filepath: string) {
const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""];
const sourcePath = path.join(
__dirname,
"..",
"tree-sitter",
"code-snippet-queries",
`tree-sitter-${fullLangName}-tags.scm`,
);
if (!fs.existsSync(sourcePath)) {
return "";
}
return fs.readFileSync(sourcePath).toString();
}
async getSnippetsInFile(
filepath: string,
contents: string,
): Promise<(ChunkWithoutID & { title: string })[]> {
const lang = await getLanguageForFile(filepath);
if (!lang) {
return [];
}
const parser = await getParserForFile(filepath);
if (!parser) {
return [];
}
const ast = parser.parse(contents);
const query = lang?.query(this.getQuerySource(filepath));
const matches = query?.matches(ast.rootNode);
return (
matches?.flatMap((match) => {
const node = match.captures[0].node;
const title = match.captures[1].node.text;
const results = {
title,
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
return results;
}) ?? []
);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await CodeSnippetsCodebaseIndex._createTables(db);
const tagString = tagToString(tag);
for (let i = 0; i < results.compute.length; i++) {
const compute = results.compute[i];
let snippets: (ChunkWithoutID & { title: string })[] = [];
try {
snippets = await this.getSnippetsInFile(
compute.path,
await this.ide.readFile(compute.path),
);
} catch (e) {
// If can't parse, assume malformatted code
}
// Add snippets to sqlite
for (const snippet of snippets) {
const { lastID } = await db.run(
"INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
[
compute.path,
compute.cacheKey,
snippet.content,
snippet.title,
snippet.startLine,
snippet.endLine,
],
);
await db.run(
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[lastID, tagString],
);
}
yield {
desc: `Indexing ${compute.path}`,
progress: i / results.compute.length,
status: "indexing",
};
markComplete([compute], IndexResultType.Compute);
}
for (let i = 0; i < results.del.length; i++) {
const del = results.del[i];
const deleted = await db.run(
"DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?",
[del.path, del.cacheKey],
);
await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [
deleted.lastID,
]);
markComplete([del], IndexResultType.Delete);
}
for (let i = 0; i < results.addTag.length; i++) {
const snippetsWithPath = await db.all(
"SELECT * FROM code_snippets WHERE cacheKey = ?",
[results.addTag[i].cacheKey],
);
for (const snippet of snippetsWithPath) {
await db.run(
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[snippet.id, tagString],
);
}
markComplete([results.addTag[i]], IndexResultType.AddTag);
}
for (let i = 0; i < results.removeTag.length; i++) {
const item = results.removeTag[i];
await db.run(
`
DELETE FROM code_snippets_tags
WHERE tag = ?
AND snippetId IN (
SELECT id FROM code_snippets
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, item.cacheKey, item.path],
);
markComplete([results.removeTag[i]], IndexResultType.RemoveTag);
}
}
static async getForId(id: number): Promise<ContextItem> {
const db = await SqliteDb.get();
const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]);
return {
name: row.title,
description: getBasename(row.path, 2),
content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``,
};
}
static async getAll(tag: IndexTag): Promise<ContextSubmenuItem[]> {
const db = await SqliteDb.get();
await CodeSnippetsCodebaseIndex._createTables(db);
try {
const rows = await db.all(
`SELECT cs.id, cs.path, cs.title
FROM code_snippets cs
JOIN code_snippets_tags cst ON cs.id = cst.snippetId
WHERE cst.tag = ?;
`,
[tagToString(tag)],
);
return rows.map((row) => ({
title: row.title,
description: getBasename(row.path, 2),
id: row.id.toString(),
}));
} catch (e) {
console.warn("Error getting all code snippets: ", e);
return [];
}
}
}