continue-custom/core/indexing/CodeSnippetsIndex.ts
Nate Sesti 04c08c7159
dev (#1542)
* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
2024-06-28 16:21:36 -07:00

205 lines
5.8 KiB
TypeScript

import type {
ChunkWithoutID,
ContextItem,
ContextSubmenuItem,
IDE,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getBasename, getLastNPathParts } from "../util/index.js";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} 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 {
relativeExpectedTime: number = 1;
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)
)`);
}
async getSnippetsInFile(
filepath: string,
contents: string,
): Promise<(ChunkWithoutID & { title: string })[]> {
const parser = await getParserForFile(filepath);
if (!parser) {
return [];
}
const ast = parser.parse(contents);
const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets);
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: getLastNPathParts(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: getLastNPathParts(row.path, 2),
id: row.id.toString(),
}));
} catch (e) {
console.warn("Error getting all code snippets: ", e);
return [];
}
}
}