continue-custom/core/indexing/chunk/ChunkCodebaseIndex.ts
Nate Sesti 53b61288ec
🎨 Refactor core (#1281)
* 🎨 refactor out react context

* 🎨 refactor local storage

* 🎨 refactor IdeMessenger

* 🔥 removing unused files

* 🚚 move scripts

* ✅ setup VSCode integration testing

* 🎨 fix test-related stuff

* 🚧 testing

* 🎨 tweak terminal cmd+L

* 🧑‍💻 install biome in core

* 🎨 run biome check on core

* 🎨 run biome check in vscode

* 🎨 run biome check in binary

* 🧑‍💻 global biome config

* 🎨 run biome check on core

* 🎨 run biome check in vscode

* 🎨 fix a few biome warnings

* 🚧 WIP on protocols

* 🚧 progress, organizing, about to remove webviewCore protocol

* 🚧 now running

* 🚧 move indexing code to core

* 🚧 WIP on JetBrains indexing implementation

* 🎨 finish listDir

* 🚧 gui fixes

* 🏷️ update IMessenger.on return type

* 🐛 fix jetbrains types + IDE detection

* 🧑‍💻 set up debugging for binary with TcpMessenger

* 👷 fix prepackage.js

* 🧑‍💻 turn off debug mode for intellij

* 🐛 merge fixes

* 🐛 fixes after refactor

* 🐛 merge fixes

* 💄 increase font size in JB

* 🔀 merge changes

* 🩹 small fixes

* 🐛 fix jetbrains build

* 🩹 more jetbrains fixes

* 🎨 jetbrains improvements

* 🐛 fix lancedb prob in jetbrains build

* 👷 update jetbrains build process

* ✨ intellij problems context provider

* 👷 add script utils file

* 💚 fix jetbrains build regression

* 🎨 dynamic import transformers.js

* 🩹 small jetbrains updates

* ✨ folder context provider in jetbrains

* 🎨 many more jetbrains improvements

* 🔀 merge fixes

* ⚡️ small improvements

* 🎨 tell users transformers.js not supported

* 🎨 trial updates

* 📝 update jetbrains readmej

* ⚡️ only use smaller context for local autocomplete models

* ⚡️ improve bracket filter

* ✨ global .continue/.prompts folder

* 💄 improved model setup process

* 🥅 display VSCode req errs
2024-05-24 19:38:13 -07:00

168 lines
4.6 KiB
TypeScript

import { IContinueServerClient } from "../../continueServer/interface.js";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
import { MAX_CHUNK_SIZE } from "../../llm/constants.js";
import { getBasename } from "../../util/index.js";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "../types.js";
import { chunkDocument } from "./chunk.js";
export class ChunkCodebaseIndex implements CodebaseIndex {
static artifactId = "chunks";
artifactId: string = ChunkCodebaseIndex.artifactId;
constructor(
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient: IContinueServerClient,
) {
this.readFile = readFile;
}
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cacheKey TEXT NOT NULL,
path TEXT NOT NULL,
idx INTEGER NOT NULL,
startLine INTEGER NOT NULL,
endLine INTEGER NOT NULL,
content TEXT NOT NULL
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
)`);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);
const tagString = tagToString(tag);
async function handleChunk(chunk: Chunk) {
const { lastID } = await db.run(
"INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)",
[
chunk.digest,
chunk.filepath,
chunk.index,
chunk.startLine,
chunk.endLine,
chunk.content,
],
);
await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [
lastID,
tagString,
]);
}
// Check the remote cache
if (this.continueServerClient.connected) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
const resp = await this.continueServerClient.getFromIndexCache(
keys,
"chunks",
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
for (const chunk of chunks) {
await handleChunk(chunk);
}
}
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
} catch (e) {
console.error("Failed to fetch from remote cache: ", e);
}
}
// Compute chunks for new files
const contents = await Promise.all(
results.compute.map(({ path }) => this.readFile(path)),
);
for (let i = 0; i < results.compute.length; i++) {
const item = results.compute[i];
// Insert chunks
for await (const chunk of chunkDocument(
item.path,
contents[i],
MAX_CHUNK_SIZE,
item.cacheKey,
)) {
handleChunk(chunk);
}
yield {
progress: i / results.compute.length,
desc: `Chunking ${getBasename(item.path)}`,
status: "indexing",
};
markComplete([item], IndexResultType.Compute);
}
// Add tag
for (const item of results.addTag) {
const chunksWithPath = await db.all(
"SELECT * FROM chunks WHERE cacheKey = ?",
[item.cacheKey],
);
for (const chunk of chunksWithPath) {
await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [
chunk.id,
tagString,
]);
}
markComplete([item], IndexResultType.AddTag);
}
// Remove tag
for (const item of results.removeTag) {
await db.run(
`
DELETE FROM chunk_tags
WHERE tag = ?
AND chunkId IN (
SELECT id FROM chunks
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, item.cacheKey, item.path],
);
markComplete([item], IndexResultType.RemoveTag);
}
// Delete
for (const item of results.del) {
const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [
item.cacheKey,
]);
// Delete from chunk_tags
await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [
deleted.lastID,
]);
markComplete([item], IndexResultType.Delete);
}
}
}